简体   繁体   中英

Django form.is_valid() is returning false everytime

I have created a django application. In that, when I click on update button on index.html page, it has to redirect to a webpage showing the form with 3 fields,(title,user, body). Everytime I click on update, the form is not validating. It is always returning false. Actually if we press on the update button, the user field should show the present user's id. But it is showing default value. The body field is becoming empty every time.

forms.py:

class ImmediateForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}),initial="Immediate",max_length=20)
class Meta:
    model = Immediate
    fields = ['title','user','body',]
    widgets = {
        'user': TextInput(attrs={'readonly': 'readonly'})
    }

Models.py:

class Immediate(models.Model):
title = models.CharField(default="Immediate",max_length=30)
user = models.ForeignKey(User, default=1,on_delete=models.CASCADE)
body = models.TextField(default="")

def __str__(self):
    return self.title

views.py:

def update_immediate(request,pk):
if not request.user.is_authenticated:
    return render(request, 'set_goals/index.html')
else:
    print(pk)
    try:
        if request.method=='POST' :
            print('Inside if')
        immediate = Immediate.objects.get(user_id=pk)
        form = ImmediateForm(request.POST or None, instance=immediate or None)
        if form.is_valid():
            print("no")
            immediate = form.save(commit=False)
            immediate.user = request.user.username
            immediate.body = form.cleaned_data['body']
            immediate.save()
            return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate})
        context = {
            "form": form,
        }
        return render(request, 'set_goals/create_template.html', context)
    except:
        if request.method=='POST' :
            print('Inside if')
        form = ImmediateForm(request.POST or None)
        if form.is_valid():
            print("yes")
            immediate = form.save(commit=False)
            immediate.user = request.user
            immediate.body = form.cleaned_data['body']
            immediate.save()
            return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate})
        context = {
            "form": form,
        }
        return render(request, 'set_goals/create_template.html', context)

And the html page where the button is:

index.html:

    <div class="col-md-6">
          <div class="card mb-4">
              <div class="card-header">
    Immediate
  </div>
            <img class="card-img-top" style="width:495px;height:400px;" src="" alt="Card image cap">
            <div class="card-body">
              <h2 class="card-title">Empty for now</h2>
              <p class="card-text"></p>
                <form class="form-horizontal" role="form" action="" method="POST" enctype="multipart/form-data">
                <a href="{% url 'set_goals:update_immediate' user.id %}" class="btn btn-primary">Update &rarr;</a>
              <a href="{% url 'set_goals:detail_immediate' user.id %}" class="btn btn-primary">Read More &rarr;</a>
              </form>
                </div>

</div>
            </div>

What is the mistake here? Why ImmediateForm() is not working? what should be done to correct this?

To debug this you can use form.errors before form.is_valid or immediately after. Then just output to the console and you look, in what a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM