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

1

6

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>
Fernandofernas answered 5/2, 2016 at 14:40 Comment(6)
But does your Category model have any data in there?Gobbledegook
Why do you pass the name of the category at form = TransactionForm(request.POST or None, initial={'category':category.name,})? Have you tried {'category':category}?Honna
@Shang Wang, Sure, there are records. for_debug variable passed successfully to the templateFernandofernas
I mean when you initialize the form at initial={'category':category.name,}. Try there with category (the instance) instead of category.name.Honna
@LostMyGlasses, you are damn great! Thanks for dabbin with finger! Please reply - I'll give a voteFernandofernas
Great! I'll post it as an answerHonna
H
6

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

Honna answered 5/2, 2016 at 15:6 Comment(1)
Just a warning, be careful of your browser's cache. In my case, It showed the previous selected item and wouldn't update. Wasted a lot of my time.Leeuwenhoek

© 2022 - 2024 — McMap. All rights reserved.