Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django IntegrityError at /main/addcomment/1 NOT NULL constraint failed: main_comment.post_id
I stuck by an integrity error when I passed comment to my product review page. Help Me through this. I think the error occurs because of the args which passed through the render function. My models.py class Comment(models.Model): post = models.ForeignKey(List, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) subject = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def __str__(self): return str(self.user) views.py def addcomment(request, id): list = get_object_or_404(List, pk=id) form = CommentForm(request.POST or None) if form.is_valid(): data = Comment() data.subject = form.cleaned_data['subject'] data.text = form.cleaned_data['text'] print("Redirected.....") current_user = request.user data.user_id = current_user.id data.save() messages.success(request, "Your Comment has been sent. Thank you for your interest.") return HttpResponseRedirect(reverse('main:hackathonList', args=[list.id])) return render(request, 'product.html', {'list': list, 'form': form}) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('subject', 'text') urls.py path('addcomment/<int:id>', views.addcomment, name='addcomment'), template.html <form action="{% url 'main:addcomment' user.id %}" role="form" method="post"> {% csrf_token %} <p>{{ form | crispy }}</p> {% if user.id is not none %} <button type="submit" class="btn btn-secondary">Comment</button> {% else %} You must be logged in to post a review. {% endif %} </form> -
How to display comment in Django using Ajax
i am new in Ajax and am trying to display comment when form is submitted using Ajax, i have been stucked on this for days now. I am working on a project using Django, users can upload post and each post have a comment form. The form submit successfully, but how do i display the comment for each post commented on. This is what i have tried, comment displayed in browser console but not displaying in post. Ajax: <script type="text/javascript"> //HomeFeeds Comment $(document).ready(function() { $('.feeds-form').on('submit', onSubmitFeedsForm); $('.feeds-form .textinput').on({ 'keyup': onKeyUpTextInput, 'change': onKeyUpTextInput, // if another jquery code changes the value of the input }); function onKeyUpTextInput(event) { var textInput = $(event.target); textInput.parent().find('.submit').attr('disabled', textInput.val() == ''); } function onSubmitFeedsForm(event) { event.preventDefault(); // show console log console.log($(this).serialize()); // if you need to use elements more than once try to keep it in variables var form = $(event.target); var textInput = form.find('.textinput'); var hiddenField = form.find('input[name="post_comment"]'); $.ajax({ type: 'POST', url: "{% url 'site:home' %}", // use the variable of the "form" here data: form.serialize(), dataType: 'json', beforeSend: function() { // beforeSend will be executed before the request is sent form.find('.submit').attr('disabled', true); }, success: function(response) { // as a hint: since you get a … -
Deploy Django and React to Digital Ocean Step by Step
i am a beginner to production and I have been looking for a way to deploy my Django and React app to Digital Ocean but then I am not able to find a suitable tutorial. Any help would be appreciated. -
Django: tried to do the booking but its not working
am working on a project where the user and driver interact with each other here is a model of booking when the user accepts the offer it will show the confirmation booking page but it is not working. here is booking model class Booking(models.Model): order_id = models.AutoField(primary_key=True, default='1') b_price = models.ForeignKey(price, on_delete=models.CASCADE, related_name='b_prices') b_post = models.ForeignKey(Loader_post, on_delete=models.CASCADE, related_name='b_posts') booked_at = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') def __str__(self): return str(self.order_id) this is my views.py @login_required def booking_approve(request, pk): booking = get_object_or_404(Booking, pk=pk) user = request.user if request.method == "POST": bk.user = user.request bk = Booking() bk.save() bk.b_price.add(booking) bk.b_post.add(booking) return redirect('Loader:my_job', pk=pk) -
How to implement logical AND and OR operator in one query using django
I am looking to implement AND and OR logic in my Django query but after checking a lot of posts and searching I found that I can not implement AND-OR logic in the same query filter. Here is what I want to achieve I want to fetch records which have key ABC AND values Value1 OR Values2 OR Values3 AND key CDE AND values Value4 I am using python3.6, django1.11, mongoengine, and MongoDB filter = [ { "Key": "ABC", "Values": ["Value1", "Value2", "Value3"]}, { "Key": "CDE", "Values": ["Value4"]} ] Response: [ { "_id" : ObjectId("5ebd29286310619f046ba866"), "linked_account_id" : "135566327975", "payer_account_id" : "135566327975", "key" : "ABC", "Value" : "Value1" } { "_id" : ObjectId("5ebd29286310619f046ba866"), "linked_account_id" : "135566327975", "payer_account_id" : "135566327975", "key" : "ABC", "Value" : "Value2" } { "_id" : ObjectId("5ebd29286310619f046ba866"), "linked_account_id" : "135566327975", "payer_account_id" : "135566327975", "key" : "ABC", "Value" : "Value3" } { "_id" : ObjectId("5ebd29286310619f046ba866"), "linked_account_id" : "135566327975", "payer_account_id" : "135566327975", "key" : "CDE", "Value" : "Value4" } ] -
My django modelform not showing any inputfields
Currently i'm following a tutorial about django. But now im stuck in the process of creating forms in django. I watched a lot of tutorials and i have read the django docs, but i couldn't fix my problem so far. i try to create a form from a model from my database Here is my code: models.py class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out of Delivery', 'Out of Delivery'), ('Delivered', 'Delivered') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) views.py from django.shortcuts import render from .models import * from .forms import OrderForm def create_order(request): form = OrderForm() context = { 'form': form } return render(request, 'accounts/create_order.html', context) forms.py from django.forms import ModelForm from .models import * class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' create_order.html {% extends 'accounts/main.html'%} {% block content%} <form action="" method="POST"> {% csrf_token%} {{form.as_p}} </form> {% endblock %} The problem is, that the create_order.html shows me the labels of my form but not the input fields and i don't know why. i add a picture of my browser, so you an see what i mean. i would appreciate if anybody could help … -
Stuck in Watching for file changes with StatReloader
I made my project fine and when I run my server through a normal shell it works but I am trying to run my project through git bash. All the commands seem to work fine but when I do python manage.py runserver it gets stuck on Watching for file changes with StatReloader. Apparently after that I go to localhost:8000 but that and my 127 port 8000 are not responding and show that theres nothing there . No errors or anything and like I said if I python manage.py runserver through shell it works -
How to take comment and rating for product in django using class based view?
#Models.py class Products(models.Model): name = models.CharField(max_length=50) img = models.ImageField(upload_to='productImage') CATEGORY = ( ('Snacks','Snacks'), ('Juice','Juice'), ) category = models.CharField(max_length=50, choices=CATEGORY) description = models.TextField() price = models.FloatField() review = models.TextField() @property def no_of_ratings(self): sum=0 ratings = Rating.objects.filter(product=self) return len(ratings) @property def avg_rating(self): sum=0 ratings = Rating.objects.filter(product=self) for rating in ratings: sum=sum+rating.stars if len(ratings)>0: return sum/len(ratings) else: return 0 class Rating(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)], blank=True, null=True) comment = models.TextField(blank=True,null=True) #timestamp = models.DateTimeField(auto_now_add=True) # Views.py class ProductListView(ListView): model = Products template_name = 'products.html' context_object_name ='Products' class ProductDetailView(LoginRequiredMixin,DetailView): login_url = '/accounts/login' model = Products #templates <form method="POST"> {% csrf_token %} <input id="rating-value" name="rating"> <textarea style="margin-top:5px;" class="form-control" rows="3" id="comment" placeholder="Enter your review" name="comment"></textarea> <button type="submit" style="margin-top:10px;margin-left:5px;" class="btn btn-lg btn-success">Submit</button> </form> How can I take rating and comment in the class-based view and save it in database for the particular product which is being open in detailed view? I want to take the rating and comment for the particular product which is being shown to user using the productdetailed view class. -
get current user in form
im trying to get current login user in form field using ForeignKey , but im getting dropdown menu with list all users in database view.py @login_required def user_request(request): if request.method == 'POST': form = UserRequest(request.POST or None) if form.is_valid(): data = form.save(commit=False) data.user = request.user form.save() messages.success(request, 'Success') return redirect('home') else: form = UserRequest() print(form) context = { 'form': form, } return render(request, 'users/request.html', context) models.py class UserRequestModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_id = models.FloatField() email = models.EmailField() status = models.CharField(default='Pending', max_length=20) date = models.DateField() created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user form.py class UserRequestForm(forms.ModelForm): class Meta: model = UserRequestModel fields = ['user'] class UserRequest(UserRequestForm): date = forms.DateField() product_id = forms.IntegerField() class Meta(UserRequestForm.Meta): fields = UserRequestForm.Meta.fields + ['date', 'product_id'] what is missing to get current user in form field instead of all users in database? -
How to exclude rows with empty prefetch_related field
I used prefetch_related with Prefetch: prefetch_qs = Offer.objects.filter(price__gt=1000) prefetch = Prefetch('offers', queryset=prefetch_qs) How can I exclude rows with empty offers? It doesn't work, because annotate counted whole offers (not filtered in prefetch): filtered_qs = Product.objects.annotate( offers_count=Count('offers') ).filter( offers_count__gt=0 ).prefetch_related( prefetch ) -
Convert data inside a list into a given format in python
I'm trying to get an convert my list into a particular format(expected output), but I'm getting a problem. so I'm trying to order exceptions according to a given time and in a lexicographical order. My output: 21:15-21:30 IllegalAgrumentsException 1, 23:45-0:0 IllegalAgrumentsException 3, 1:0-1:15 IllegalAgrumentsException 0, 1:45-2:0 IllegalAgrumentsException 3, 2:0-2:15 IllegalAgrumentsException 0, 3:0-3:15 IllegalAgrumentsException 0, 21:15-21:30 NullPointerException 1, 21:15-21:30 NullPointerException 1, 22:15-22:30 NullPointerException 1, 23:0-23:15 NullPointerException 0, 23:30-23:45 NullPointerException 2, 23:30-23:45 NullPointerException 2, 0:30-0:45 NullPointerException 2, 1:30-1:45 NullPointerException 2, 2:30-2:45 NullPointerException 2, 22:0-22:15 UserNotFoundException 0, 22:30-22:45 UserNotFoundException 2, 22:30-22:45 UserNotFoundException 2, 22:30-22:45 UserNotFoundException 2, 22:45-23:0 UserNotFoundException 3, 23:15-23:30 UserNotFoundException 1, 0:0-0:15 UserNotFoundException 0, 0:45-1:0 UserNotFoundException 3, 1:15-1:30 UserNotFoundException 1, 2:15-2:30 UserNotFoundException 1, Expected Output : 21:15-21:30 IllegalAgrumentsException 1, 21:15-21:30 NullPointerException 2, 22:00-22:15 UserNotFoundException 1, 22:15-22:30 NullPointerException 1, 22:30-22:45 UserNotFoundException 3, 22:45-23:00 UserNotFoundException 1, 23:00-23:15 NullPointerException 1, 23:15-23:30 UserNotFoundException 1, 23:30-23:45 NullPointerException 2, 23:45-00:00 IllegalAgrumentsException 1, 00:00-00:15 UserNotFoundException 1, 00:30-00:45 NullPointerException 1, 00:45-01:00 UserNotFoundException 1, 01:00-01:15 IllegalAgrumentsException 1, 01:15-01:30 UserNotFoundException 1, 01:30-01:45 NullPointerException 1, 01:45-02:00 IllegalAgrumentsException 1, 02:00-02:15 IllegalAgrumentsException 1, 02:15-02:30 UserNotFoundException 1, 02:30-02:45 NullPointerException 1, 03:00-03:15 IllegalAgrumentsException 1 I got my output by performing a particular algorithm which is:(my approach) data = {'minute': 27, 'hour': 21, 'second': 12, 'data': 'IllegalAgrumentsException'} {'minute': … -
Django RunPython add data which have foreign key
I know we can use migrations (RunPython)[https://docs.djangoproject.com/zh-hans/3.0/ref/migration-operations/#runpython] to pre-add data into table. you see the example of the official document. def forwards_func(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Country = apps.get_model("myapp", "Country") db_alias = schema_editor.connection.alias Country.objects.using(db_alias).bulk_create([ Country(name="USA", code="us"), Country(name="France", code="fr"), ]) def reverse_func(apps, schema_editor): # forwards_func() creates two Country instances, # so reverse_func() should delete them. Country = apps.get_model("myapp", "Country") db_alias = schema_editor.connection.alias Country.objects.using(db_alias).filter(name="USA", code="us").delete() Country.objects.using(db_alias).filter(name="France", code="fr").delete() class Migration(migrations.Migration): dependencies = [] operations = [ migrations.RunPython(forwards_func, reverse_func), ] but how about if there have a foreign key of a model? such as: def forwards_func(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Country = apps.get_model("myapp", "Country") db_alias = schema_editor.connection.alias Country.objects.using(db_alias).bulk_create([ Country(name="USA", code="us"), Country(name="France", code="fr"), ]) Province = apps.get_model("myapp", "Province") Province.objects.using(db_alias).bulk_create([ Province(name="California", country="1"), Province(name="Rhodia", country="1"), ]) You see my requirement, I want to add several Provices, is my way right? or can I use the below way to achieve? USA=Province.objects.get(name="USA") Province.objects.using(db_alias).bulk_create([ Province(name="California", country=USA), Province(name="Rhodia", country=USA), ]) -
How to Display Data According to Different Different category on Page in Django?
I have multiple category store in my database, and i am developing a blog website, I want to display front page according to my requirement. There are lots of section available on front page and each section have different category, so data will be display according to category. Please let me know how i can do this. Here are my views.py file.... def article_list(request): category = Category.objects.all().order_by('created_at') blog = Post.objects.all().order_by('-created_at')[0:5] return render(request, 'article/index.html', {'category': category, 'blog': blog}) and here are my one section on index.html file...i want to get data from business category(this is store in my database) in this section. But i am getting all posts from database, please let me know how i can change in my for loop so that data will be display from business category. <ul class="list-posts"> {% for i in blog %} <li> <img src="/media/{{i.image}}" alt=""> <div class="post-content"> <h2><a href="single-post.html">{{i.name}}</a></h2> <ul class="post-tags"> <li><i class="fa fa-clock-o"></i>{{i.created_at}}</li> </ul> </div> </li> {% endfor %} </ul> -
please tell a good tutorial or documentation for import and export data to excel from html on django
I have a web application in which there is data in the form of a table and I need to add the function of exporting data to excel. is there any tutorial for beginners or documentation with clear examples? -
ImportError: cannot import name 'Author' from 'hymnbook.models.author' (C:\..\hymnbook\models\author.py)
I'm trying to make migration of this app that we have been developing, but when I run python manage.py migrate I get this error: from .author import Author ImportError: cannot import name 'Author' from 'hymnbook.models.author' (C:\Users\Asus-PC\Py charmProjects\hinario\ourhymnbook-py\novo\hymnbook\hymnbook\models\author.py) I'm using the version 3.7 of python and django 3.0.6 ATT: All models are in same directory but in separeted files This is the author model from django.db import models from .hymn import Hymn class Author(models.Model): first_name = models.CharField(max_length=20, null=False, blank=False, default='') last_name = models.CharField(max_length=20, null=False, blank=False, default='') country = models.CharField(max_length=50, blank=True, null=False) birth = models.DateTimeField() death = models.DateTimeField() hymn = models.ManyToManyField(Hymn, on_delete=models.CASCADE()) def __str__(self): return self.first_name, self.hymn And this is the hymn model from django.db import models import uuid from .verse import Verse from .language import Language from .hymnbook import HymnBook from .author import Author from .genre import Genre class Hymn(models.Model): number = models.IntegerField() title = models.CharField(max_length=100, blank=False, null=False) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) hymnBook = models.ForeignKey(HymnBook, on_delete=models.CASCADE) author = models.ManyToManyField(Author) date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.title I will be very thankful if some help me with this! Since now my thanks! -
django channels group_send not working suddenly
I have recently converted my existing django project to have a react front end. However , im facing the issue whereby the backend of my django-channels is not working. The issue im having is that the group_send method is not working in my case , as such the consumer does not receive the information generated by a signal in my models. Here is my code : consumers.py class NotificationConsumer (AsyncJsonWebsocketConsumer): async def connect (self): close_old_connections() user = self.scope["user"] if not user.is_anonymous: await self.accept() #connects the user to his/her websocket channel group_name = "notifications_{}".format(str(user)) print(group_name) await self.channel_layer.group_add(group_name, self.channel_name) async def disconnect (self, code): close_old_connections() user = self.scope["user"] if not user.is_anonymous: #Notifications notifications_group_name = "notifications_{}".format(str(user)) await self.channel_layer.group_discard(notifications_group_name, self.channel_name) async def user_notification (self, event): close_old_connections() print('Notification recieved by consumer') await self.send_json({ 'event': 'notification', 'data': { 'event_type': 'notification', 'notification_pk': event['notification_pk'], 'link': event['link'], 'date_created': event['date_created'], 'object_preview': event['object_preview'], } }) print(event) Models/signals def ChannelNotification(sender, instance, created, **kwargs): if created: channel_layer = get_channel_layer() print(channel_layer) group_name = "notifications_{}".format(str(instance.target)) print('inside channel signal') print(group_name) async_to_sync(channel_layer.group_send)( group_name, { "type": "user_notification", "notification_pk": instance.pk, "link": instance.object_url, "date_created": instance.time.strftime("%Y-%m-%d %H:%M:%S"), "object_preview": instance.object_preview, } ) Whenever an notification object is created in the database , the signal will be sent to my ChannelNotification which receives … -
Use field from foreign key value if field is blank in django model
I'm working on creating a basic inventory system and am trying out django. I'm curious of there is a, "best practices" way of creating a model that have fields themselves inherit values from another model if the child field is blank. For example, I want to be able to create two hosts, HostA and HostB which are both in the same classroom. Instead of having to go into both host instances and changing the classroom string when they get moved, I would like to create a group of hosts. That way if the "classroom" field is blank in HostA and HostB, but they have a foreignkey of ClassroomA with the "classroom" field filled out queries on them return the same string. Also, I want to be able to specify that the form factor of the computer is a laptop or desktop and since only the instructor computer is a laptop, I can set the "formfactor" string to desktop in the group, add the instructor computer to the group so it also gets the classroom string, and set its form factor as "laptop" so when I do a query for all laptops it doesn't show up as a desktop. So far … -
can we impliment charts like this with django
There is any possible way we can apply chart like this in python using matplotlib if not can anyone guide me in proper direction. -
Sending signal from django to C# client
I would like to add a simple remote control functions to the C# program. Surely the best way to do so is to make C# terminal itself a server and deal with the signal internally. But the thing is, I'll have to do it through a webpage that is made with django. What would be the best way to send signal from django/python to client that is made with C#? -
Django: Annotate list of related fields
I have an Company and User models with a related model CompanyRecruiter: class CompanyRecruiter(models.Model): organization = models.ForeignKey(Company, related_name="company_recruiters") recruiter = models.ForeignKey(User, related_name="company_recruiters") I want to annotate the list of user ids of users who are recruiters for companies to be able to filter on them later: Company.objects.annotate(some_stuff=some_other_stuff).values_list("user_ids", flat=True) # [ [1, 2], [1, 56], [] ] I already tried with Custom Aggregates and Subqueries without success. I use postgres. -
Create Superuser in Django Custom Auth Model
I want to create a superuser in my custom Authorization User model. Here is my models.py class User(AbstractUser): is_Admin = models.BooleanField(default=False) is_HR = models.BooleanField(default=False) is_MGR = models.BooleanField(default=False) is_EMP = models.BooleanField(default=True) class Admins(models.Model): def __str__(self): return self.user.username user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_admin = True first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) I want the Admins model to be able to access all user data, and access the Django Administration page. I haven't been able to figure it out for weeks. Have I done something wrong? -
Add form field from a different model in between another form in Django
I want to add fields for different models in one single form of another model. app_1/models.py from app_2.models import City class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics') city = models.ForeignKey(City, models.SET_NULL, blank=True, null=True) location = models.TextField(blank=True, null=True) app_1/forms.py from .models import UserProfile from app_2.models import City, State, Country class UserProfileUpdateForm(forms.ModelForm): class Meta: model = UserProfile fields = ['profile_pic', 'city', 'location'] # Here I want to add fields for new city, state and country # These will be shown onclicking a link only or else they will be hidden # These fields will be shown in between city and location fields app_1/views.py @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) up_form = UserProfileUpdateForm(request.POST, request.FILES, instance=request.user.userprofile) if u_form.is_valid() and up_form.is_valid(): u_form.save() up_form.save() messages.success(request, f'Your profile has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) up_form = UserProfileUpdateForm(instance=request.user.userprofile) context = { 'u_form': u_form, 'up_form': up_form } app_1/templates/app_1/profile.html {% extends 'app_1/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <legend> User Info </legend> {{ c_form|crispy }} {{ cp_form|crispy }} // Here I want to add a button onclicking which the required fields are shown. </fieldset> <div> <button type="submit"> Update </button> … -
Can't get Dynamic image URL work in Django
I'm trying to show an img with the Django dynamic url, but I cant get the dynamic url right url.py path('Obra/<int:id>/', views.detalle_obra, name="detalle_obra"), work-single.html ...<img src="{{object.img.url}}" views.py def works(request, id): obj = Work.objects.get(id=id) context= { 'object':obj } return render(request, 'works-single.html',context) when I render the template this image pop on the console: Not Found: /Obra/1/static/mySiteWork/img/uploads/Proyecto Obra Cerrillos/P5230031.jpg I don't know why is showing the "/Obra/1/". When I print {{object.img.url}} it will only show me the "static path static/mySiteWork/img/uploads/Proyecto Obra Cerrillos/P5230031.jpg" the static files works fine in the rest of templates Thanks in advance. -
How to structure a Django project to include both web application and API?
I am very new to Django and creating my first application. Is it possible to have both web application and API together in a project? I want this because I don't have a UI developer to use modern JS frameworks. So I want to use Django Built-In Templates. At the same time I want to expose API end points as well so to enable other applications to use my APIS -
I have created user and try to login then this error is poping out. 'NoneType' object is not callable
I am getting errors like the title above. I don't where are the mistakes. This is the code for views.py I have created user and when I try to login the user then this error popout. I am trying to get rid this from yesterday. I am using signal method from django.http import HttpResponse from django.shortcuts import redirect def admin_only(view_fun): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'customer': return redirect('user') if group =='admin': return view_fun(request, *args, **kwargs) return wrapper_function This is the code for views.py. I am debugging this from yesterday. from django.shortcuts import render,redirect from django.http import HttpResponse from django.template import RequestContext from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login as dj_login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from account.models import * from account.forms import OrderForm, CreateUserForm, CustomerForm from account.filters import OrderFilter from account.decorators import unauthenticated_user, allowed_users, admin_only @login_required(login_url='login') @admin_only def dashboard(request): orders = Order.objects.all() customers = Customer.objects.all() total_customer = customers.count() total_order = orders.count() delivered = orders.filter(status = 'Delivered').count() pending = orders.filter(status = 'Pending').count() context= {'orders':orders,'customers':customers, 'total_order':total_order, 'delivered':delivered,'pending':pending} return render(request,'account/dashboard.html',context)