需要的结果:我的主要目的是获取用户添加电子邮件地址的访客登录,然后django检查数据库中的电子邮件,如果找到,则显示错误,否则用户被记录英寸
问题:在我添加电子邮件地址的格式中,Django会在数据库中添加电子邮件,但如果我再次添加该电子邮件,则不会显示错误,我也没有登录Django。< / p>
版本使用:
forms.py
from django import forms
from django.contrib.auth import get_user_model
User = get_user_model()
class GuestCheckoutForm(forms.Form):
email = forms.EmailField()
email2 = forms.EmailField(label='Verify Email')
def clean_email2(self):
email = self.cleaned_data.get("email")
email2 = self.cleaned_data.get("email2")
if email == email2:
user_exists = User.objects.filter(email=email).count()
if user_exists != 0:
raise forms.ValidationError("This User already exists. Please login instead.")
return email2
else:
raise forms.ValidationError("Please confirm emails are the same")
views.py
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic.base import View
from django.views.generic.detail import SingleObjectMixin, DetailView
from django.views.generic.edit import FormMixin
# Create your views here.
from orders.forms import GuestCheckoutForm
from orders.models import UserCheckout
from products.models import Variation
from .models import Cart, CartItem
class ItemCountView(View):
def get(self, request, *args, **kwargs):
if request.is_ajax():
cart_id = self.request.session.get("cart_id")
if cart_id == None:
count = 0
else:
cart = Cart.objects.get(id=cart_id)
count = cart.items.count()
request.session["cart_item_count"] = count
return JsonResponse({"count": count})
else:
raise Http404
class CartView(SingleObjectMixin, View):
model = Cart
template_name = "carts/view.html"
def get_object(self, *args, **kwargs):
self.request.session.set_expiry(0) #5 minutes
cart_id = self.request.session.get("cart_id")
if cart_id == None:
cart = Cart()
cart.save()
cart_id = cart.id
self.request.session["cart_id"] = cart_id
cart = Cart.objects.get(id=cart_id)
if self.request.user.is_authenticated():
cart.user = self.request.user
cart.save()
return cart
def get(self, request, *args, **kwargs):
cart = self.get_object()
item_id = request.GET.get("item")
delete_item = request.GET.get("delete", False)
item_added = False
if item_id:
item_instance = get_object_or_404(Variation, id=item_id)
qty = request.GET.get("qty", 1)
try:
if int(qty) < 1:
delete_item = True
except:
raise Http404
cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item_instance)
if created:
item_added = True
if delete_item:
cart_item.delete()
else:
cart_item.quantity = qty
cart_item.save()
if not request.is_ajax():
return HttpResponseRedirect(reverse("cart"))
#return cart_item.cart.get_absolute_url()
if request.is_ajax():
try:
total = cart_item.line_item_total
except:
total = None
try:
subtotal = cart_item.cart.subtotal
except:
subtotal = None
try:
cart_total = cart_item.cart.total
except:
cart_total = None
try:
tax_total = cart_item.cart.tax_total
except:
tax_total = None
try:
total_items = cart_item.cart.items.count()
except:
total_items = 0
data = {
"deleted": delete_item,
"item_added": item_added,
"line_total": total,
"subtotal": subtotal,
"cart_total": cart_total,
"tax_total": tax_total,
"total_items": total_items
}
return JsonResponse(data)
context = {
"object": self.get_object()
}
template = self.template_name
return render(request, template, context)
class CheckoutView(FormMixin, DetailView):
model = Cart
template_name = "carts/checkout_view.html"
form_class = GuestCheckoutForm
def get_object(self, *args, **kwargs):
cart_id = self.request.session.get("cart_id")
if cart_id == None:
return redirect("cart")
cart = Cart.objects.get(id=cart_id)
return cart
def get_context_data(self, *args, **kwargs):
context = super(CheckoutView, self).get_context_data(*args, **kwargs)
user_can_continue = False
user_check_id = self.request.session.get("user_checkout_id")
if not self.request.user.is_authenticated() or user_check_id == None:# or if request.user.is_guest:
context["login_form"] = AuthenticationForm()
context["next_url"] = self.request.build_absolute_uri()
elif self.request.user.is_authenticated() or user_check_id != None:
user_can_continue = True
else:
pass
context["user_can_continue"] = user_can_continue
context["form"] = self.get_form()
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
email = form.cleaned_data.get("email")
user_checkout, created = UserCheckout.objects.get_or_create(email=email)
request.session["user_checkout_id"] = user_checkout.id
print user_checkout
return self.form_valid(form)
else:
return self.form_invalid(form)
def get_success_url(self):
return reverse("checkout")
checkout_view.html
{% extends "base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content %}
{% if not user_can_continue %}
<div class='col-sm-6'>
<p class='lead'>Continue as Guest</p>
<form method='POST' action=''>{% csrf_token %}
{{ form|crispy }}
<input type='submit' class='btn btn-success' value='Continue as Guest' />
</form>
</div>
<div class='col-sm-6'>
<p class='lead'>Login to Continue</p>
<form method='POST' action="{% url 'auth_login' %}"> {% csrf_token %}
{{ login_form|crispy }}
<input type='hidden' name='next' value='{{ next_url }}' />
<input type='submit' class='btn btn-success' value='Login' />
</form>
<p class='text-center'>
<p>{% trans "Forgot password" %}? <a href="{% url 'auth_password_reset' %}">{% trans "Reset it" %}</a>!</p>
<p>{% trans "Not member" %}? <a href="{% url 'registration_register' %}">{% trans "Register" %}</a>!</p>
</p>
</div>
{% endif %}
{% endblock %}
models.py
from django.conf import settings
from django.db import models
# Create your models here.
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True) #not required
email = models.EmailField(unique=True) #--> required
def __unicode__(self): #def __str__(self):
return self.email
因此我没有收到任何错误,但上述问题正在发生
答案 0 :(得分:0)
django中的clean_*
方法应为always return the value
。
def clean_email2(self):
email = self.cleaned_data.get("email")
email2 = self.cleaned_data.get("email2")
if email == email2:
# Query your UserCheckout model. Not the auth one!
if UserCheckout.objects.filter(email=email).exists():
raise forms.ValidationError("This User already exists. Please login instead.")
else:
raise forms.ValidationError("Please confirm emails are the same")
return email2