Django: Add a new value to ModelChoiceField

187 Views Asked by At

I have a ModelChoiceField in a form that uses a TextInput widget. I want to be able to select a value from the database or add new entries to the database with this input. If the value is not already in the database, I get an error on the form that says "Select a valid choice. That choice is not one of the available choices."

Model

class FeedCategory(models.Model):
    category = models.CharField(max_length=255, unique=True)

class RssFeed(models.Model):
    category = models.ForeignKey(FeedCategory, null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=255)
    feed = models.URLField()

Form

class RssForm(forms.Form):
    name = forms.CharField()
    feed = forms.URLField()
    category = forms.ModelChoiceField(queryset=FeedCategory.objects.all(), to_field_name='category', widget=forms.TextInput())

    def clean(self):
         cleaned_data = super().clean()
         ????

Views

class RssCreateView(FormView):
     template_name = 'dashboard/rss_feed_form.html'
     form_class = RssForm
     success_url = '/dashboard/'

     def form_valid(self, form):
         name = form.cleaned_data['name']
         feed = form.cleaned_data['feed']
         category = form.cleaned_data['category']

         rss_obj = RssFeed(category=category, name=name, feed=feed)
         rss_obj.save()
          return super().form_valid(form)

Template

<form method="post">
   {%csrf_token%}
   {{form|crispy}}
   <button type="submit">Save</button>
</form>
1

There are 1 best solutions below

0
João Martins On

It might help you what I am using:

     category = models.ForeignKey("General.entity",verbose_name='Category', db_column="CategoryEntityRef", null=False, blank=False)

so, what I am doing with this is creating a field that points to an existing category that exists in another table. It will display it as a dropdown box. However using this method will allow me to have the option to add another Category: dropdownbox django