B
B
blackbb2017-04-26 21:31:51
Django
blackbb, 2017-04-26 21:31:51

How do I convert a ForeignKey field into a CharField in a Django form?

The site has a form to add an ad. The ad has a category field. And so this field now in the form of select, and CharField is necessary to me.

class Subcategory(models.Model):
    title = models.CharField(max_length=300, verbose_name=u'Подкатегории')
class Order(models.Model):
    title = models.CharField(max_length=200, verbose_name=u'Название')
    category = models.ForeignKey(Subcategory, verbose_name='Категория')

I did this in forms.py:
class AddOrderForm(forms.ModelForm):
    category = forms.CharField(max_length=300)
    class Meta:
        model = Order
        fields = '__all__'
        exclude = ['user','status','email','born','category']

In views.py I do this:
def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.email = self.request.user.email
        form.instance.category = self.request.POST['category']
        self.object = form.save()

When saving, it gives the error Cannot assign "u'\u0413\u0440\u0443\u0437\u043e\u043f\u0435\u0440\u0435\u0432\u043e\u0437\u043a\u0438, \u043b\u043e\u0433\u0438\u042 "Order.category" must be a "Subcategory" "instance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Burov, 2017-04-26
@blackbb

form.instance.category = get_object_or_404(Subcategory, title=self.request.POST['category'])

https://docs.djangoproject.com/en/1.11/topics/http...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question