1

I wanted to have a form which displays all Records of a model(Event) in a drop down list format. This is what I did.

models.py

class Event(models.Model):
    # All Fields
class AllEvents(models.Model):
    event = models.ForeignKey(Event,blank=False)

forms.py

class SelectEventForm(ModelForm):
    class Meta:
            model = AllEvents

views.py

def testView(request):
    if request.method == 'POST':
        selectEventForm = SelectEventForm(request.POST)
        if selectEventForm.is_valid():
            # do some logic
        else:
            # some problem in form

This is serving my purpose. But This is allowing null values to be passed on to views. As in, If I don't select anything from drop down, no form error is raised else condition is triggered in my views.py. Any help ?

user3490695
  • 139
  • 2
  • 13
  • Does applying [this solution](http://stackoverflow.com/a/1429646/771848) help? – alecxe Aug 04 '14 at 13:10
  • No, I've tried this stuff before. It still goes to views.py and executes the `else` part – user3490695 Aug 04 '14 at 13:19
  • I don't understand the problem exactly, the form is not valid because no event is selected and the else statement is executed, right? Isn't this the correct behavior? It's your responsibility to display the errors later on. What is it you try to achieve? Allow null values so that no error exists or display the error message? – ppetrid Aug 04 '14 at 16:05
  • Try with null=False in models.ForeignKey(Event,blank=False) or in class Meta: model = AllEvents Add fields = [event] – levi Aug 04 '14 at 16:24
  • @levi I've tried both, none works – user3490695 Aug 04 '14 at 19:02
  • @ppetrid If we have defined required = True and we submit without selecting anything then form errors should be raised automatically without our coding any stuff – user3490695 Aug 04 '14 at 19:03

0 Answers0