foreign key as initial value not passed to the ModelForm in django

為{幸葍}努か 提交于 2019-12-10 22:57:11

问题


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!

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!

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)

my urls.py:

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

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})

my forms.py:

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

my template:

<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>

回答1:


Try replacing

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

with

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

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



来源:https://stackoverflow.com/questions/35226793/foreign-key-as-initial-value-not-passed-to-the-modelform-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!