When adding a quote which must reffer to author id I get the bellow error: <QueryDict: {'csrfmiddlewaretoken': ['qcbbM4KsxyH5jIOZYUEY4sUzy63TylU1oBgVn8bNX9EAHDcnGvoO1k4Oq0Yy5f3C'], 'quote': ['gf'], 'author': ['']}>
Form is not valid:
By default the database connection is set to postgres, however for the quotes and authors I'm using MongoDB.
I would appreciate it if someone could point out my mistakes.
forms.py
class QuoteForm(ModelForm):
quote = CharField(max_length=50, widget=TextInput(attrs={"class": "form-control", "id": "exampleInputQuote1"}))
#tags = CharField(max_length=50, widget=TextInput(attrs={"class": "form-control", "id": "exampleInputQuote2"}))
author = ModelChoiceField(queryset=Author.objects.all(),
widget=Select(attrs={"class": "form-control", "id": "exampleInputQuote3"}))
models.py
class Quote(models.Model):
quote = models.TextField()
tags = models.ManyToManyField(Tag, blank=True, null=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE, default=None, null=True)
created_at = models.DateTimeField(auto_now_add=True)
add_quote.html
<div class="mb-3">
<label for="exampleInputQuote3" class="form-label">Author</label>
<select name="author" class="form-control" id="exampleInputQuote3" required="">
{% for author in authors %}
<option value="{{ author.pk }}">{{ author.fullname }}</option>
{% endfor %}
</select>
<div id="textHelp3" class="form-text">Quote Author.</div>
<span></span>
</div>
views.py
def add_quote(request):
db = get_mongodb()
authors = db.authors.find()
form = QuoteForm(instance=Quote())
if request.method == "POST":
form = QuoteForm(request.POST, instance=Quote())
print(request.POST)
if form.is_valid():
quote_text = form.cleaned_data['quote']
author_id = form.cleaned_data['author'].id
db.quotes.insert_one({"quote": quote_text, "author_id": author_id})
return redirect(to="quotes:root")
else:
print("Form is not valid:", form.errors)
return render(request, "quotes/add_quote.html", context={"form": form, "authors": authors})