外键作为初始值未传递到Django的ModelForm

外键作为初始值未传递到Django的ModelForm

本文介绍了外键作为初始值未传递到Django的ModelForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将ForeignKey的值(基于category_id)传递给ModelForm,但是它不起作用.我的字段仍然是"--------",并且没有从下拉字段中设置适当的值.类别的值必须为选中状态,并且其他值不得对用户隐藏.

I need to pass the value (based on category_id) for a ForeignKey to the ModelForm but it's not working. My field remains "--------" and proper value is not set from the drop-down field.Value for the Category must BE SELECTED and other values must be not hided from user to choice.

结果类别值成功传递到模板,但下拉字段类别未设置!

As the result category value successfuly passed to template but drop-down field Category not set!

我看到其他人通过ModelForm的构造函数解决了这个问题,但是我觉得必须有本地的django解决方案.

As I can see other guys solved it via constructor for ModelForm, but I feel there must be native django solution.

将感谢您提供任何解决方案!

Would be thankful for any solutions!

我的models.py:

my models.py:

class Category(models.Model):
    name = models.CharField('Name', max_length=20)
    icon = models.CharField('Icon', blank=True, max_length=20)

class Transaction(models.Model):
    type = models.CharField('Type', default='exp', max_length=20)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    note = models.CharField('Note', blank=True, max_length=20)

我的urls.py:

urlpatterns = [
url(r'^add/(?P<category_id>[0-9]+)', "core.views.add_trans_view", name='add_trans_url'),
]

我的views.py:

my views.py:

def add_trans_view(request, category_id):
    category = Category.objects.get(id=category_id)
    form = TransactionForm(request.POST or None, initial={'category':category.name,})
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return render(request,
            'core/transaction_form.html', {'form': form, 'for_debug':category})

我的forms.py:

my forms.py:

class TransactionForm(forms.ModelForm):
class Meta:
    model = Transaction
    fields = ['type', 'category', 'note']

我的模板:

<p>Initial 'category' value transfered from view:</p>
<h4>{{for_debug}}</h4>
<form method='POST' action=''> {% csrf_token %}
  {{form.as_p}}
  <input type='submit' value='Done'/>
</form>

推荐答案

尝试替换

form = TransactionForm(request.POST or None, initial={'category':category.name,})

使用

form = TransactionForm(request.POST or None, initial={'category':category,})

initial需要实例(category),而不仅仅是包含其名称(category.name)的字符串.

initial needs the instance (category), instead of only the string that contains its name (category.name).

这篇关于外键作为初始值未传递到Django的ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:02