C
C
Cyber_bober2016-10-26 11:25:54
Django
Cyber_bober, 2016-10-26 11:25:54

How to describe form fields if model data is linked via foreignkey?

Hi, some fields in the model are bound via foreignkey
//models.py

class Item(models.Model):
    ......
    category = models.ForeignKey(Category, verbose_name=u'Укажите категорию')
    ......

class Category(models.Model):
    name = models.CharField('Name', max_length=50)
    slug = models.SlugField('Slug')

How can I describe the fields in the form so that the form correctly enters data into the model?
//forms.py
class EditForm(forms.ModelForm):
    class Meta:
      model = Item
      fields = ('category', 'mode', 'type',  'delivery' )

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Lebedev, 2016-10-26
@Cyber_bober

class EditForm(forms.ModelForm):
    category = forms.ModelChoiceField(
        queryset=Category.objects.all(),
        label='Categories',
        widget=forms.Select()
    )

    class Meta:
      model = Item
      fields = ('category', 'mode', 'type',  'delivery' )

And, of course, do not forget to import Categoryfrom models.
Details here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question