Home > front end >  How to remove "this field is not required" in django?
How to remove "this field is not required" in django?

Time:07-17

I found posts with similar problem, but the solutions dont seem to work with me. Or maybe I am missing something.

I created a form in Django, but as a default it seems that every mandatory fields have this "this field is required" text above.

Ideally, I would like to have this only when someone tries to submit a form and a field is missing.

form.py

class ElderFlowerChampFormAdmin(ModelForm):
    fieldsets=[
            ("Look",{'fields':[
            ('look_colour','look_clarity','look_effervescence')]}),
        }

        widgets = {
                    'user': forms.Select(attrs={'class':'form-control','required':'True'}),
                    'look_colour':forms.Select(attrs={'class':'form-control','required':'True'}),

                }

view.py

def elderflowerchamp(request, product_id):
    global ChampageRating
    product = Product.objects.get(pk=product_id)
    url = request.META.get('HTTP_REFERER')
    submitted = False
    try:
        if request.method == "POST":
            reviews = ChampageRating.objects.get(pk=product_id)
            if request.user.is_superuser:
                form = ElderFlowerChampFormAdmin(request.POST, instance=reviews)
                if form.is_valid():
                        form.save()
                        return redirect('home')
            else:
                form = ElderFlowerChampForm(request.POST, instance=reviews)
                if form.is_valid():
                    ChampageRating = form.save(commit=False)
                    ChampageRating.user = request.user
                    ChampageRating.save()
                    return redirect('home')
        else:
            #This part goes to the page, but doesnt submit
            reviews = ChampageRating.objects.get(pk=product_id)
            if request.user.is_superuser:
                form = ElderFlowerChampFormAdmin
            else:
                form = ElderFlowerChampForm
            if 'submitted' in request.GET:
                submitted = True
    except:
        reviews = None
        if request.user.is_superuser:
            form = ElderFlowerChampFormAdmin(request.POST)
            if form.is_valid():
                    data = ChampageRating()
                    data.rating = form.cleaned_data['rating']
                    data.look_colour = form.cleaned_data['look_colour']
                    data.ip = request.META.get('REMOTE_ADDR')
                    data.product_id = product_id
                    data.user_id = request.user.id
                    data.save()
                    messages.success(request, 'Thank you! Your review has been submitted.')
                    return redirect('home')
        else:
            form = ElderFlowerChampForm(request.POST)
            if form.is_valid():
                    data = ChampageRating()
                    data.rating = form.cleaned_data['rating']
                    data.look_colour = form.cleaned_data['look_colour']
                    data.ip = request.META.get('REMOTE_ADDR')
                    data.product_id = product_id
                    data.user_id = request.user.id
                    data.save()
                    messages.success(request, 'Thank you! Your review has been submitted.')
                    return redirect('home')


    return render(request,"main/ElderFlowerReview.html", {'form':form, 'submitted':submitted,'reviews':reviews, 'product':product})

models.py

LOOKCOLOUR=(
    (1,'Straw'),
    (2,'Yellow'),
    (3,'Gold'),
    (4,'Amber'),
)

class ChampageRating(models.Model):
    user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE)
    product=models.ForeignKey(Product,related_name="champcomments", on_delete=models.CASCADE)
    look_colour=models.IntegerField(choices=LOOKCOLOUR, default=0)
   
    def __str__(self):
        return '%s - %s - %s'%(self.user, self.product, self.date_added)

Any ideasenter image description here

CodePudding user response:

something wrong on case request.GET here:

    if request.user.is_superuser:
        form = ElderFlowerChampFormAdmin
    else:
        form = ElderFlowerChampForm

You send the FormClass into the template context, and not the form instance.

Also see eror on the except case: If i have a GET, i should not render BoundedForm, here should be form.bounded = false (form is not bounded with any data). But you are always made the BoundedForm, with the request.POST data after error here:

reviews = ChampageRating.objects.get(pk=product_id)

My opinion is - you should try to read about Django-GCBV, it is better way to avoid complex errors, like in your question.

https://docs.djangoproject.com/en/4.0/topics/class-based-views/

  • Related