Home > front end >  Django ModelForm never passes is_valid()
Django ModelForm never passes is_valid()

Time:01-03

I'm new to Django and I am currently trying to store data entered from a form into a model/database. The bit which I think is causing the issue is that I don't want all the model fields accessible on the form. The model I have has the fields as follows:

    description = models.TextField()
    date_referred = models.DateTimeField(default=timezone.now)
    full_name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    phone_number = models.CharField(max_length=17, blank=True)
    column_number = models.IntegerField()
    notes = models.TextField()
    colour = models.CharField(max_length=6)
    user = models.ForeignKey(User, on_delete=models.CASCADE) 

The ModelForm I am using is as follows:

class ReferralForm(ModelForm):
    class Meta:
        model = kanban_item
        fields = ["item_name", "description", "full_name", "email", "phone_number"]

The code inside of the views.py file is this:

def submit_referrals(request):
    form = ReferralForm()
    if request.method == "POST":
        form = ReferralForm()
        print(request.POST)
        if form.is_valid():
            print("VALID")
            referral = form.save(commit=False)
            referral.user = request.user
            referral.column_number = 0
            referral.colour = "ffffff"
            referral.save()
        else :
            print ("NOT VALID")

As you can see, I am trying to create a model from the form then add the extra fields and then save the model to the database. This is not working as whenever I submit the form my code never gets past the is_valid method on the form.

Any suggestions or answers are appreciated as I am lost, thanks.

CodePudding user response:

You need to construct the ReferralForm with the data (request.POST) and probably also with the files (request.FILES).

A Form without data is called an "unbounded" form, and unbounded forms are always invalid. You thus create a form with data with:

def submit_referrals(request):
    form = ReferralForm()
    if request.method == "POST":
        form = ReferralForm(request.POST, request.FILES)  #            
  • Related