Answer the question
In order to leave comments, you need to log in
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='Категория')
class AddOrderForm(forms.ModelForm):
category = forms.CharField(max_length=300)
class Meta:
model = Order
fields = '__all__'
exclude = ['user','status','email','born','category']
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()
Answer the question
In order to leave comments, you need to log in
form.instance.category = get_object_or_404(Subcategory, title=self.request.POST['category'])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question