Django 'ProductDetailView' object has no attribute 'user' - python

Creating a page for an ecommerce site that allows a user to add an item to their cart. Im having issues with no object user found in the ProductDetailView. I overrode the get_context_data function to the class based view, so it will be called when they access the specific product page.
Error:
'ProductDetailView' object has no attribute 'user'
I'm assuming this is because the view doesn't see users, because it needs a user.objects.all()?
views.py
from django.shortcuts import render, redirect
from django.shortcuts import render
from django.views.generic import CreateView, DetailView, ListView, RedirectView, UpdateView
from django.views import generic
from django.contrib.auth.decorators import login_required # This is to block pages to non users using function views
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import ProductForm, ContactForm
from .models import Product, Contact
from checkout.models import OrderItem, Order
from users.models import User, Profile
# Create your views here.
class ProductDetailView(generic.DetailView):
model = Product
template_name = 'portal/product_detail.html'
def get_context_data(request, **kwargs):
filtered_orders = Order.objects.filter(owner=request.user.user_profile, is_ordered=False)
current_order_products = []
if filtered_orders.exists():
user_order = filtered_orders[0]
user_order_items = user_order.items.all()
current_order_products = [product.product for product in user_order_items]
context = {
'current_order_products': current_order_products
}
return context

The problem is in your def get_context_data(request, **kwargs), you need to have self as first argument. You need to remove request from the arguments and use self.request to access it:
def get_context_data(self, **kwargs):
filtered_orders = Order.objects.filter(owner=self.request.user.user_profile, is_ordered=False)

Related

How to convert a function based view into class based ListView?

How implement Django.views.generic if earlier used request?
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import *
from django.contrib.auth import login,logout,authenticate
from .forms import *
from django.views.generic import ListView
# Create your views here.
# New
class HomePage(ListView):
model = Book
template_name = 'book/templates/home.html'
# Old
def home(request):
books=Book.objects.all()
context={'books':books}
if request.user.is_staff:
return render(request,'book/templates/adminhome.html',context)
else:
return render(request,'book/templates/home.html',context)
You can make ListView in following way:
class BookListView(ListView):
model=Book
context_object_name='books'
def get_template_names(self):
if self.request.user.is_staff:
return ['book/templates/adminhome.html']
else:
return ['book/templates/home.html']
Note: Class based views requires their names to be written as model name as the prefix and actual view name as the suffix, so I changed it to BookListView from HomePage.

Django LoginRequiredMixin not working as intented

The LoginRequiredMixin is not working as intended for the class based view below, I was able to access the webpage regardless of login status, but it should have redirected the unauthorized users to the login page. Where have I gone wrong?
from django.shortcuts import render, redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import FormView
from .forms import UpdatePortfolio
# Create your views here.
class UpdatePortfolioView(LoginRequiredMixin, FormView):
login_url = 'users:login'
redirect_field_name = 'mainpage:update'
form = UpdatePortfolio
template_name = 'mainpage/updateportfolio.html'
def get_object(self):
# return self.request.user.id
return self.request.user.pk
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, self.template_name, {'form': form})
I think the Problem is Because you Override the Get method... Because the functionality of Redirecting the users will add to the get function and you had overridden it
remove it ... and you should know that all the code in the function is already will be done by the FormView You don't have to write it
Read this Docs

'register' object has no attribute 'get' in Django

