Hi
I’m new to django and have been building upon the polls application for a personal project.
This issue that I have, as the title suggests, is that my use of InlineFormSet within admin isn’t saving to the database. I feel like it is my solution for having a pre-populated TubularInLine fields within my polls choice model so that I don’t have to manually input 2 choices into my poll every time a poll is created. It would seem that the use of InlineFormSet will allow me to have 2 constant options in these fields.
The goal is that the user is able to enter a date, hit submit and then the poll is generated with the choices being automatically set to ‘yay’ / ‘nay’
When I’m creating the poll via the form in my application, everything is working at is should with the poll being generated client-side and within admin.
Within admin, the fields are being populated with ‘Yay’ and ‘Nay’ as desired, however, they aren’t being saved to the database and therefor, not being rendered as possible selections within my poll.
Please forgive me if any of this is confusing…
Any help with this would be massively appreciated. Thank you.
models.py
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200, null=True, blank=True)
votes = models.IntegerField(default=0, null=True, blank=True)
def __str__(self):
return self.choice_text
admin.py
class ChoiceInLineFormset(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
kwargs['initial'] = [
{'choice_text': 'Yay'}, {'choice_text': 'Nay'}
]
super(ChoiceInLineFormset, self).__init__(*args, **kwargs)
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 2
max_num = 2
formset = ChoiceInLineFormset
views.py
@login_required(login_url="/")
def createPoll(request, *args, **kwargs):
form = QuestionForm()
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
form.save()
return redirect('/polls/')
context = {'form': form}
return render(request, 'polls/poll-form.html', context)
forms.py
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = ['question_text']
widgets = {
'question_text': forms.TextInput(attrs={'placeholder': 'Date: xx/xx/xxxx'}),
}
Thanks