简体   繁体   中英

Django Form Not Saving the Data

I've imported this from django.contrib.auth.forms import UserCreationForm used csrf_token in the form but still when I hit submit the page reloads but doesn't save the data to database.

def signup(req):
    if req.method == 'POST':
        form = UserCreationForm(req.POST)
        if form.is_valid():
            form.save()
    form = UserCreationForm()
    reg_con={
        'regform': form
    }
    return render(req, 'signup.html', reg_con)

form

<form action="." method="POST">
    {% csrf_token %}
    {{ regform.as_ul }}
    <input type="submit" value="Sign Up">
</form>

Try removing the action attribute from your form tag. Also don't forget to redirect after calling form.save()

This is normally because something is wrong with your form the problem is however that you each time construct a new form, and you thus can not see what went wrong. You should only create a new form in case it is a GET request, so:

def signup(req):
    if req.method == 'POST':
        form = UserCreationForm(req.POST)
        if form.is_valid():
            form.save()
    :
        form = UserCreationForm()
    reg_con={
        'regform': form
    }
    return render(req, 'signup.html', reg_con)

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