Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 模板上不显示表单错误_Python_Django - Fatal编程技术网

Python 模板上不显示表单错误

Python 模板上不显示表单错误,python,django,Python,Django,没有任何验证错误显示,如果出现错误,模板页面将刷新。我把验证错误代码放在了我的forms.py中,我不知道是否应该把它放在我的视图中,因为什么都不起作用。我还认为django有一个默认错误,似乎我错了 html views.py def addpatient(request): form = PatientForm(request.POST) if form.is_valid(): user = form.save() user.refresh_f

没有任何验证错误显示,如果出现错误,模板页面将刷新。我把验证错误代码放在了我的forms.py中,我不知道是否应该把它放在我的视图中,因为什么都不起作用。我还认为django有一个默认错误,似乎我错了

html

views.py

def addpatient(request):
    form = PatientForm(request.POST)
    if form.is_valid():
        user = form.save()
        user.refresh_from_db()
        user.profile.first_name = form.cleaned_data.get('first_name')
        user.profile.last_name = form.cleaned_data.get('last_name')
        user.profile.email = form.cleaned_data.get('email')
        user.profile.state = form.cleaned_data.get('state')
        user.profile.dob = form.cleaned_data.get('dob')
        user.profile.next_of_kin = form.cleaned_data.get('next_of_kin')
        user.profile.address = form.cleaned_data.get('address')
        user.profile.phonenumber = form.cleaned_data.get('phonenumber')
        user.is_active = True

        user.save()


        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password1')
        messages.success(request, 'Account was created for ' + username)
        user = authenticate(username=username, password=password)
        print(username, password, user)
        login(request, user)
        return redirect(f'/dashboard/profile/{user.profile.slug}/{user.pk}')
    else:
        form = PatientForm()
    return render(request, 'core/addpatient.html', {'form': form})

我认为问题出在您的
views.py
文件中,特别是检查表单是否有效

在POST中,检查表单是否有效,如果无效,则创建一个新表单并将其作为contaxt to render方法传递

如果form.is_有效():
#如果表格是有效的,你会怎么做
其他:
#每次表单无效时都会执行此操作
#如果表单无效,这将创建一个新表单并返回它,而不是现有表单。
form=PatientForm()
返回呈现(请求'core/addpatient.html',{'form':form})
您可以通过删除
else
子句并返回表单而不创建新表单来解决问题。像这样的

form=PatientForm(request.POST)
如果form.is_有效():
#如果东西
返回呈现(请求'core/addpatient.html',{'form':form})
您可以通过如下操作检查方法是否为“POST”

def添加患者(请求):
if request.method==“POST”
表单=PatientForm(request.POST)
如果form.is_有效():
#如果形式有效的话
返回呈现(请求'core/addpatient.html',{'form':form})
#在get方法的情况下执行此操作
form=PatientForm()
返回呈现(请求'core/addpatient.html',{'form':form})
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class PatientForm(UserCreationForm):
    first_name = forms.CharField(max_length=100, help_text='First Name')
    last_name = forms.CharField(max_length=100, help_text='Last Name')
    address = forms.CharField(max_length=100, help_text='address')
    next_of_kin = forms.CharField(max_length=100, help_text='Next of kin')
    dob = forms.CharField(max_length=100, help_text='Date of birth')
    state = forms.CharField(max_length=100, help_text='State')
    phonenumber = forms.CharField(
        max_length=100, help_text='Enter Phone number')
    email = forms.EmailField(max_length=150, help_text='Email')
    
    

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update(
        {'placeholder': ('Username')})
        self.fields['email'].widget.attrs.update(
        {'placeholder': ('Email')})
        self.fields['address'].widget.attrs.update(
            {'placeholder': ('Address')})
        self.fields['phonenumber'].widget.attrs.update(
            {'placeholder': ('Phone number')})
        self.fields['first_name'].widget.attrs.update(
            {'placeholder': ('First name')})
        self.fields['last_name'].widget.attrs.update(
            {'placeholder': ('Last name')})
        
        

        self.fields['password1'].widget.attrs.update({'placeholder': ('Password')})
        self.fields['password2'].widget.attrs.update({'placeholder': ('Repeat password')})
        self.fields['dob'].widget.attrs.update({'placeholder': ('Date of birth')})
        self.fields['state'].widget.attrs.update({'placeholder': ('State')})
        self.fields['next_of_kin'].widget.attrs.update({'placeholder': ('Next of kin')})
        self.fields['first_name'].widget.attrs.update({'class': 'log'})
        self.fields['last_name'].widget.attrs.update({'class': 'log'})
        self.fields['email'].widget.attrs.update({'class': 'log'})
        self.fields['phonenumber'].widget.attrs.update({'class': 'log'})
        self.fields['address'].widget.attrs.update({'class': 'log'})
        self.fields['dob'].widget.attrs.update({'class': 'log'})
        self.fields['state'].widget.attrs.update({'class': 'log'})
        self.fields['next_of_kin'].widget.attrs.update({'class': 'log'})
        self.fields['username'].widget.attrs.update({'class': 'log'})
        self.fields['password1'].widget.attrs.update({'class': 'log swiy'})
        self.fields['password2'].widget.attrs.update({'class': 'log swiy'})

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'phonenumber',
                  'email', 'password1', 'password2', 'address','dob','state','next_of_kin')
    def clean(self):
        cleaned_data = super(PatientForm, self).clean()
        password = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')
        if password != password2:
            raise forms.ValidationError('Passwords do not match!')
    
    # Add this to check if the email already exists in your database or not

    def clean_email(self):
        username = self.cleaned_data.get('username')
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exclude(username=username).count():
            raise forms.ValidationError('This email is already in use! Try another email.')
        return email
       
     # Add this to check if the username already exists in your database or not     
    def clean_username(self):
        username = self.cleaned_data.get('username')
        email=self.cleaned_data.get('email')
        if username and User.objects.filter(username=username).exclude(email=email).count():
            raise forms.ValidationError('This username has already been taken!')
        return username 
def addpatient(request):
    form = PatientForm(request.POST)
    if form.is_valid():
        user = form.save()
        user.refresh_from_db()
        user.profile.first_name = form.cleaned_data.get('first_name')
        user.profile.last_name = form.cleaned_data.get('last_name')
        user.profile.email = form.cleaned_data.get('email')
        user.profile.state = form.cleaned_data.get('state')
        user.profile.dob = form.cleaned_data.get('dob')
        user.profile.next_of_kin = form.cleaned_data.get('next_of_kin')
        user.profile.address = form.cleaned_data.get('address')
        user.profile.phonenumber = form.cleaned_data.get('phonenumber')
        user.is_active = True

        user.save()


        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password1')
        messages.success(request, 'Account was created for ' + username)
        user = authenticate(username=username, password=password)
        print(username, password, user)
        login(request, user)
        return redirect(f'/dashboard/profile/{user.profile.slug}/{user.pk}')
    else:
        form = PatientForm()
    return render(request, 'core/addpatient.html', {'form': form})