我在解决该问题方面遇到麻烦...请帮助我摆脱这个错误...它还在打印值并且数据库表已经创建。以下是我的代码,错误提示类似异常值:
save()缺少1个必需的位置参数:“ self”
//This is my model.py file
rom django.db import models
class Reg(models.Model):
name = models.CharField(max_length=20)
//this is my form.py file
from django import forms
class RegistrationForm(forms.Form):
name = forms.CharField()
//this is my view.py file
from django.shortcuts import render
from .forms import RegistrationForm
from .models import Reg
def ragistration(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
Reg.name = form.cleaned_data.get('name')
Reg.save()
print(Reg.name)
else:
form = RegistrationForm()
return render(request, 'registration/reg.html', {"form": form})
//I got this error
Exception Value:
save() missing 1 required positional argument: 'self'
答案 0 :(得分:2)
您没有创建类Reg
的实例。试试这个
reg = Reg()
reg.name = form.cleaned_data.get('name')
reg.save()
答案 1 :(得分:1)
我们只必须在模型类的实例上调用save方法。我们可以使用模型表格来简化它。
from django import forms
from .models import Reg
class RegistrationForm(forms.ModelForm):
name = forms.CharField()
class Meta:
model = Reg
fields = '__all__'
from django.http import HttpResponse
from .forms import RegistrationForm
def ragistration(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("Object Saved")
else:
form = RegistrationForm()
return render(request, 'registration/reg.html', {"form": form})
答案 2 :(得分:0)
您可以在这里做几件事。
1:使用插入表格的模型表格
class RegistrationForm(forms.ModelForm):
class Meta:
model = Reg
fields = ['name']
2:在您看来,请注意form.is_valid()部分:
def ragistration(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
print(form.name)
else:
form = RegistrationForm()
return render(request, 'registration/reg.html', {"form": form})