目的:当提交 django 表单以将数据发送并保存到管理端时。问题:我可以在提交表单后将其重定向到另一个页面,但是当我进入管理端时,数据不会保存。我怎样才能解决这个问题?使用 Django 还是 JavaScript?html: <form method="post" > {% csrf_token %} {{form.as_p}} <input class="btn" type="submit" value="Log In"> </form>models.py: from django.db import models from django import forms class Customer(models.Model): first_name = models.CharField(max_length=200, verbose_name='') last_name = models.CharField( max_length=200, verbose_name='') def __str__(self): return self.first_name + ', ' + self.last_nameforms.py: from django.forms import ModelForm from django import forms from .models import Customer class CustomerForm(ModelForm): class Meta: model = Customer fields = '__all__'views.py:from django.shortcuts import renderfrom .forms import CustomerFormdef index(request): form = CustomerForm() if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'app/index.html', context)
3 回答
明月笑刀无情
TA贡献1828条经验 获得超4个赞
将 html 更改为 method="POST"
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
return redirect('urlname')
else:
form = CustomerForm()
context = {'form': form}
return render(request, 'app/index.html', context)
添加回答
举报
0/150
提交
取消