Hi Everyone i make a blog with django but i need to register use and always i get this error:
AttributeError at /register/
'register' object has no attribute 'get'
i already search too many times but i don't get correct answer so make sure don't mark as a duplicate
Here is my Views.py
from django.shortcuts import render , get_object_or_404,redirect
from django.utils import timezone
from blog.models import *
from blog.forms import *
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.\
def user_register(request):
if request.method == "POST":
reg = register(data=request.POST)
if reg.is_valid():
user = reg.save()
user.set_password(user.password)
user.save()
else:
print(register.errors)
else:
reg = register()
return render(request,'register.html',{'reg':reg})
Here is my Models.py
class register(models.Model):
user = models.OneToOneField(User,on_delete="Cascade")
Here is my Forms.py
class register(forms.ModelForm):
class Meta():
model = User
fields = ('username','email','password')
I'm Wating For Your Answers!
Providing yoururls.py file would be helpful, but for the time being I'm going to assume it looks something like this:
urls.py
urlpatterns = [
path('register/', views.user_register, name='register'),
]
Either way, the issue is that your user_register function does not know how to handle GET requests (i.e. when you visit the URL which calls this function). You should define logic within user_register to handle a GET request. Something like this:
def user_register(request):
if request.method == "POST":
reg = register(data=request.POST)
if reg.is_valid():
user = reg.save()
user.set_password(user.password)
user.save()
else:
print(register.errors)
>if request.method=='GET':
> # do something
return render(request,'register.html',{'reg':reg})

ImproperlyConfigured DeletePost's select_related property

So I'm trying to enable the currently logged in user to delete their own post on my site. I'm using a DeleteView with select_related mixing. I keep getting an error that says it's improperly configured and needs to be a tuple or a list. Here is the error, my post models, and views. Not really sure where to go from here, and this doesn't seem to be a very popular error as I'm not really able to find much with a Google search.
Error:
ImproperlyConfigured at /colorsets/delete/7/
DeletePost's select_related property must be a tuple or list.
App Views.py
from django.shortcuts import render
from colorsets.forms import ColorForm
from colorsets import models
from colorsets.models import ColorSet
from django.utils import timezone
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse,reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import SelectRelatedMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
#def index(request):
# return render(request,'index.html')
class PostListView(ListView):
model = ColorSet
def get_queryset(self):
return ColorSet.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class CreateColorSetView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'index.html'
form_class = ColorForm
model = ColorSet
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class DeletePost(LoginRequiredMixin,SelectRelatedMixin,DeleteView):
model = models.ColorSet
select_related = ('user')
success_url = reverse_lazy('index')
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)
App models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class ColorSet(models.Model):
user = models.ForeignKey(User,related_name='colorset')
published_date = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=50,blank=False)
color_one = models.CharField(max_length=6,blank=False,default='cccccc')
color_two = models.CharField(max_length=6,blank=False,default='ffffff')
color_three = models.CharField(max_length=6,blank=False,default='e5e5e5')
color_four = models.CharField(max_length=6,blank=False,default='f0f0f0')
color_five = models.CharField(max_length=6,blank=False,default='bababa')
def publish(self):
self.save()
def get_absolute_url(self):
return reverse('index')
def __str__(self):
return self.name
Traceback:
Let me know if you need to see anything else.
You are missing the comma to make select_related a tuple.
select_related = ('user',)
Without the comma, ('user') is the string 'user'.

ValueError: The keyword argument `name` must be the name of a method of the decorated class:

views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from briefcase.BaseBriefcaseView import BaseBriefcaseView
from briefcase.models import Customer
#method_decorator(login_required, name='dispatch')
class BriefcaseIndexView(BaseBriefcaseView):
model = Customer
template_name = 'briefcase/index.html'
urls.py
from django.conf.urls import url
from briefcase.views import BriefcaseIndexView, invoice_view
urlpatterns = [
url(r'^$', BriefcaseIndexView.as_view(), name='index'),
url(r'^index/invoice_view$', invoice_view.as_view(), name='invoice'),
]
BaseBriefcase.py
from cmms.views import DefaultContextView
class BaseBriefcaseView(DefaultContextView):
extra_context = {}
def get_context_data(self, **kwargs):
context = super(BaseBriefcaseView, self).get_context_data(**kwargs)
context["side_menu"] = self.get_side_menu()
context["main_menu"] = self.get_main_menu()
context["side_filter"] = self.get_side_filter()
context["module"] = "Briefcase"
return context
And the error i get is.......
ValueError: The keyword argument name must be the name of a method of . > the decorated class: . Got 'dispatch' instead
Please help a django newbie. What am I doing wrong?
To apply login_required to a class based view, you should use the LoginRequiredMixin
class BriefcaseIndexView(LoginRequiredMixin, DefaultContextView):

Categories

Resources