Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - when i refresh the page the form data automatically adding due to GET method when i remove it it show doesn't return httpresponse obj

how can i use is_valid() with POST method to get inputs from user my views.py i also use return redirect() and HttpResponseRedirect() but it doesn't work

@login_required
def about(request):
    data= userdata.objects.all()
    form=student(request.POST) 
    if  request.method =='POST' or 'GET':
        if form.is_valid():
            name = request.POST.get('name')
            email= request.POST.get('email')
            password =request.POST.get('password')
            fm = userdata(name=name,email=email,password=password)
            fm.save()
            form =student()
        else:
            form=student()
            

        return render(request,'about.html',{'form':form ,'data':data})
question from:https://stackoverflow.com/questions/65560019/when-i-refresh-the-page-the-form-data-automatically-adding-due-to-get-method-whe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try the code below

@login_required
def about(request):

    # i think you don't need 'data' and thus pass it in the context with 'form'
    # data= userdata.objects.all()

    if  request.method =='POST':  # POST request

        form=student(request.POST) 

        if form.is_valid():

            name = request.POST.get('name')
            email= request.POST.get('email')
            password = request.POST.get('password')

            fm = userdata(name=name,email=email,password=password)

            fm.save()

            # Add flash message and then redirect 
            messages.success(request, 'SUCCESS !')
            return redirect(reverse_lazy('home'))

        else:
            messages.error(request, 'Please correct the errors below.')
            #  if 'form.is_valid()' return false you will get all errors in 'form.errors' bag
            
    else:  # GET request
        form=student()

    return render(request,'about.html',{'form':form})

refer to :


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...