简体   繁体   English

客户匹配查询不存在 <- 这是什么以及为什么它在 form.is_valid() django 中触发

[英]costumer matching query does not exist <- what is this and why does it trigger in form.is_valid() django

I have a code this kind of registration form for my app that I am developing, I am just on my way to implement validation and this happened.我有一个代码,用于我正在开发的应用程序的注册表单,我正在实施验证的路上,这发生了。 在此处输入图像描述

I have no idea what is happening Here is my views.py我不知道发生了什么这是我的views.py

from django.http import HttpResponse
from django.shortcuts import render, redirect, get_list_or_404
from users.models import costumer
from .forms import costumer_forms


def home_view(request, *args, **kwargs):
    # return HttpResponse("<h1>Hello</h1>")
    username = "Hello"
    stat = "Hey"
    if request.method == "POST":
        email = request.POST.get("email")
        password = request.POST.get("password")
        obj = costumer.objects.get(email=email)
        stat = obj.check_password(password)
        if stat:
            return redirect('messenger', username=obj.username)
    context = {
        "name": username,
        "stat": stat,
    }
    return render(request, "home.html", context)



def register_form(request):
    
    # if request.method == "POST":
    
    form = costumer_forms(request.POST or None, request.FILES or None)
    request.session.flush()
    if form.is_valid():
        print("hello")
        form = costumer_forms()
    context={
        "form": form,
    }
    return render(request, "register.html", context)

def contact_view(request, username):
    obj = costumer.objects.get(username = username)
    context ={
        "obj": obj
    }
    return render(request, "product/detail.html", context)

Here is my forms.py这是我的 forms.py

from django import forms
from users.models import costumer

class costumer_forms(forms.Form):
    firstname = forms.CharField(required=True,
                widget=forms.TextInput(
                    attrs={
                        "type":"text",
                        "name":"firstname",
                        "placeholder": "Ex Juan"
                    }
                )
    )
    lastname = forms.CharField(required=True,
                widget=forms.TextInput(
                    attrs={
                        "type":"text",
                        "name":"lastname",
                        "placeholder": "Dela Cruz"
                    }
                )
    )
    username = forms.CharField(required=True,
                widget=forms.TextInput(
                    attrs={
                        "type":"text",
                        "name":"username",
                        "placeholder": "What should we call you?"
                    }
                )
    )
    email = forms.CharField(required=True,
                widget=forms.TextInput(
                    attrs={
                        "type":"email",
                        "name":"lastname",
                        "placeholder": "Dela Cruz"
                    }
                )
    )
    contact = forms.CharField(required=True,
                widget=forms.TextInput(
                    attrs={
                        "type":"number",
                        "name":"contact",
                        "placeholder": "997XXXXXXX"
                    }
                )
    )
    password = forms.CharField(required=True,
                widget=forms.TextInput(
                    attrs={
                        "type":"password",
                        "name":"password",
                        "placeholder": "Please Make Password as Secure as Possible"
                    }
                )
    )

    about = forms.CharField(required=False,
            widget=forms.Textarea(
                    attrs={
                        "placeholder": "Tell us something about you",
                        "rows": 20,
                        "cols":50,
                    }
                )
    )
    class Meta:
        model = costumer
        fields=[
            "firstname",
            "lastname",
            "username",
            "email",
            "password",
        ]
    def clean_username(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        if costumer.objects.get(email=username):
            raise forms.ValidationError("Username Already Exists!!!!")
        else: return username

    def clean_email(self, *args, **kwargs):
        email = self.cleaned_data.get("email")
        if ".com" not in email:
            raise forms.ValidationError("Invalid email")
        if costumer.objects.get(email=email):
            raise forms.ValidationError("Email Already Exists!!!!")
        return email

    def clean_password(self, *args, **kwargs):
        passw  = self.cleaned_data.get("password")
        cpassw = self.data.get("confirm_password")
        if passw != cpassw:
            raise forms.ValidationError("Password not match")

        if len(passw) < 8:
            raise forms.ValidationError("Minimum 8 Characters for Passwords ")
        
        if len(passw) > 15:
            raise forms.ValidationError("Maximum 15 Characters for Passwords ")
        return passw

    

Here is my registration.html这是我的注册。html

 {%extends 'base.html'%} {% load static %} {% block head%} <script src="{% static 'js/index.js' %}"></script> <link rel="stylesheet" href="{% static 'css/register.css'%}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"> {% endblock %} {% block content %} <div class="wrapper"> <br><br><br><br> <div class="form"> <h1>Form</h1> <form action="." method="POST">{% csrf_token %} {{ form.as_p }} <div class="inner"> <input type="submit" name="submit" value="Enter"> </div> </form> </div> </div> {% endblock %}

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
# Create your models here.


class costumer_base_manager(BaseUserManager):
    def create_user(self, email, username,firstname, lastname, password, contact, **other_fields):
        if not email:
            raise ValueError("Please provide email")
        email = self.normalize_email(email)
        user  = self.model(email=email, username=username, firstname=firstname, lastname=lastname, password=password,contact=contact, **other_fields)
        print(password)
        user.set_password(password)
        print(password)
        user.save()
        return user
    def create_superuser(self, email, username,firstname, lastname, password, contact, **other_fields):
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)
        if other_fields.get('is_staff') is not True:
            raise ValueError('Superuser must assign is_staff = True')
        
        return self.create_user(email, username, firstname, lastname, password, contact, **other_fields)



