Home > Software design >  Django Validation is working on django admin but not working on html template
Django Validation is working on django admin but not working on html template

Time:12-09

I'm creating a form where if we register it should save data to the database if the form is valid. otherwise, it should raise an error but it doesn't save data to the database, and also some fields are required but if I submit the form it doesn't even raise the error field is required. but if I register it manually on Django admin pannel it works perfectly fine.

here is my model:

class foodlancer(models.Model):
    Your_Name = models.CharField(max_length=50)
    Kitchen_Name = models.CharField(max_length=50)
    Email_Address = models.EmailField(max_length=50)
    Street_Address = models.CharField(max_length=50)
    City = models.CharField(max_length=5)
    phone = PhoneNumberField(null=False, blank=False, unique=True)
    
    def __str__(self):
        return f'{self.Your_Name}'

also, I disabled html5 validation

forms.py

class FoodlancerRegistration(forms.ModelForm):
    phone = forms.CharField(widget=PhoneNumberPrefixWidget(initial="US"))

    class Meta:
        model = foodlancer
        fields = "__all__"

views.py:

def apply_foodlancer(request):
    form = FoodlancerRegistration()
    return render(request, 'appy_foodlancer.html', {"form": form})

and finally Django template

<form method="POST" novalidate>
   {% csrf_token %}
   {{ form.as_p }}
   <button type="submit" >Submit</button>

</form>

Thank you for your time/help

CodePudding user response:

You don't have any form saving logic in your view. Try something like this:

def apply_foodlancer(request):
  if request.method == 'POST':
    form = FoodlancerRegistration(data=request.POST)
    if form.is_valid(): # if it's not valid, error messages are shown in the form
       form.save()
       # redirect to some successpage or so
       return HttpResponse("<h1>Success!</h1>")
  else:
    # make sure to present a new form when called with GET
    form = FoodlancerRegistration()
  return render(request, 'appy_foodlancer.html', {"form": form})

Also check that the method of your form in your HTML file is post. I'm not sure if POST also works. Avoid defining fields in a modelform with __all__. It's less secure, as written in the docs

  • Related