Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms - create a variable based on user input selection
I am attempting to create a router config generator using django form. The idea is that the form takes input / choices and these are then displayed as part of a larger router config page using jinja and html. Where I am getting stuck is being able to create a new variable based on input and displaying this in the config_page.html. So for example lets say for 'WAN_SubnetMask' '30' is selected, I want to take the integers entered for 'WAN_Subnet', perform some very basic math e.g. add 2 and then create a new variable called 'WAN_IP'. I can display objects from my database in the however the 'WAN_IP' does not show as desired. Here is what I have come up with so far, I have tried adding the logic to create the 'WAN_IP' variable in both forms and views. forms.py from django import forms from .models import CPEconfig Router = [ ('2901', 'Cisco 2901'), ('1941', 'Cisco 1941'), WAN_SubnetMask = [ ('30', '30'), ('29', '29'), ] LAN_SubnetMask = [ ('30', '30'), ('29', '29'), ] class ConfigForm(forms.ModelForm): Router = forms.CharField(label='Select Router', widget=forms.Select(choices=Router)) WAN_Subnet = forms.GenericIPAddressField() WAN_SubnetMask = forms.CharField(label='WAN Subnet Mask', widget=forms.Select(choices=WAN_SubnetMask)) LAN_SubnetMask = forms.CharField(label='LAN Subnet Mask', widget=forms.Select(choices=LAN_SubnetMask)) class Meta: model = CPEconfig … -
Django not deleting stored messages when iterated over
I'm tryin to retrieve django messages through an api. However the messages are not being deleting upon iteration. It is being consumed with Vue JS on the front-end with a request made through Axios. def api_messages(request): all_messages = [] stored_messages = messages.get_messages(request) for message in stored_messages: all_messages.append({"message": message.message, "tag": message.tags}) response = {"messages": all_messages} return JsonResponse(response) -
Create an app only for the homepage in Django?
The rest of the apps do not seem relevant enough to make use one of their views as the main homepage. Is it a bad practice to create an app only for the homepage? What is the best practice for the homepage when developing in Django? Or at least the most common? -
translate django formset to apollo graphql mutation
I'm currently converting a full django app to a Django/React app and I need to update multiple objects in the same form. I'm using GraphQl with apollo client to link React and Django but I can't find to process to replicate the django Formset. Anyone has an idea ? -
Django and Celery - ModuleNotFoundError: No module named 'celery.task'
I wanted to start a periodic task in Django using Celery. Here are the relevant parts of my project: # celery.py from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookProjectSetting.settings') app = Celery('bookProjectSetting') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') The __init__.py looks like this: # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) My tasks.py file in my books app folder looks like this: from books.models import Book from celery.schedules import crontab from celery.decorators import periodic_task @periodic_task( run_every=(crontab(minute='*/10')), name="update_life_time_of_books", ignore_result=True) def update_life_time_of_books(): # do sth. I also set up redis as broker and installed the django-celery-beat stuff. But when I run the worker via the command: celery -A bookProjectSetting beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler Then I get the following error: File "/home/ac3l1k/Desktop/PROJECT/simpleDjangoProjects/bookProject/env/lib/python3.8/site-packages/celery/local.py", line 403, in _compat_periodic_task_decorator … -
Input text boxes in HTML for loop not recognized
so I am trying to align each Comment input box and comment text per updated posts. I am using for loop to iterate all the posts but only the text input in very first comment input box is recognized, and trying to enter text input on other boxes returns "enter a text" error. Will there be any way to fix this? Below is the code of my for loop. <ol> {% for post in posts reversed%} <li> {% csrf_token %} </form> <span class="details"> <a href ="{% url 'profile' post.created_by.id %}"> <label>Post by</label> <span id = "id_post_profile_{{post.id}}"> {{post.created_by.first_name}} {{post.created_by.last_name}} </span> </a> </span> <div id = "id_post_text_{{post.id}}"> {{post.content}} </div> <span class="details" id = "id_post_date_time_{{post.id}}"> {{post.creation_time}} </span> <br><label class = "comment">Comment: </label> <input type = 'text', id = "id_comment_input_text_{{post.id}}", class = "comment", name = "comment"> <button class = "comment", type = "submit", id = "id_comment_button_{{post.id}}", onclick = "addItem()" >Submit your comment</button> <span id="error" class="error"></span> {% for comment in post.test_set.all %} <li> {{comment.text}} </li> {% endfor %} </li> {% endfor %} </ol> -
What exactly does UpdateCacheMiddleware and FetchFromCacheMiddleware do?
I added these to my "settings.py" and Django seemed to cache every page. I wasn't expecting it to change the behaviour of the whole site. MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', (other middleware goes here) 'django.middleware.cache.FetchFromCacheMiddleware' ] This seems to happen on a view (every one) unless you override the behaviour by adding the never cache decorator for example. I guess that it is how it is supposed to work, right? from django.views.decorators.cache import never_cache @never_cache def fooView(request): return render(request, 'foo.html') If you put this decorator on every view that you didn't want to cache, then is that equivalent to not using this caching middleware and just putting a cache page decorator on all the other pages (the ones you do want to cache), or is there more to it? Using the caching middleware seems a bit drastic if you only need caching on a few pages. -
Django Admin model editor: grey out field if another boolean field is not checked
I have the following two fields in my Treatment Model: is_followup = models.BooleanField() parent_treatment = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) In the screen grab below from my admin page, I'd like to grey out "Parent treatment" if is followup is not checked. Is this possible? and if so, how to do it? -
Django request.POST QueryDict only returns true/on values from forms.booleanfield(required=False)
I am currently working on a Django admin action where you can create a model object from two or more already existing objects. Each object have an integerfield to store the current amount of items it has. When I'm using the action I want to be able to choose how many to take from each object and give to the new one. I also want to have an option to take all. Currently this is a simple Boolean checkbox field. My problem is, whenever i submit my form, where I for example only checked 2/4 checkboxes and two a number in the other two. The request.POST returns a QueryDict where the booleanfield called empty_field is like this: 'empty_field': ['on', 'on']. It doesn't account for False or 'off' which i need. The exact thing I am asking for, is how do I get the False/off values from request.POST? Thanks My views.py: def post(self, request, *args, **kwargs): form = MergeForm(data=request.POST) print(request.POST) My forms.py: class MergeForm(forms.ModelForm): batch_stock_choicefield = forms.IntegerField() empty_field = forms.BooleanField(required=False) class Meta: model = Batch fields = ['batch_stock_choicefield', 'empty_field'] My html div: <div> <form action="" method="POST"> {% csrf_token %} <table class="form-group"> <thead> <tr> <th>Batch id</th> <th>Stock item</th> <th>Quantity</th> <th>Take From Batch … -
Django read file from model, [Errno 2] No such file or directory
In Django I am using model forms to upload .stl file in model shown below. Once I submit form I see files get uploaded to myproject => media directory. But while reading uploaded file from the model, I am keep getting file not found error. I tried using both absolute and relative path without success, any help is much appreciated. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') model.py from django.db import models class StlFile(models.Model): uploaded_file = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) volume = models.FloatField(default=0.0) forms.py from django import forms from .models import StlFile class StlForm(forms.ModelForm): class Meta: model = StlFile fields = [ 'uploaded_file' ] After POST request numpy stl reads saved stl file from the model in views.py. views.py import os from django.shortcuts import render import numpy as np from stl import mesh from .forms import StlForm from .models import StlFile # Create your views here. def model_form_upload(request): if request.method == 'POST': form = StlForm(request.POST, request.FILES) if form.is_valid(): stl_file = form.save(commit=False) # Read file but Don't save the file yet stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter stl_file.save() # Extract mechanical properties from STL stl_path = stl_file.uploaded_file.url stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the … -
Design Database Efficiently with several relations - Django (PostgreSQL)
I want to know the most efficient way for structuring and designing a database with several relations. I will explain my problem with a toy example which is scaled up in my current situation. Here are the Models in the Django database 1.) Employee Master (biggest table with several columns and rows) class Emp_Mast(): emp_mast_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) desgn_mast = models.ForeignKey("hr.Desgn_Mast", on_delete=models.SET_NULL, null=True) qual_mast = models.ForeignKey("hr.Qualification_Mast", on_delete=models.SET_NULL, null=True) office_mast = models.ManyToManyField("company_setup.Office_Mast", ref_mast = models.ForeignKey("hr.Reference_Mast", on_delete=models.SET_NULL, null=True) refernce_mast = models.ForeignKey("hr.Refernce_Mast", on_delete=models.SET_NULL, null=True) This is how the data is displayed in frontend 2.) All the relational field in the Employee Master have their corresponding models 3.) Crw_Movement_Transaction Now I need to create a table for Transaction Data that that stores each and every movement of the employees. We have several Offshore sites that the employees need to travel to and daily about 50 rows would be added to this Transaction Table called Crw_Movement_Transaction The Crw_Movement Table will have a few additional columns of calculations of itself and rest of the columns will be static (data would not be changed from here) and will be from the employee_master such as desgn_mast, souring_mast (so … -
Applozic Django Web Integration Unresponsive
My Current Goal Access the Applozic web demo through my application Final Goal Add a 1 to 1 chat to my Django web application using Applozic with the Fullview UI. Users are able to log-in to my website and chat with each other through the Fullview UI while still having the same navigation bar as my website and being on my website. Expected results Being able to open the demo through my application and send a test message Actual results When I open the demo through my application nothing happens when I press the Enter Chat button What I've tried Sample I downloaded the demo, started it and entered my applozic account information. The first box (that requires the application id) said 'applozic-sample-app', I left this as is. Next, I entered my Applozic email and password to log in, as seen below. [![enter image description here][1]][1] It worked and I was able to send messages to their sample account. [![enter image description here][2]][2] Initial Integration to Django Application Next I copied and pasted the fullview.html file into my django project's template directory, created a new view that shows that file, added the url to redirect to the view and started … -
Django next page and prvious page not working
In my Django admin the previous and next page button is not working.it always go to the else part of the code. I don't know what's the issue. On clicking it always go on the same page {% load admin_list %} {% load i18n %} {% if pagination_required %} <ul class="pagination"> {% if cl.has_previous %} <li><a href="?p={{ cl.previous_page_number }}">&laquo;</a></li> {% else %} <li class="active"><span>&laquo;</span></li> {% endif %} {% for i in cl.paginator.page_range %} {% if cl.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?p={{ i|add:"-1" }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if cl.has_next %} <li><a href="?p={{ cl.next_page_number }}">&raquo;</a></li> {% else %} <li class="active"><span>&raquo;</span></li> {% endif %} </ul> <p style="float:right; margin:10px;">{{ cl.paginator.count }} Projects</p> {% endif %} -
Django progressive web app gives an error in all browsers after caching files
I was following this tutorial to make my website a PWA website using django-progressive-web-app. However, when I opened the app from firefox I get the following error: Oops. The site at http://localhost:8000/ has experienced a network protocol violation that cannot be repaired. The page you are trying to view cannot be shown because an error in the data transmission was detected. Please contact the website owners to inform them of this problem. When I open from Safari I get this error: Safari Can't Open the Page SAfari can't open the page "http://localhost:8000/base_layout/". The error is: "Response served by service worker has redirections" (WebKitInternal:0) I don't have chrome so I can't tell what is the error there, also running it from private -Incognito- window would solve the problem (and clearing data) So the problem is clearly with the cached code How can i fix? My code settings.py: INSTALLED_APPS = [ ... 'pwa', ... ] ... # Pwa settings PWA_SERVICE_WORKER_PATH = os.path.join( BASE_DIR, 'static/chat/js', 'serviceworker.js') urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('webpush/', include('webpush.urls')), path('', chat_views.home, name="home"), path('', include('pwa.urls')), path('base_layout/', chat_views.base_layout, name="base_layout"), ... ] serviceworker.js (path: Orgachat/static/chat/js/serviceworker.js var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function (event) { event.waitUntil( caches.open(staticCacheName).then(function (cache) { return cache.addAll([ '/base_layout' ]); … -
django_hosts - NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern name
Versions: Django 2.2.10 django-hosts 4.0 I have installed django_hosts successfully as per this documentation. I can successfully now access pages like https://blog.mysite.com However, the urls on the page are NOT resolved correctly. I have followed the example shown in the django_hosts official documentation. This is what my setup looks like: mysite/urls.py # imports etc. truncated for brevity # ... urlpatterns = [ path('', include(('home.urls', 'home'), namespace='home')), path('blog/', include('blog.urls', namespace="blog")), # ... ] home/urls.py from django.urls import path from django.conf.urls import include, url from .views import HomePageView, AboutView, TermsView, PrivacyView, \ sample, register, signin app_name = 'home' urlpatterns = [ path('', HomePageView.as_view(), name='index'), path('about', AboutView.as_view(), name='about'), path('terms', TermsView.as_view(), name='terms'), path('privacy', PrivacyView.as_view(), name='privacy'), path('sample', sample), path('register', register, name='register'), path('signin', signin, name='signin'), ] blog/templates/index.html <div class="container"> 116 <!-- Logo --> 117 <a class="logo" href="{% host_url 'home' host 'www' %}" style="text-decoration: none; font-size: 250%;"> 118 <img src="/static/assets/img/logo.png"> 119 My Site 120 </a> 121 <!-- End Logo --> -
AttributeError: module 'rest_framework.serializers' has no attribute 'serialize'
I am trying to serialize model instance as i can't reach out the url or the details of the 'followiing' model. from django.core import serializers from django.contrib.auth import authenticate from django.contrib.auth.models import update_last_login from rest_framework_jwt.settings import api_settings from django.core import serializers from rest_framework import serializers from urllib import request from rest_framework.permissions import AllowAny,IsAuthenticated from rest_framework import routers, serializers, viewsets from django.http import HttpResponse class UserSerializer(serializers.HyperlinkedModelSerializer): jsonfollowing = serializers.serialize('json', [ followiing ,]) class Meta: model = User fields = ('id','email','username','password','followiing','jsonfollowing') But i get the following error AttributeError: module 'rest_framework.serializers' has no attribute 'serialize' Does anybody know why? -
Django Data Migration
I want to write a data migration that read the records in the right order and delete the older records when the newer record was found I write the sql for this one. But I want to write data migration How can I write this my sql query is this ;with cte as ( select cid,count(*),max(id) as id from automation_irrig_record_data group by cid having count(*)>1 ) Delete from automation_irrig_record_data irrigRec where irrigRec.id in (select irrig.id from automation_irrig_record_data irrig JOIN cte on cte.cid=irrig.cid and cte.id !=irrig.id ) how can I write the Data migration my model name is automation_irrig_record_data id is my primary key cid is my field -
Create a user with a signal
I am trying to implement a signal to create a user when I create another model. When I create the sender object, the signal does not go through. Here is the code. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Spender from django.contrib.auth.models import User @receiver(post_save, sender=Spender) def create_user(sender, instance, created, **kwargs): spender = Spender if created: User.objects.create( username=spender.spender_username, first_name=spender.spender_firstname, last_name=spender.spender_lastname, email=spender.spender_email, password1=spender.spender_password1, password2=spender.spender_password2, ) User.save() -
Best way to store thousands of different files in Django Rest Framework?
I have to create an app in my DRF project that will be used to store thousands of different files (mostly PDF an Excel). The app will allow the user simple ACL requests and simple standard functionalities of a repository (see Recent files, move to different folders..). I've always used the hard disk of the server to store files in Django (through static root), I would like to have some feedback for this situation. Is it better to save them as binary on a databse? what approach would you suggest? In case of an external storage, which one is more functional for my situation? Thank a lot for your answers :) -
Save multiple values in one field (Django)
The problem: I have a model, which is referencing the basic User model of django. Right now, if I submit the form Django updates my database by replacing the existing data with the new one. I want to be able to access both of them. (In weight and date field) Models file: I saw other posts here, where they solved a problem by specifying a foreign key, but that doesn't solve it for me. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) weight = models.FloatField(max_length=20, blank=True, null=True) height = models.FloatField(max_length=20, blank=True, null=True) date = models.DateField(auto_now_add=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Views file: This is where I save the data that I get from my form called WeightForm from django.shortcuts import render from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import get_object_or_404 from users import models from users.models import Profile from .forms import WeightForm def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, … -
Graphite Browser "Exception Value: attempt to write a readonly database"
Well, i got into graphite and graphite-web and got stuck at the "Exception Value: attempt to write a readonly database" Error. I already tried chmod and chown at the db itself and im still getting this Error. File is under /opt/graphite/storage/graphite.db it got rwx-rwx-rwx (chmod 777) perms and i tried www-data as owner and put root back at it cause it got the same error. Environment: Request Method: GET Request URL: http://IP:8000/composer Django Version: 1.8.18 Python Version: 2.7.16 Installed Applications: ('graphite.account', 'graphite.browser', 'graphite.composer', 'graphite.dashboard', 'graphite.events', 'graphite.functions', 'graphite.metrics', 'graphite.render', 'graphite.tags', 'graphite.url_shortener', 'graphite.whitelist', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'tagging') Installed Middleware: ('graphite.middleware.LogExceptionsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/graphite/webapp/graphite/composer/views.py" in composer 27. profile = getProfile(request) File "/opt/graphite/webapp/graphite/user_util.py" in getProfile 35. return default_profile() File "/opt/graphite/webapp/graphite/user_util.py" in default_profile 51. 'password': '!'}) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 127. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get_or_create 407. return self._create_object_from_params(lookup, params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _create_object_from_params 439. obj = self.create(**params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create 348. obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save 734. force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base 762. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in _save_table 846. result = self._do_insert(cls._base_manager, … -
Hy i have a problem in my django app sohow i can solve it you will see all of the requireddocuments in the desc
Hy guys i'm achraf chahin a beginner web developer so i have a problem in my django app so it's a school management system that give courses exercices also link of live streams but there is a problem in my app even if the file is stored in my static files it giving me file not found i don't know what is the problem here some pics [This Images][1] [1]: https://i.stack.imgur.com/62sZW.png [This Images][2] [2]: https://i.stack.imgur.com/L5zlO.png [This Images][3] [3]: https://i.stack.imgur.com/9OIaj.png [This Images][4] [4]: https://i.stack.imgur.com/jOHcA.png [This Images][5] [5]: https://i.stack.imgur.com/i1Nj7.png [This Images][6] [6]: https://i.stack.imgur.com/MzRDQ.png [This Images][7] [7]: https://i.stack.imgur.com/lWjV3.png please help your answers will really gonna help me and others like me a lot -
looking for the best economic solution to deploy a flask application on the web. if you have any suggestion (MVC flask with JWT token ) please advice
looking for the best economic solution to deploy a flask application on the web, and also wants to know the deployment process. I am a beginner in python and flask, if you have any good structural suggestion (MVC in the flask with JWT token ) for API will be helpful. -
Summing up total amount from multiple models in Django
The title of my question has said it all. I have multiple models, and I want to add up the amount to derive the total amount, here's my code class FurnitureItem(models.Model): fur_title = models.CharField(max_length=200) fur_price = models.FloatField() fur_discount_price = models.FloatField(blank=True, null=True) fur_pictures = models.ImageField(upload_to='Pictures/', blank=True) label = models.CharField(choices=LABEL_CHOICES, max_length=1) category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24) fur_descriptions = models.TextField() slug = models.SlugField() date = models.DateTimeField(default=timezone.now) def __str__(self): return self.fur_title class FurnitureOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fur_ordered = models.BooleanField(default=False) item = models.ForeignKey(FurnitureItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.fur_title}" .... def get_final_fur_price(self): if self.item.fur_discount_price: return self.get_total_discount_fur_price() return self.get_total_item_fur_price() class FurnitureOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fur_items = models.ManyToManyField(FurnitureOrderItem) date_created = models.DateTimeField(auto_now_add=True) ordered_created = models.DateTimeField() fur_ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total_fur_everything(self): total = 0 for fur_order_item in self.fur_items.all(): total += fur_order_item.get_final_fur_price() return total class GraphicItem(models.Model): graphic_title = models.CharField(max_length=200) graphic_price = models.FloatField() graphic_discount_price = models.FloatField(blank=True, null=True) graphic_pictures = models.ImageField(upload_to='Pictures/', blank=True) label = models.CharField(choices=LABEL_CHOICES, max_length=1) category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24) graphic_descriptions = models.TextField() slug = models.SlugField() date = models.DateTimeField(default=timezone.now) def __str__(self): return self.graphic_title class GraphicOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) graphic_ordered = models.BooleanField(default=False) item = models.ForeignKey(GraphicItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.graphic_title}" .... def get_final_graphic_price(self): if self.item.graphic_discount_price: return self.get_total_discount_graphic_price() return … -
i have erroe ith paginating in django
hi im trying to use django paginator but i get 404 error i want to reach to this url http://127.0.0.1:8000/products/2/?page=1 but i get 404 error where is the problem ?please help me views.py from django.core.paginator import Paginator, EmptyPage, InvalidPage def sort(request, value): category = Category.objects.all() if(value=='2'): products_list = Product.objects.all().order_by('price') elif(value=='3'): products_list = Product.objects.all().order_by('-price') elif(value=='4') : products_list = Product.objects.all().order_by('-id') elif (value == '5'): products_list = Product.objects.all().order_by('-view') paginator = Paginator(products_list,5) try: page=int(request.GET.get('page','1')) except: page = 1 try: products = paginator.page(page) except(EmptyPage,InvalidPage): products = paginator.page(paginator.num_pages) context = { 'products': products, 'category': category, 'value' : value } return render(request, 'shopPage.html', context) urls.py path('products/<value>', views.sort, name='sort'), shopPage.html <div> <ul> {% if products.has_previous %}> <li><a href="products/?page={{ products.previous_page_number }}">previous</a></li> {% endif %} {% for pg in products.paginator.page_range %} {% if products.number == pg %} <li class="active"><a href="products/?page{{ pg }}">{{ pg }}</a></li> {% else %} <li><a href="products/?page{{ pg }}">{{ pg }}</a></li> {% endif %} {% endfor %} {% if products.has_next %} <li><a href="products/?page={{ products.next_page_number }}">next</a></li> {% endif %} </ul> </div>