这是完整的代码。当我尝试构建登录和注册表单时发生此错误!
错误`
AttributeError at /menu/register/
'function' object has no attribute 'objects'
Request Method: POST
Request URL: http://127.0.0.1:8000/menu/register/
Django Version: 1.11
Exception Type: AttributeError
Exception Value:
'function' object has no attribute 'objects'
Exception Location: /Users/ambuj/Documents/GitHub/TrailPOS/pos/menu/forms.py in clean_username, line 70
Python Executable: /usr/bin/python
Python Version: 2.7.10
Python Path:
['/Users/ambuj/Documents/GitHub/TrailPOS/pos',
'/Library/Python/2.7/site-packages/Django-1.11-py2.7.egg',
'/Library/Python/2.7/site-packages/twilio-6.3.dev0-py2.7.egg',
'/Library/Python/2.7/site-packages/httplib2-0.10.3-py2.7.egg',
'/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/Library/Python/2.7/site-packages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC']
Server time: Wed, 14 Jun 2017 10:44:22 +0000`
我的views.py
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404
from django.views.generic import DetailView, ListView, CreateView, UpdateView, DeleteView
from .models import dish
from django.core.urlresolvers import reverse_lazy
from .mixins import FormUserNeededMixin
from .mixins import UserOwnerMixin
from .models import category
from .models import discount
from .models import tax
from .models import Cash
from .models import Order
from .forms import dishModelForm
from .forms import categoryModelForm
from .forms import discountModelForm
from .forms import taxModelForm
from .forms import UserRegisterModelForm
import logging
from django.http import HttpResponse
from django.template import loader
from django.core.exceptions import MultipleObjectsReturned
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import FormView
import json
# Create your views here.
User = get_user_model()
discList = {}
taxList = {}
class UserRegisterView(FormView):
template_name = 'menu/user_register.html'
form_class = UserRegisterModelForm
success_url = '/login'
def form_valid(self, form):
username = form.cleaned_data.get("username")
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
new_user = User.objects.create(username=username, email=email)
new_user.set_password(password)
new_user.save()
return super(UserRegisterView, self).form_valid(form)
class DiscountListView(LoginRequiredMixin, ListView):
queryset = discount.objects.all()
def get_context_data(self, *args, **kwargs):
context = super(DiscountListView, self).get_context_data(*args, **kwargs)
return context
class DiscountCreateView(LoginRequiredMixin, UserOwnerMixin, CreateView):
form_class = discountModelForm
template_name = 'menu/adddiscount.html'
success_url = "/menu/create_discount/"
def form_valid(self, form):
form.instance.user = self.request.user
return super(DiscountCreateView, self).form_valid(form)
class DiscountDetailView(LoginRequiredMixin, DetailView):
queryset = discount.objects.all()
class DiscountUpdateView(LoginRequiredMixin, UserOwnerMixin, UpdateView):
queryset = discount.objects.all()
form_class = discountModelForm
template_name = 'menu/discount_update.html'
success_url = reverse_lazy("discount_list")
class DiscountDeleteView(LoginRequiredMixin, UserOwnerMixin, DeleteView):
model = discount
template_name = 'menu/delete_confirm.html'
success_url = reverse_lazy("discount_list")
class CategoryDetailView(LoginRequiredMixin, DetailView):
queryset = category.objects.all()
class CategoryCreateView(LoginRequiredMixin, UserOwnerMixin, CreateView):
form_class = categoryModelForm
template_name = 'menu/addcategory.html'
success_url = "/menu/create_category/"
def form_valid(self, form):
form.instance.user = self.request.user
return super(CategoryCreateView, self).form_valid(form)
class CategoryListView(LoginRequiredMixin, ListView):
queryset = category.objects.all()
def get_context_data(self, *args, **kwargs):
context = super(CategoryListView, self).get_context_data(*args, **kwargs)
return context
class CategoryUpdateView(LoginRequiredMixin, UserOwnerMixin, UpdateView):
queryset = category.objects.all()
form_class = categoryModelForm
template_name = 'menu/category_update.html'
success_url = reverse_lazy("category_list")
class CategoryDeleteView(LoginRequiredMixin, UserOwnerMixin, DeleteView):
model = category
template_name = 'menu/delete_confirm.html'
success_url = reverse_lazy("category_list")
class DishCreateView(LoginRequiredMixin, UserOwnerMixin, FormUserNeededMixin, CreateView):
form_class = dishModelForm
template_name = 'menu/adddish.html'
success_url = "/menu/dishes/"
def form_valid(self, form):
form.instance.user = self.request.user
return super(DishCreateView, self).form_valid(form)
class DishDetailView(LoginRequiredMixin, DetailView):
queryset = dish.objects.all()
#def get_object(self):
# print(self.kwargs)
# pk = self.kwargs.get("pk")
# obj = get_object_or_404(dish, pk=pk)
# return obj
class DishListView(LoginRequiredMixin, ListView):
queryset = dish.objects.all()
def get_context_data(self, *args, **kwargs):
context = super(DishListView, self).get_context_data(*args, **kwargs)
return context
class DishUpdateView(LoginRequiredMixin, UserOwnerMixin, UpdateView):
queryset = dish.objects.all()
form_class = dishModelForm
template_name = 'menu/dish_update.html'
success_url = reverse_lazy("dish_list")
class DishDeleteView(LoginRequiredMixin, UserOwnerMixin, DeleteView):
model = dish
template_name = 'menu/delete_confirm.html'
success_url = reverse_lazy("dish_list")
class TaxCreateView(LoginRequiredMixin, UserOwnerMixin, CreateView):
form_class = taxModelForm
template_name = 'menu/addtax.html'
success_url = "/menu/create_tax/"
def form_valid(self, form):
form.instance.user = self.request.user
return super(TaxCreateView, self).form_valid(form)
class TaxListView(LoginRequiredMixin, ListView):
queryset = tax.objects.all()
def get_context_data(self, *args, **kwargs):
context = super(TaxListView, self).get_context_data(*args, **kwargs)
return context
class TaxDetailView(LoginRequiredMixin, DetailView):
queryset = tax.objects.all()
class TaxUpdateView(LoginRequiredMixin, UserOwnerMixin, UpdateView):
queryset = tax.objects.all()
form_class = taxModelForm
template_name = 'menu/tax_update.html'
success_url = reverse_lazy("tax_list")
class TaxDeleteView(LoginRequiredMixin, UserOwnerMixin, DeleteView):
model = tax
template_name = 'menu/delete_confirm.html'
success_url = reverse_lazy("tax_list")
def order(request):
product_list = dish.objects.all
template = loader.get_template('menu/order.html')
context = {
'product_list': product_list,
}
return HttpResponse(template.render(context, request))
def addition(request, operation):
cash,_ = Cash.objects.get_or_create(id=0)
succesfully_payed = False
payment_error = False
amountAdded = 0
try:
currentOrder,_ = Order.objects.get_or_create(order_user=request.user.username)
except MultipleObjectsReturned:
currentOrder = list(Order.objects.filter(order_user=request.user.username))[0]
logging.warn("there were MultipleObjectsReturned")
if currentOrder is None:
raise Exception("current Order is empty")
if operation:
if operation.isdecimal():
tmplist = json.loads(currentOrder.order_list)
tmpproduct = dish.objects.get(pk=operation)
tmpdiscount = discount.objects.get(discountDish=tmpproduct)
if tmpdiscount.discountApp:
sub = tmpdiscount.discountRate
sub = Decimal(sub / 100) * tmpproduct.dishFullPrice
else:
sub = 0
tmptax = tax.objects.get(taxDish=tmpproduct)
if tmptax.taxApp:
add = tmptax.taxRate
add = Decimal(add / 100) * tmpproduct.dishFullPrice
else:
add = 0
tmplist.append(tmpproduct.dishName)
currentOrder.order_list = json.dumps(tmplist)
currentOrder.order_totalprice = currentOrder.order_totalprice + tmpproduct.dishFullPrice - Decimal(sub) + Decimal(add)
if not tmpdiscount.discountApp:
bd = tmpdiscount.discountRate
bd = Decimal(bd / 100) * currentOrder.order_totalprice
currentOrder.order_totalprice = currentOrder.order_totalprice -bd
discList[tmpdiscount.discountName] = tmpdiscount.discountRate
tmptax = tax.objects.get(taxDish=tmpproduct)
if not tmptax.taxApp:
bt = tmptax.taxRate
bt = Decimal(bt / 100) * tmpproduct.dishFullPrice
currentOrder.order_totalprice = currentOrder.order_totalprice + bt
taxList[tmptax.taxName] = tmptax.taxRate
currentOrder.save()
elif operation == "reset":
currentOrder.order_list = json.dumps(list())
currentOrder.order_totalprice = 0
discList.clear()
taxList.clear()
currentOrder.save()
elif operation == "payed":
for x in json.loads(currentOrder.order_list):
tmpproduct = dish.objects.get(dishName=x)
tmpproduct.save()
cash.cash_amount = cash.cash_amount + tmpproduct.dishFullPrice
amountAdded = amountAdded + tmpproduct.dishFullPrice
cash.save()
currentOrder.order_list = json.dumps(list())
currentOrder.order_totalprice = 0
currentOrder.save()
succesfully_payed = True
else:
tmpproduct = dish.objects.filter(dishName = operation).first()
if tmpproduct is not None:
tmplist = json.loads(currentOrder.order_list)
i = tmplist.index(tmpproduct.dishName)
del tmplist[i]
currentOrder.order_list = json.dumps(tmplist)
currentOrder.order_totalprice = currentOrder.order_totalprice - tmpproduct.dishFullPrice
if currentOrder.order_totalprice < 0:
logging.warn("prices below 0!")
currentOrder.order_totalprice = 0
currentOrder.save()
totalprice = currentOrder.order_totalprice
order_list = json.loads(currentOrder.order_list)
template = loader.get_template('menu/addition.html')
context = {
'order_list': order_list,
'totalprice': totalprice,
'cash': cash,
'discList': discList,
'taxList': taxList,
'succesfully_payed': succesfully_payed,
'payment_error': payment_error,
'amount_added': amountAdded,
}
return HttpResponse(template.render(context, request))
#def dish_detail_view(request, id=1):
# obj = dish.objects.get(id=id)
# print(obj)
# context = {
# "object": obj
# }
# return render(request, "menu/detail_view.html", context)
#def dish_list_view(request):
# queryset = dish.objects.all()
# print(queryset)
# for obj in queryset:
# print(obj.dishName)
# context = {
# "object_list": queryset
# }
# return render(request, "menu/list_view.html", context)
我的Models.py
from django.db import models
from django.conf import settings
class category(models.Model):
categoryName = models.CharField(max_length=50)
def __str__(self):
return self.categoryName
class dish(models.Model):
BOOL_CHOICES = ((True,'Veg'),(False,'Non-Veg'))
dishid = models.AutoField(primary_key=True)
dishName = models.CharField(max_length=200)
dishCuisine = models.CharField(max_length=100)
dishContent = models.TextField(max_length=1000)
dishType = models.BooleanField(choices=BOOL_CHOICES)
dishCategory = models.ForeignKey(category, on_delete=models.CASCADE)
dishHalfPrice = models.DecimalField(max_digits=7,decimal_places=3,default=0)
dishFullPrice = models.DecimalField(max_digits=7,decimal_places=3,default=0)
dishCostPrice = models.DecimalField(max_digits=7,decimal_places=3,default=0)
def __str__(self):
return self.dishID
def __str__(self):
return self.dishName
def save(self, *args, **kwargs):
if not self.pk:
self.full_clean()
super(dish, self).save(*args, **kwargs)
#def clean(self, *args, **kwargs):
# dishName = self.dishName
# if dishName == "":
# raise ValidationError("Cannot be empty")
# return super(dish, self).clean(*args, **kwargs)
class discount(models.Model):
APPLICATION_CHOICES = ((True, 'Single Item'), (False, 'Final Bill'))
discountName = models.CharField(max_length=200)
discountDish = models.ForeignKey(dish, on_delete=models.CASCADE)
discountRate = models.IntegerField()
discountDescription = models.TextField(max_length=1000)
discountApp = models.BooleanField(choices=APPLICATION_CHOICES)
def __str__(self):
return self.discountName
class tax(models.Model):
APPLICATION_CHOICES = ((True, 'Single Item'), (False, 'Final Bill'))
taxName = models.CharField(max_length=200)
taxDish = models.ForeignKey(dish, on_delete=models.CASCADE)
taxRate = models.IntegerField()
taxDescription = models.TextField(max_length=1000)
taxApp = models.BooleanField(choices=APPLICATION_CHOICES)
def __str__(self):
return self.taxName
class Order(models.Model):
order_user = models.CharField(max_length=50)
order_list = models.CharField(max_length=1000)
order_totalprice = models.DecimalField(max_digits=7,decimal_places=3,default=0)
class Cash(models.Model):
cash_amount = models.DecimalField(max_digits=7, decimal_places=3,default=0)
我的Forms.py
from django import forms
from .models import dish
from .models import category
from .models import discount
from .models import tax
from django.contrib.auth import get_user_model
User = get_user_model
class dishModelForm(forms.ModelForm):
class Meta:
model = dish
fields = [
"dishName",
"dishCuisine",
"dishContent",
"dishType",
"dishCategory",
"dishHalfPrice",
"dishFullPrice",
"dishCostPrice"
]
class categoryModelForm(forms.ModelForm):
class Meta:
model = category
fields = [
"categoryName"
]
class discountModelForm(forms.ModelForm):
class Meta:
model = discount
fields = [
"discountName",
"discountDish",
"discountRate",
"discountDescription",
"discountApp"
]
class taxModelForm(forms.ModelForm):
class Meta:
model = tax
fields = [
"taxName",
"taxDish",
"taxRate",
"taxDescription",
"taxApp"
]
class UserRegisterModelForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
def clean_password2(self):
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password != password2:
raise forms.ValidationError("Password must match")
return password2
def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username__icontains=username).exists():
raise forms.ValidationError("This username is taken")
return username
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email__icontains=email).exists():
raise forms.ValidationError("This email is already registered.")
return email
我的html文件
{% extends "menu/base.html" %}
{% block content %}
<div class='row'>
<div class='col-sm-6 col-sm-offset-3'>
<h1>Register</h1>
<form class='form' method='POST' action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Register" />
</form>
</div>
</div>
{% endblock %}
答案 0 :(得分:1)
当你在forms.py中引用它时,你还没有调用get_user_model
。
User = get_user_model()
请不要多次剪切和粘贴文本;有一个原因,SO要求您编写与您的代码相比最少量的文本;在您的情况下,您发布了大量与您的问题无关的代码。