class costumer(AbstractBaseUser, PermissionsMixin):
    email           = models.EmailField(_("email"),unique=True, blank=False)
    username       = models.CharField(max_length=100, unique=True, blank=False)
    firstname       = models.CharField(max_length=100, blank=False)
    lastname       = models.CharField(max_length=120, blank=False)
    start_date      = models.DateTimeField(default=timezone.now)
    about           = models.TextField(_("about me"), max_length=500, blank=True)
    investing_style = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(3)])
    contact         = models.PositiveIntegerField(default=0,validators=[MinValueValidator(9000000001), MaxValueValidator(9999999999)])
    is_active       = models.BooleanField(default=False)
    is_staff        = models.BooleanField(default=False)

    objects = costumer_base_manager()
    USERNAME_FIELD  = 'email'
    REQUIRED_FIELDS = ['username', 'firstname', 'lastname', 'contact']

    def __str__(self):
        return self.username

I really have no idea what is happening.我真的不知道发生了什么。 I would really appreciate if someobe could tell me about some insights on this problems如果有人能告诉我有关此问题的一些见解,我将不胜感激

Here is the full description of the problem:以下是问题的完整描述:

   Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/sign-up/

Django Version: 3.2
Python Version: 3.9.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'products',
 'dashboard',
 'pages',
 'users']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\ASUS\Desktop\Development\Django\src\finbot\pages\views.py", line 32, in register_form
    if form.is_valid():
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\forms\forms.py", line 175, in is_valid
    return self.is_bound and not self.errors
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\forms\forms.py", line 170, in errors
    self.full_clean()
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\forms\forms.py", line 372, in full_clean
    self._clean_fields()
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\forms\forms.py", line 393, in _clean_fields
    value = getattr(self, 'clean_%s' % name)()
  File "C:\Users\ASUS\Desktop\Development\Django\src\finbot\pages\forms.py", line 80, in clean_username
    if costumer.objects.get(email=username):
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\ASUS\Desktop\Development\Django\venv\lib\site-packages\django\db\models\query.py", line 435, in get
    raise self.model.DoesNotExist(

Exception Type: DoesNotExist at /sign-up/
Exception Value: costumer matching query does not exist.

I am new to Django, but I would like to ask why are you referring the same form again inside the if form.is_valid condition?我是 Django 的新手,但我想问一下你为什么在 if form.is_valid条件中再次引用相同的表单? From my experience the form should be called before that condition and I dont think there is any need to assign same form variable inside again.根据我的经验,应该在该条件之前调用表单,我认为没有必要再次在内部分配相同的表单变量。

def register_view(request):
    context = {}

    form = yourform(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        user = form.cleaned_data.get('username')
        messages.success(request, 'Account was created for '+ user)
        
        #name of page you want to be redirected to after regitration.
        return redirect('login')
     context['form'] = form

     return render(request, 'yourtemplatename.html', context)

Yow, zup all.哎呀,都搞定了。 As it turns out the reason that I have been receiving the error is that I have not handled my queries inside the cleaning functions properly.事实证明,我收到错误的原因是我没有正确处理清洁功能中的查询。 We can take the clean_email() as an example.我们可以以 clean_email() 为例。

 def clean_email(self, *args, **kwargs):
        email = self.cleaned_data.get("email")
        if ".com" not in email:
            raise forms.ValidationError("Invalid email")
        if costumer.objects.get(email=email):
            raise forms.ValidationError("Email Already Exists!!!!")
        return email

as it turns out the class form runs all of the cleaning function when is_valid() is called however as you can see in the function I have this little quirky line costumer.objects.get(email=email) that is supposed to check whether the email already exists or not. as it turns out the class form runs all of the cleaning function when is_valid() is called however as you can see in the function I have this little quirky line costumer.objects.get(email=email) that is supposed to check whether the email 是否已经存在。 This will work given that the email already exists and raising a validation error in return.鉴于 email 已经存在并引发验证错误,这将起作用。 However, the code breaks when the email is new popping an error that is akin to a SQL error when you are getting non-existent data from the database, similar to what is happening here.但是,当您从数据库中获取不存在的数据时,当 email 新弹出一个类似于 SQL 错误的错误时,代码会中断,类似于此处发生的情况。 So as a fix I need to have a piece of code that will serve as a handler to my data.因此,作为修复,我需要一段代码来处理我的数据。

try:
    error = costumer.objects.get(email=email)
except costumer.DoesNotExist:  
    return email

This is to use a try-except method, which will handle the query errors the way we wanted to.这是使用 try-except 方法,它将按照我们想要的方式处理查询错误。 After I have done this my system is now running smoothly.完成此操作后,我的系统现在运行顺利。 I hate myself我恨我自己

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM