Issues with view.py - python

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'})

Related

Whats the reason for decorator returns None in Django?

I am doing a customer relation project in Django and it returns this ValueError at /login/ error. I can log into the admin panel and when I logout this error occurs.
*ValueError at /login/
The view accounts.decorators.wrapper_func didn't return an HttpResponse object. It returned None instead.
decorators.py:
from django.http import HttpResponse
from django.shortcuts import redirect,render
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('home')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
def allowed_users(allowed_roles=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return HttpResponse('You are not authorized to view this page')
views.py:
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.forms import inlineformset_factory
from accounts.models import *
from .forms import orderForm,createUserForm
from .filters import orderFilter
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from .decorators import unauthenticated_user,allowed_users,admin_only
# Create your views here.
#unauthenticated_user
def registerPage(request):
form = createUserForm()
if request.method == 'POST':
form = createUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
group = Group.objects.get(name='customer')
user.groups.add(group)
messages.success(request, 'Account was created for ' + username)
return redirect('login')
context = {'form':form}
return render(request, 'accounts/register.html', context)
#unauthenticated_user
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username or Password is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def logoutUser(request):
logout(request)
return redirect('login')
#login_required(login_url='login')
#allowed_users(allowed_roles=['admin'])
def home(request):
customer = Customer.objects.all()
orders = Orders.objects.all()
total_customers = customer.count()
total_orders = orders.count()
delivered = orders.filter(status='Delivered').count()
pending = orders.filter(status='Pending').count()
context = {'customer':customer, 'orders':orders, 'total_orders':total_orders, 'delivered':delivered, 'pending':pending}
return render(request,'accounts/home.html', context)
def userPage(request):
context = {}
return render(request, 'accounts/user.html', context)
#login_required(login_url='login')
def products(request):
product = Product.objects.all()
return render(request, 'accounts/product.html',{'products':product})
#login_required(login_url='login')
def customer(request, pk):
customer = Customer.objects.get(id=pk)
orders = customer.orders_set.all()
count = orders.count()
myFilter = orderFilter(request.GET, queryset=orders)
orders = myFilter.qs
context = {'customer':customer, 'orders':orders, 'count':count, 'myFilter':myFilter}
return render(request, 'accounts/customer.html', context)
#login_required(login_url='login')
def createOrder(request):
orderFormSet = inlineformset_factory(Customer, Orders, fields=('product','status'), extra=5)
#customer = Customer.objects.get(id=pk)
formset = orderFormSet(queryset=Orders.objects.none()) #instance=customer
#form = orderForm(initial={'customer':customer})
if request.method == 'POST':
#form = orderForm(request.POST)
formset = orderFormSet(request.POST) #instance=customer
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset':formset}
return render(request, 'accounts/order_form.html', context)
#login_required(login_url='login')
def updateOrder(request,pk):
order = Orders.objects.get(id=pk)
form = orderForm(instance=order)
if request.method == 'POST':
form = orderForm(request.POST, instance=order)
if form.is_valid():
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'accounts/order_form.html', context)
#login_required(login_url='login')
def deleteOrder(request, pk):
order = Orders.objects.get(id=pk)
if request.method == 'POST':
order.delete()
return redirect('/')
context = {'order':order}
return render(request, 'accounts/delete.html', context)

getting error while saving a data into database in django using .save() method

I have created 2 models.
from django.db import models
from django.contrib.auth.models import User
class categories(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class tasks(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
category = models.ForeignKey(categories, on_delete=models.CASCADE)
def __str__(self):
return self.title
and have created the forms from these models.
the view.py is
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from .forms import CategoriesForm,TaskForm
from .models import categories,tasks
from django.utils import timezone
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'user/home.html')
def signupuser(request):
if request.method == 'GET':
return render(request, 'user/signupuser.html', {'form':UserCreationForm()})
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return redirect('currentcategories')
except IntegrityError:
return render(request, 'user/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'})
else:
return render(request, 'user/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'})
def loginuser(request):
if request.method == 'GET':
return render(request, 'user/loginuser.html', {'form':AuthenticationForm()})
else:
user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
if user is None:
return render(request, 'user/loginuser.html', {'form':AuthenticationForm(), 'error':'Username and password did not match'})
else:
login(request, user)
return redirect('currentcategories')
#login_required
def logoutuser(request):
if request.method == 'POST':
logout(request)
return redirect('home')
#login_required
def createcategories(request):
if request.method == 'GET':
return render(request, 'user/createcategories.html', {'form':CategoriesForm()})
else:
try:
form = CategoriesForm(request.POST)
newcategory = form.save(commit=False)
newcategory.user = request.user
newcategory.save()
return redirect('currentcategories')
except ValueError:
return render(request, 'user/createcategories.html', {'form':CategoriesForm(), 'error':'Bad data passed in. Try again.'})
#login_required
def currentcategories(request):
categ = categories.objects.filter(user=request.user)
return render(request, 'user/currentcategories.html', {'categories':categ})
#login_required
def viewcategory(request, categories_pk):
categ = get_object_or_404(categories, pk=categories_pk, user=request.user)
if request.method == 'GET':
form = CategoriesForm(instance=categories)
return render(request, 'user/viewcategory.html', {'categories':categ, 'form':form})
else:
try:
form = CategoriesForm(request.POST, instance=user)
form.save()
return redirect('currentcategories')
except ValueError:
return render(request, 'user/viewcategory.html', {'categories':categ, 'form':form, 'error':'Bad info'})
#login_required
def deletecategories(request, categories_pk):
categ = get_object_or_404(categories, pk=categories_pk, user=request.user)
if request.method == 'POST':
categ.delete()
return redirect('currentcategories')
#login_required
def task(request,categories_pk):
categ = get_object_or_404(categories, pk=categories_pk, user=request.user)
if request.method == 'GET':
form = TaskForm(instance = tasks)
return render(request, 'user/task.html', {'categories':categ, 'form':form})
else:
try:
form = TaskForm(request.POST, instance=tasks)
form.save()
return redirect('currentcategories')
except ValueError:
return render(request, 'user/viewcategory.html', {'categories':categ, 'form':form, 'error':'Bad info'})
#login_required
def createtask(request, categories_pk):
if request.method == 'GET':
return render(request, 'user/createtask.html', {'form':TaskForm()})
else:
try:
form = TaskForm(request.POST)
newtask = form.save(commit=False)
newtask.user = request.user
newtask.category_id = request.POST.get('categories_pk')
newtask.save()
return redirect('currenttask')
except ValueError:
return render(request, 'user/createtask.html', {'form':TaskForm(), 'error':'Bad data passed in. Try again.'})
#login_required
def currenttask(request):
tasks = task.objects.filter(categories=request.user.category)
return render(request, 'user/currenttask.html', {'categories':categ})
i am getting error at newtask.save()
Error is:
IntegrityError at /categories/16/createtask/
null value in column "category_id" violates not-null constraint
DETAIL: Failing row contains (10, low, asdfgh, null).
how to procede with this?
Try :
category = models.ForeignKey(categories, null=True, on_delete=models.CASCADE)
You need to use the keyword argument passed to the view categories_pk:
#login_required
def createtask(request, categories_pk):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.instance.category_id = categories_pk
newtask = form.save()
return redirect('currenttask')
else:
form = TaskForm()
return render(request, 'user/createtask.html', {'form':TaskForm()})
Note: Instead of passing 'error':'Bad data passed in. Try again.'
into the context use the forms errors. form.field_name.errors
contains a fields errors and form.non_field_errors contain non-field
errors.

NoReverseMatch at /cars/

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)),

Django 127.0.0.1:8000/admin/ stopped working

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.

Django pass get parameters from login to users home page

My login url is like this http://localhost:8000/?wid=ca1480&ref_url=localhost&adpart=left
When a users log in through login page and come to his dashboard his url should be like this
http://localhost:8000/dashboard/?wid=ca1480&ref_url=localhost&adpart=left
But i am unable to achive this what changes i need to make.
urls.py
url(r'^$', LoginPageView.as_view(), name='login'),
url(r'^dashboard$', login_required(DashboardPageView.as_view()), name='dashboard'),
Views.py
class LoginPageView(FormView):
template_name = 'login.html'
form_class = LoginForm
success_url = '/dashboard'
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
username = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(self.get_success_url())
else:
return render(request, self.template_name, {
'error':'Invalid Username and Password, Please try again.','form': form
})
else:
messages.error(request, "Wrong Email and Password combination.")
return self.form_invalid(form)
else:
return self.form_invalid(form)
class DashboardPageView(TemplateView):
template_name = 'dashboard.html'
def get(self, request, *args, **kwargs):
data = request.GET
url = reverse()
return HttpResponseRedirect(url)
#views.py
...
success_url = self.get_success_url()
if request.META.get('QUERY_STRING'):
success_url += '?' + request.META.get('QUERY_STRING')
return HttpResponseRedirect(success_url)
...
I would also recommend to replace
success_url = '/dashboard'
with:
from django.core import urlresolvers
...
success_url = urlresolvers.reverse('dashboard')

Categories

Resources