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


i need pass value (based on category_id) foreignkey modelform it's not working. field remains "--------" , proper value not set drop-down field. value category must selected , other values must not hided user choice.

as result category value successfuly passed template drop-down field category not set!

as can see other guys solved via constructor modelform, feel there must native django solution.

would thankful 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 view:</p> <h4>{{for_debug}}</h4> <form method='post' action=''> {% csrf_token %}   {{form.as_p}}   <input type='submit' value='done'/>     </form> 

try replacing

form = transactionform(request.post or none, initial={'category':category.name,}) 

with

form = transactionform(request.post or none, initial={'category':category,}) 

initial needs instance (category), instead of string contains name (category.name).


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -