i am working on a project .
i use crispy_form in my project.
it is my cars urls.py::
from django.urls import path
from . import views
app_name = 'cars'
urlpatterns = [
path('', views.CarsListView.as_view(), name='cars'),
path('add-car/', views.AddCarView.as_view(), name='add_car'),
path('car/', views.RepairsListView.as_view(), name='car_detail'),
path('car/<int:pk>/update/', views.UpdateCarView.as_view(), name='update_car'),
path('car/<int:pk>/delete/', views.DeleteCarView.as_view(), name='delete_car'),
path('car/<int:pk>/new-repair/', views.AddRepairView.as_view(), name='add_repair'),
]
it is my cars views.py ::
from .models import Car, Repair
from django.views.generic import ListView, UpdateView, DeleteView, CreateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.contrib import messages
class CarsListView(LoginRequiredMixin, ListView):
model = Car
template_name = 'cars/cars.html'
context_object_name = 'cars'
paginate_by = 10
def get_queryset(self):
if self.request.GET.get('q'):
q = self.request.GET.get('q')
make_results = self.model.objects.filter(
user=self.request.user, make=q).order_by('-pk')
model_results = self.model.objects.filter(
user=self.request.user, model=q).order_by('-pk')
if make_results.exists():
return make_results
elif model_results.exists():
return model_results
else:
return self.model.objects.none()
return self.model.objects.filter(user=self.request.user).order_by('-pk')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['q'] = self.request.GET.get('q', '')
return context
class AddCarView(LoginRequiredMixin, CreateView):
model = Car
fields = ['make', 'model', 'vrn', 'year']
success_url = '/'
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
class DeleteCarView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Car
success_url = '/'
def test_func(self):
if self.get_object().user == self.request.user:
return True
return False
def delete(self, request, *args, **kwargs):
success_message = f'Car {self.get_object()} has been deleted'
messages.success(self.request, success_message)
return super().delete(request, *args, **kwargs)
class UpdateCarView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Car
fields = ['make', 'model', 'vrn', 'year']
success_message = 'Car info has been updated'
def get_success_url(self, **kwargs):
row = self.request.GET.get('row')
p = self.request.GET.get('p')
q = self.request.GET.get('q')
options = '?p=' + p + '&row=' + row
options += '&q=' + q
messages.success(self.request, self.success_message)
return reverse_lazy('car_detail') + options
def test_func(self):
if self.get_object().user == self.request.user:
return True
return False
class AddRepairView(LoginRequiredMixin, CreateView):
model = Repair
fields = ['date', 'description']
success_message = 'New repair has been added'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['car'] = Car.objects.get(id=self.kwargs['pk'])
return context
def form_valid(self, form, **kwargs):
form.instance.car = Car.objects.get(id=self.kwargs['pk'])
return super().form_valid(form)
def get_success_url(self, **kwargs):
row = self.request.GET.get('row')
p = self.request.GET.get('p')
q = self.request.GET.get('q')
options = '?p=' + p + '&row=' + row
options += '&q=' + q
return reverse_lazy('car_detail') + options
class RepairsListView(LoginRequiredMixin, ListView):
model = Repair
paginate_by = 10
def __get_car(self):
cars = Car.objects.filter(user=self.request.user).order_by('-pk')
if self.request.GET.get('q'):
q = self.request.GET.get('q')
make_results = Car.objects.filter(
user=self.request.user, make=q).order_by('-pk')
model_results = Car.objects.filter(
user=self.request.user, model=q).order_by('-pk')
if make_results.exists():
cars = make_results
elif model_results.exists():
cars = model_results
id = int(self.request.GET.get('row')) - 1
page = int(self.request.GET.get('p')) - 1
id = id + page * 10
return cars[id]
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['car'] = self.__get_car()
context['row'] = self.request.GET.get('row')
context['p'] = self.request.GET.get('p')
context['q'] = self.request.GET.get('q')
return context
def get_queryset(self, **kwargs):
return self.model.objects.filter(car=self.__get_car()).order_by('-pk')
and it is my users views.py ::
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.contrib.auth import login, authenticate
from django.views.generic import CreateView
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
class RegisterUser(CreateView):
form_class = UserCreationForm
def get(self, request, *args, **kwargs):
return render(request, 'users/register-user.html', {'form': UserCreationForm()})
def post(self, request, *args, **kwargs):
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, f'Welcome, {username}!')
return redirect('cars')
return render(request, 'users/register-user.html', {'form': form})
class ChangePassword(LoginRequiredMixin, CreateView):
form_class = PasswordChangeForm
template_name = 'users/change-password'
def get(self, request, *args, **kwargs):
form = PasswordChangeForm(request.user)
return render(request, 'users/change-password.html', {'form': form})
def post(self, request, *args, **kwargs):
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user)
messages.success(request, 'Password changed!')
return redirect('cars')
return render(request, 'users/change-password.html', {'form': form})
and when i want to cars page i have error :: ((NoReverseMatch at /cars/))
and
(Reverse for 'login' not found. 'login' is not a valid view function or pattern name.)
can anyone help me??
please help me guys!!!!!!
Try to include your cars and user Url into your base urls.py.
from yourproject.cars import urls as car_urls
from yourproject.users import urls as users_urls
and then add the following to your base urlpatterns
url(r"^cars/", include((car_urls)),
url(r"^users/", include((user_urls)),
Related
I am trying to make a form in Django that gives the user a limited selection based on a foreign key. To be more exact, the form has 2 fields, a ModelChoiceField and a simple text field. This form's purpose is to allow a user to add a Riddle to a previously created Room. So the goal is to limit the ModelChoiceField to only allow the currently logged-in user to add riddles to just their own rooms.
forms.py:
from django import forms
from .models import Project, Riddle
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['title', 'max_players', 'has_actor', 'scenario']
class RiddleForm(forms.ModelForm):
project = forms.ModelChoiceField(queryset=Project.objects.all(),
empty_label=None,
widget=forms.Select(attrs={'class': 'form-control'}),
label='Project')
class Meta:
model = Riddle
fields = ['project','description']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['project'].queryset = Project.objects.all()
self.fields['project'].label_from_instance = lambda obj: obj.title
models.py:
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
User = get_user_model()
class Project(models.Model):
title = models.CharField(max_length=255, unique=True)
max_players = models.PositiveIntegerField(default=0)
has_actor = models.BooleanField(default=False)
scenario = models.TextField(blank=True, null=True)
#number_of_riddles = models.PositiveIntegerField(default=0)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rooms')
def get_absolute_url(self):
return reverse(
"rooms:project_list",
kwargs={
"username": self.user.username,
#"pk": self.pk
}
)
class Riddle(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
description = models.TextField()
urls.py:
from django.urls import path
from .views import ProjectListView, ProjectDetailView, ProjectCreateView, ProjectUpdateView, ProjectDeleteView, RiddleAddView
app_name = 'rooms'
urlpatterns = [
path('projects/madeby/<slug:username>', ProjectListView.as_view(), name='project_list'),
path('projects/<slug:username>/<int:pk>/', ProjectDetailView.as_view(), name='project_detail'),
path('projects/create/', ProjectCreateView.as_view(), name='project_create'),
path('projects/update/<int:pk>', ProjectUpdateView.as_view(), name='project_update'),
path('projects/delete/<int:pk>/', ProjectDeleteView.as_view(), name='project_delete'),
path('projects/addriddle/', RiddleAddView.as_view(), name='riddle_add'),
]
views.py:
from django.urls import reverse_lazy, reverse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View, generic
from django.views.generic import CreateView, DetailView, UpdateView
from .models import Project, Riddle
from .forms import ProjectForm, RiddleForm
from django.contrib.auth import get_user_model
from django.http import Http404
from braces.views import SelectRelatedMixin
from django.contrib import messages
User = get_user_model()
class ProjectCreateView(CreateView):
model = Project
form_class = ProjectForm
template_name = 'rooms/project_form.html'
#success_url = reverse_lazy('rooms:project_list username=')
def get_success_url(self):
return reverse('rooms:project_list', kwargs= {'username': self.request.user})
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
#def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# context['riddle_form'] = RiddleForm()
# return context
#def form_valid(self, form):
#project = form.save()
# project_id = self.kwargs.get('pk')
# project = Project.objects.get(id=project_id)
# riddle_form = RiddleForm(self.request.POST)
#if riddle_form.is_valid():
# riddle = riddle_form.save(commit=False)
# riddle.project = project
# riddle.save()
#return super().form_valid(form)
class ProjectDetailView(DetailView):
model = Project
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project_id = self.kwargs.get('pk')
project = Project.objects.get(id=project_id)
context['project'] = project
return context
class ProjectUpdateView(UpdateView):
model = Project
form_class = ProjectForm
template_name = 'rooms/project_form.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['riddle_form'] = RiddleForm()
return context
#def form_valid(self, form):
#project = form.save()
# project_id = self.kwargs.get('pk')
# project = Project.objects.get(id=project_id)
# riddle_form = RiddleForm(self.request.POST)
#if riddle_form.is_valid():
# riddle = riddle_form.save(commit=False)
# riddle.project = project
# riddle.save()
#return super().form_valid(form)
#def form_valid(self, form):
# form.save()
# return redirect('rooms:project_list')
class ProjectListView(generic.ListView):
model = Project
template_name = "rooms/room_list.html"
def get_queryset(self):
try:
self.room_user = User.objects.prefetch_related('rooms').get(
username__iexact=self.kwargs.get('username')
)
except User.DoesNotExist:
raise Http404
else:
return self.room_user.rooms.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["room_user"] = self.room_user
return context
class ProjectDeleteView(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView):
model = Project
select_related = ('user',)
#success_url = reverse_lazy('home')
def get_success_url(self):
return reverse('rooms:project_list', kwargs= {'username': self.request.user})
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
class RiddleAddView(CreateView):
model = Riddle
form_class = RiddleForm
template_name = 'rooms/riddle_form.html'
def form_valid(self, form):
project = form.cleaned_data.get('project')
project_title = project.title
try:
project = Project.objects.get(title=project_title)
except Project.DoesNotExist:
messages.error(self.request, "No project with the title '{}' was found.".format(project_title))
return super().form_invalid(form)
form.instance.project = project
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('rooms:project_detail', kwargs={'username': self.object.project.user.username, 'pk': self.object.project.id})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['riddle_form'] = RiddleForm()
#context['project_id'] = self.kwargs['project_id']
return context
For now, I just have the Project.objects.all() but that does not achieve the functionality I want.
I have tried using the select_related(), filter() methods and the attribute__foreignattribute syntax to no success. Any ideas of how I should go about this are welcome! Taking into account how common this operation is, the solution is probably something pretty obvious, but I haven't been able to come up with something to fit my case.
Thanks in advance!
I think you can pass the user as an argument for the RiddleForm:
In RiddleAddView you can define user as a parameter for the RiddleForm:
class RiddleAddView(CreateView):
...
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
...
Then you can use it to restrict the queryset in the RiddleForm:
class RiddleForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super().__init__(*args, **kwargs)
self.fields['project'].queryset = Project.objects.filter(user=user)
...
Also, you can use the reverse relationship:
class RiddleForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super().__init__(*args, **kwargs)
self.fields['project'].queryset = user.rooms.all()
...
I want to create a new post using PostCreateView and go to the details page of the new post in the next step, but I get this error:
(The view post.views.view didn't return an HttpResponse object. It returned None instead.)
views
class PostDetailView(View):
"""see detail post"""
def get(self, request, post_id, post_slug):
post = Post.objects.get(pk=post_id, slug=post_slug)
return render(request, "post/detail.html", {"post": post})
class PostCreateView(LoginRequiredMixin, View):
form_class = PostCreateUpdateForm
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, "post/create.html", {"form": form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug = slugify(form.cleaned_data["body"][:20])
new_post.user = request.user
new_post.save()
messages.success(request, "you created a new post", "success")
return redirect("post:post-detail", new_post.id, new_post.slug)
models
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
slug = models.SlugField()
img = models.ImageField(upload_to="%Y/%m/%d/")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
urls
app_name = 'post'
urlpatterns = [
path('', views.BlogView.as_view(), name="home"),
path('detail/<int:post_id>/<slug:post_slug>/', views.PostDetailView.as_view(), name="post-detail"),
path('delete/<int:post_id>/', views.PostDeleteView.as_view(), name="post-delete"),
path('update/<int:post_id>/', views.PostUpdateView.as_view(), name="post-update"),
path('create/', views.PostCreateView.as_view(), name="post-create"),
]
In case the form is not valid, you should rerender the template with the form, so:
class PostCreateView(LoginRequiredMixin, View):
form_class = PostCreateUpdateForm
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, "post/create.html", {"form": form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug = slugify(form.cleaned_data['body'][:20])
new_post.user = request.user
new_post.save()
messages.success(request, 'you created a new post', 'success')
return redirect('post:post-detail', new_post.id, new_post.slug)
return render(request, 'post/create.html', {'form': form})
But you are implementing a lot of boilerplate code here. What you here do is implementing a CreateView [Django-doc]:
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView
class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
form_class = PostCreateUpdateForm
template_name = 'post/create.html'
success_message = 'you created a new post'
def form_valid(self, form):
form.instance.slug = slugify(form.cleaned_data['body'][:20])
form.instance.user = request.user
return super().form_valid()
def get_success_url(self):
return reverse('post:post-detail', args=(new_post.id, new_post.slug))
Your "post" method in PostCreateView only returns a response if the form is valid. If it isn't valid, it will return None, causing an error.
Modify that method so it looks like this:
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug = slugify(form.cleaned_data["body"][:20])
new_post.user = request.user
new_post.save()
messages.success(request, "you created a new post", "success")
return redirect("post:post-detail", new_post.id, new_post.slug)
return render(request, "post/create.html", {"form": form})
Not sure what I've done to break the admin site, but going to 127.0.0.1:8000/admin/ is not working and gives me the error in the screenshot below:
Here's the two urls.py files:
myproject/urls.py
from django.conf.urls import include, url
from django.contrib import admin
import product_app.urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(product_app.urls)),
]
and the product_app urls.py:
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
from . import views
from .views import *
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^subscribe/$', views.subscribe, name='subscribe'),
url(r'^products/$', views.products, name = 'products'),
url(r'^product/$', ProductListView.as_view(), name='product_list'),
url(r'^user/(\w+)/$', views.profile, name='profile'),
url(r'post_url/', views.post_product, name='post_product'),
url(r'^([0-9]+)/$', views.detail, name = 'detail'),
url(r'^login/$', views.login_view, name='Login'),
url(r'^logout/$', views.logout_view, name='Logout'),
url(r'^like_product/$', views.like_product, name='like_product' ),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^(?P<pk>\d+)/edit/$', PostUpdateView.as_view(), name='product-edit'),
url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='product-delete'),
]
if settings.DEBUG:
urlpatterns += [
url(r'^product/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
...and just in case, the models.py:
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
def get_image_path(instance, filename):
return '/'.join(['product_images', str(instance.name), filename])
class Product(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
price = models.DecimalField(max_digits=10, decimal_places=2)
url = models.CharField(max_length=200)
product_type = models.CharField(max_length=100)
image = models.ImageField(upload_to='product_images', blank=True, null=True)
image_url = models.CharField(max_length=200, blank=True)
likes = models.IntegerField(default=0)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index', kwargs={})
...finally, my views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from .models import Product #, HashTag
from .forms import ProductForm, LoginForm, ContactForm, SubscribeForm, EditProfileForm
from django.views import generic
# edit / delete views
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.edit import UpdateView, DeleteView
# contact and subscribe forms
from django.core.mail import EmailMessage
from django.template import Context
from django.template.loader import get_template
from django.contrib.auth import get_user_model
from . import forms
from django.shortcuts import render
from django.views.generic.list import ListView
class HomePage(generic.TemplateView):
template_name = "index.html"
def get_context_data(self, *args, **kwargs):
context=super(HomePage, self).get_context_data(*args, **kwargs)
context['form'] = ContactForm
return context
def products(request):
username = request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
else:
products = Product.objects.all()
form = ProductForm()
return render(request, 'products.html', {'products': products, 'form':form})
class ProductListView(ListView):
template_name = 'product_list.html'
context_object_name = 'product_list'
paginate_by = None
def get_queryset(self):
username = self.request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
return Product.objects.none()
def post_product(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProductForm(data = request.POST, files = request.FILES)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
product = form.save(commit = False)
product.user = request.user
product.likes = 0
product.save()
# redirect to a new URL:
return HttpResponseRedirect('/products')
def detail(request, product_id):
product = Product.objects.get(id=product_id)
#hashtags = HashTag.objects.filter(product=product_id)
return render(request, 'detail.html', {'product': product})
def profile(request, username):
user = get_object_or_404(User, username=username)
products = Product.objects.filter(user=user)
if not request.user == user:
return render(request, 'no.html')
else:
return render(request, 'profile.html', {'user':user,'products': products})
def edit_profile(request):
user = request.user
products = Product.objects.filter(user=user)
form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.save()
return render(request, 'profile.html', {'user':user,'products': products})
context = {"form": form}
return render(request, "edit_profile.html", context)
def like_product(request):
product_id = request.POST.get('product_id', None)
likes = 0
if (product_id):
product = Product.objects.get(id=int(product_id))
if product is not None:
likes = product.likes + 1
product.likes = likes
product.save()
return HttpResponse(likes)
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
# the password verified for the user
if user.is_active:
print("User is valid, active and authenticated")
login(request, user)
products = Product.objects.filter(user=user)
return render(request, 'profile.html', {'user':user,'products': products})
else:
print("The password is valid, but the account has been disabled!")
else:
# the authentication system was unable to verify the username and password
print("The username and password were incorrect.")
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def logout_view(request):
logout(request)
return HttpResponseRedirect('/')
class PostUpdateView(UpdateView):
model = Product
form_class = ProductForm
template_name = 'edit_product.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# Any manual settings go here
self.object.save()
# return HttpResponseRedirect(self.object.get_absolute_url())
return redirect ('products')
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostUpdateView, self).dispatch(request, *args, **kwargs)
class PostDeleteView(DeleteView):
model = Product
template_name = 'product_confirm_delete.html'
def get_success_url(self):
return reverse ('products')
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostDeleteView, self).dispatch(request, *args, **kwargs)
User = get_user_model()
def subscribe(request):
form_class = SubscribeForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
# Email the profile with the
# contact information
template = get_template('contact/subscribe_template.txt')
context = dict({'contact_name': contact_name, 'contact_email': contact_email,})
content = template.render(context)
email = EmailMessage(
"New subscribe form submission",
content,
"Your website" +'',
['steve#steve-shead.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return render(request, 'contact/thank_you_subscribe.html')
return render(request, 'contact/subscribe.html', {
'form': form_class,
})
def contact(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('contact/contact_template.txt')
context = dict({'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content,})
content = template.render(context)
email = EmailMessage(
"New contact form submission",
content,
"Your website" +'',
['steve#steve-shead.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return render(request, 'contact/thank_you.html')
return render(request, 'contact/contact.html', {
'form': form_class,
})
I have no clue what I changed to make the admin site not work - any help gratefully received!
Check your ROOT_URLCONF setting - it needs to be set to myproject.urls but looks like it is currently set to product_app.urls.
Here's the full code. This error occurs when I try to build the login and register form!
ERROR`
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`
My 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)
My 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)
My 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
My html file
{% 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 %}
You haven't called get_user_model when you reference it in your forms.py.
User = get_user_model()
And please, do not cut and paste your text multiple times; there's a reason SO requires you to write a minimum amount of text compared to your code; in your case, you've posted tons of code that is unrelated to your question.
I am getting the following error: view_page() takes exactly 2 arguments (1 given)
The code of view.py is:
from wiki.models import Page
from django.shortcuts import render_to_response
def view_page(request, page_name):
try:
page = Page.objects.get(pk=page_name)
except PageDoesNotExist:
return render_to_response("create.html", {"page_name":page_name})
the url given in url.py is :
url(r'^wiki/$', 'wiki.views.view_page'),
But when I am giving the url as given below and delete the above one then i am getting the error of page not found.
url(r'^wiki/(?P<page_name>[^/]+)/$','wiki.views.view_page'),
This is because the second parameter for the view_page() is passed in the url
example
url(r'^wiki/(?P<page_name>[^/]+)/$','wiki.views.view_page')
something.com/wiki/2 #here 2 is the second parameter which is like
def view_page(request, 2)
if u use this
url(r'^wiki/$', 'wiki.views.view_page'),
something.com/wiki/ #The second parameter is not passed to the function
I think your queryset is wrong. If you're passing page_name in the URL, then it should look like:
Page.objects.get(name=page_name)
Maybe second argument should be optional?
def view_page(request, page_name="Default value"):
from django.shortcuts import render, redirect, HttpResponseRedirect
from django.http import HttpResponse
from .forms import loginForm, signUpForm, createBlog, blogcomment
from django.contrib.auth import authenticate, login as auth_login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.views.generic import View, TemplateView, ListView, DetailView, CreateView
from django.contrib.auth.decorators import login_required
from . import models
def login(request):
login_form = loginForm()
if request.method =='POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
auth_login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return render(request,'login.html',{'login_form':login_form,'message':'Please check the username and password'})
else:
return render(request,'login.html',{'login_form':login_form})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('login'))
def signup(request):
# print(request.method)
signup_form = signUpForm()
if request.method =='POST':
#print(request.POST)
signup_form = signUpForm(request.POST)
#print(signup_form)
# signup_form.firstname = request.POST['firstname']
# signup_form.lastname = request.POST['lastname']
# signup_form.email = request.POST['email']
# signup_form.username = request.POST['username']
# signup_form.dob = request.POST['dob']
# signup_form.my_photo = request.POST.get('my_photo',False)
# signup_form.password = request.POST['password']
if signup_form.is_valid():
user = signup_form.save()
user.set_password(user.password)
user.save()
return redirect('login')
else:
print(signup_form.errors)
else:
#print('hello1')
signup_form = signUpForm()
#print('hello2')
return render(request, 'signup.html',{'signup_form':signup_form})
class create_blog(LoginRequiredMixin,CreateView):
def get(self, request):
context = {'form':createBlog(),'title':'create'}
return render(request, 'create.html',context)
def post(self, request):
form = createBlog(request.POST)
if form.is_valid():
blog = form.save(commit=False)
blog.blogger = request.user
blog.save()
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'create.html',{'form':form})
# login_url = '/login/'
# redirect_field_name = 'index.html'
# template_name = 'create.html'
#
# form_class = createBlog
#
# model = models.blog
class index(ListView, LoginRequiredMixin):
def get(self, request):
#print(request.user)
blogs= models.blog.objects.filter(blogger= request.user).values('id','title','content','created_at','blog_photo')
#print(list(blogs))
return render(request, 'index.html',{'title':'index','blogs':list(blogs)})
def post(self, request):
#print(request.POST)
return user_logout(request)
class delete(LoginRequiredMixin, DetailView):
def get(self, request, id):
blog = models.blog.objects.filter(id=id)
blog.delete()
return HttpResponseRedirect(reverse('index'))
class blog(ListView, LoginRequiredMixin, CreateView):
def get(self, request, id):
#print(request.user)
blog= models.blog.objects.get(id=id)
#blog=list(blog)[0]
#print(blog)
comments = models.comment.objects.filter(blog=id).values('comment')
#print(comments)
'''
new_list=[]
print(list(comments))
for comment in list(comments):
new_dict={}
blogg= models.blog.objects.filter(id=comment.get('blog_id')).values()
blogg=list(blogg)[0]
print(blogg)
bloger = models.user.objects.filter(email=blogg['blogger_id']).values('username')
print(bloger)
bloger = list(bloger)[0]
new_dict['comment']=comment['comment']
new_dict['comment_user'] = bloger['username']
new_list.append(new_dict)
print(new_list)
'''
context = {'form':blogcomment(),'title':'blog','blog':blog,'comments':comments}
return render(request, 'blog.html',{'title':'blog','blog':blog,'comments':comments,'form':blogcomment()})
def post(self, request, id):
#print(request.POST)
if 'logout' in request.POST:
return user_logout(request)
else:
form = blogcomment(request.POST)
blog = models.blog.objects.get(id=id)
#print(blog)
if form.is_valid():
comment = form.save(commit=False)
comment.blog = blog
comment.save()
return HttpResponseRedirect(reverse('blogview', kwargs={'id':id}))
return render(request, 'blog.html',{'form':form})
class sr(ListView, LoginRequiredMixin):
def get(self, request, string):
print(request )
blogs= models.blog.objects.filter(title__contains=string).values('id','title','content','created_at')
print(blogs)
return render(request,'search-page.html',{'data':list(blogs),'title':'Search Results'})