Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 Bad Gateway nginx Server
I am following satssehgal tutorial to host a website on a cloud server. I am unfortunately getting a 502 Bad Gateway. Here is my nginx/error.log 2021/06/25 12:18:58 [crit] 2494#2494: *1 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:19:07 [crit] 2494#2494: *3 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:19:08 [crit] 2519#2519: *1 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:19:10 [crit] 2519#2519: *1 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:20:58 [crit] 2519#2519: *5 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/admin", host: "139.162.255.54" 2021/06/25 12:21:03 [crit] 2519#2519: *5 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET /polls HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/polls", host: "139.162.255.54" 2021/06/25 12:26:04 [crit] 2519#2519: *9 connect() to … -
Varying cloudinary images in a django template
I'm trying to vary images based on a variable - id in the Django template. <img href="'https://res.cloudinary.com/.../image/'|add:{{ object.id }}|add:'.png'" class="mx-auto" width="100px" alt="No Image"/> object.id is passed into the template from a Queryset object (i.e. object). Page load, but image does not show up and goes to alt="No Image". -
django form queryset choices
this is my model class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_variation") name = models.CharField(max_length=50) this is my form: class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, label=_('Quantity'),widget=forms.NumberInput(attrs={'class': 'form-control text-center'})) variation_select = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['variation_select'].queryset = Variation.objects.filter(i want to filter there by foreign key, product_id=product_id) any suggestion? -
How can I capture a picture from webcam and store it in a ImageField or FileField in Django?
I am trying to capture a photo from a webcam and store it in a FileField or ImageField. But I am not getting how to get the captured image data on request. Please check my HTML template, javascript code, and views.py. Can anyone suggest a way to get this image data captured using javascript, on submitting the form in HTML? class UserDetails(models.Model): User_name = models.CharField(max_length= 300) User_phone = models.BigIntegerField() User_address = models.TextField() User_pic = models.FileField(upload_to='documents/%Y/%m/%d') My HTML form {% extends 'base.html' %} {% load static %} {% block content %} <form method="POST" action="/usersave/" enctype="multipart/form-data"> {% csrf_token %} .... <div class="card-body"> <div class="row"> <div class="col-md-4 ml-auto mr-auto"> <div class="form-group"> <video id="video" autoplay ></video> <canvas id="canvas"></canvas> </div> <button id="startbutton1" class="btn btn-outline-secondary btn-sm">Take Photo</button> <script src="{% static "assets/js/capture.js" %}"></script> </div> ..... <div class="img pull-center" > <img id ="photo" name="photo" alt="The screen capture will appear in this box."> </form> </div> </div> </div> Views.py def usersave(request): if request.method== 'POST': User_name = request.POST["Username"] User_phone = request.POST["Userphone"] User_address = request.POST["Useraddress"] pic = request.FILES["photo"] User_info= UserDetails(User_name=User_name, User_phone=User_phone, User_address=User_address, User_pic= pic) User_info.save() return render(request, 'some.html') Using this capture.js file I am able to take photo and populate the HTML file in img tag (function() { var width = 320; … -
Django - Passing exceptions in large try block without skipping whole block?
I have a view in django which gathers a lot of data depending on user input. Sometimes, not all of the data will be available for the specific query. I currently have large try blocks, but it is less than ideal as it will skip the whole block and not show any data. Is there any way to continue past the errors without having to do a ton of individual try blocks? Here is a much shorter example to show what I currently have. try: year1 = income[0]['date'] year2 = income[1]['date'] year3 = income[2]['date'] year4 = income[3]['date'] year5 = income[4]['date'] except Exception as e: pass This will pass the whole block if year5 is unavailable. One solution would be to put each year in it's own try block, but that would add 100s of lines of code if not thousands. It would be great if there was a simple way to maintain the data that is successfully collected, and pass the ones that throw an exception (or give them a default value). Thanks! -
Adding data to a Django model associated with a user field
I am creating an application that contains the model UserDetail. In this model, there are 3 fields, a field for donations, points, and a field for the user who is associated with these points. I show these fields in the dashboard.html file, and everything works. My problem is that I manually have to go into /admin and give a user in the database a points and donations field. I want my program to automatically populate the user, donations, and points data to the database when their account is completed, giving the points and donation field a value of 0 and associating it with the user. Below is my code for both the dashboard.html view, which allows the data to be shown on the dashboard page, my UserDetail model, and the view for when the account is created. Thank you to everyone who helps! Model: class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) Dashboard view: @login_required(login_url='/login/') def dashboard(request): user = request.user # assuming there is exactly one # this will break if there are multiple or if there are zero # You can (And should) add your … -
Django: How to add query params to queryset as is done in Pagination?
Our site is DRF backend, with Vue frontend. It incorporates extensive filter options, so any endpoint could have many query parameters - like example.com?name__icontains=bob&...etc. We have a situation on one view where we need to return a sum of one column. Instead of creating a separate endpoint for the frontend to hit, we want to add it to the results of the original view. Like so... { "pagination": { ...pagination stuff... }, "results": [ { "id": 1, "task": "DMSD-50", ...other fields..., "duration": 204 }, { "id": 2, "task": "DMSD-53", ...other fields..., "duration": 121 }, ...more rows... ], "totals": { "duration": 955 } } My first attempt was to add this to the get() method of the view: def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) queryset = self.get_queryset() totals = queryset.aggregate(total_duration=Sum('duration')) response['totals'] = { 'duration': totals['total_duration'] or 0 } return response ...which worked when I did the full (unfiltered) list. But when I added filters in the URL, the total was always the same. That made me realize that get_queryset() doesn't add query parameters from the URL. I then realized that the pagination class must be incorporating query parameters, so my second solution was to add this code … -
Error while performing Cloud Build and connecting to Cloud PostgreSQL
I am trying to automate the process of building a Django app on Google Cloud Build. This app has to communicate with a PostgreSQL DB hosted on Cloud SQL and there're three stages I would like to complete: Building the image with a Dockerfile Pushing the image to Artifact Registry Running Django migrations python manage.py migrate by connecting to Cloud PostgreSQL through Cloud SQL Proxy I have successfully made the first two stages work with these configuration files: cloudbuild.yaml steps: # Build the container image - id: "build image" name: "gcr.io/cloud-builders/docker" args: ["build", "-t", "${_IMAGE_TAG}", "."] # Push the container image to Artifact Registry - id: "push image" name: "gcr.io/cloud-builders/docker" args: ["push", "${_IMAGE_TAG}"] # Apply Django migrations - id: "apply migrations" # https://github.com/GoogleCloudPlatform/ruby-docker/tree/master/app-engine-exec-wrapper name: "gcr.io/google-appengine/exec-wrapper" # Args: image tag, Cloud SQL instance, environment variables, command args: ["-i", "${_IMAGE_TAG}", "-s", "${PROJECT_ID}:${_DB_REGION}:${_DB_INSTANCE_NAME}=tcp:127.0.0.1:3306", "-e", "DJANGO_SECRET_ID=${_DJANGO_SECRET_ID}", "--", "python", "manage.py", "migrate"] # Substitutions (more substitutions within the trigger on Google Cloud Build) substitutions: _IMAGE_TAG: ${_REPOSITORY_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPOSITORY}/${_IMAGE_NAME}:${COMMIT_SHA} # Display the image in the build results # https://cloud.google.com/build/docs/building/build-containers#store-images images: - '${_IMAGE_TAG}' Dockerfile FROM python:3.7-slim # Add new /app directory to the base image ENV APP_HOME /app WORKDIR $APP_HOME # Removes output stream buffering, allowing for more efficient logging … -
How to define range in "for" at Django template
Django ListView returns object_list, and in Template I want to take the data only once using "for". So I wrote this code. {% for item in object_list(range(1)) %} But this code does not work. Here is the error code. Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(range(1))' from 'object_list(range(1))' I know my for code is something wrong, please teach me how to write properly. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you. -
how to display a form in function based view
I have got an error when I tried to display a form in function-based view in Django. I could display it in another HTML file and users can make their comments to the blog. But, I think it can be more convenient for users if they can make a comment on the same blog-detail HTML file, so I wanna implement it. When I tried, this error showed up. "NoReverseMatch at /blogs/blog/30/ Reverse for 'blog' with no arguments not found. 1 pattern(s) tried: ['blogs/blog/(?P[0-9]+)/$']" Any comments can help me and thanks for your time in advance!! Here are the codes I wrote... from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('user', 'text',) #views.py @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) form = CommentForm() # if request.method == 'POST': # form = CommentForm(request.POST) # if form.is_valid(): # comment = form.save(commit=False) # comment.blog = blog # comment.save() # return redirect('blog', pk=blog.pk) # else: # form = CommentForm() if blog.link_1 is not None and blog.link_2 is not None: link_1 = blog.link_1 link_2 = blog.link_2 context = { 'blog': blog, 'link_1': link_1, 'link_2': link_2, 'form': form, } elif blog.link_1 is not None or blog.link_2 is … -
Python/Django read a cookie that was set with JavaScript
I am building an application using Python/Django. I have set a cookie using Javascript: document.cookie = "color=blue" In my Django-middleware-function I need to provide a choice to redirect or not based upon the value of the cookie. I do not know how to read the cookie. I don't even know if it is possible. Any advice would be appreciated. -
How to connect the m2m_change with pre_save signal?
I have a model MyTracingModel that track the changes that occur on the other models, i create a signal function that compares the old model with the instance and if they are equal then it will just pop the fields out so I keep only the changed fields. this function does not register the changes that accur on the ManyToManyfields, so I created a signal that registers the changes that occur on the many to many fields. Problem: I don't now how to append the fields that I got from the m2m_changed function in the data variable that is in the pre_save function. Goal: I need to have all the changed fields in one palce @receiver([m2m_changed]) def __init__(instance, sender, action, **kwargs): ... if action == "post_remove": data.append({fieldname:[ids..]}) @receiver([pre_save]) def __init__(sender, instance, **kwargs): data = modelfields ... for field in modelfields: if field == field: data.pop(key) if key != 'id' else None MyTracingModel.ojbects.create(data=data) Note: don't warry about infint recursoin issue I set if model.__name__ == MyTracingModel`:pass -
Change password form or link in abstractuser django custom user model
I created a custom user model using abstractuser and replace mobile with username and then recreate user page in admin but my problem is I don't have change password form (in default Django authentication) and if I put save method and change other data in the user model then empty password stored and user can not login any more models.py: class MyUser(AbstractUser): username = None mobile = models.CharField(max_length=15, unique=True) international_id = models.CharField(max_length=25, blank=True, null=True) company_name = models.CharField(max_length=255, blank=True, null=True) business_code = models.CharField(max_length=25, blank=True, null=True) otp = models.PositiveIntegerField(blank=True, null=True) otp_create_time = models.DateTimeField(auto_now=True) objects = MyUserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = [] backend = 'custom_login.mybackend.ModelBackend' admin.py: class MyUserAdmin(admin.ModelAdmin): list_display = ['mobile','company_name'] search_fields = ['mobile'] form = UserAdminChangeForm fieldsets = ( (None, {'fields': ('mobile','email','password','otp')}), ('Personal Info', {'fields': ('first_name', 'last_name','international_id')}), ('Company Info', {'fields': ('company_name','business_code')}), (_('Permissions'), {'fields': ('is_active', 'is_staff','is_superuser','groups','user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) class Meta: model = MyUser admin.site.register(MyUser,MyUserAdmin) forms.py: from django import forms from .models import MyUser from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext as _ class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ # password = ReadOnlyPasswordHashField(label=("Password"), # help_text=("Raw passwords are not … -
virtualenv raises importerror because of changing app name in django
I've used [this link] to rename my django app. So I've edited some files and table's name and so on. But as it has been mentioned in that link, There is problem with virtualenv. So how can I fix it? I've change name "notes" to "blog". -
Django - divert all messages running in a Google Cloud Engine Instance into a file
How can I divert all messages of a Django application that runs in a Google Cloud Engine instance into a file ? This is my current settings for the logging options : LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/mylogs.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } It provides output (which are created with logging functions) to some extend, however when there is a stack trace and exception. It does not provide the output into the file. This is how I execute Django on the console : python3 manage.py runserver --noreload >> /tmp/mylogs.log -
HTML changes not reflecting in Django
I am new to Django and have started a project but I am facing an issue. All my pages are working fine and the changes I make are getting reflected on the webpage but when I make a changes to my login page, no changes are reflected on the webpage (It is a simple static page, I only used Django template and nothing else). I deleted all the content in the html file and even deleted the whole html file but no error or change was shown and the page loaded just the way it was when first created. I also tried pressing Shift+F5 but nothing worked :( The output in terminal was as follows (even after deleting the file): [25/Jun/2021 10:24:23] "GET /login HTTP/1.1" 200 8183 -
I am currently using DRF token based authentication where i want to give a role to the user of either a mentor or the student, how to achieve that?
serializers.py for authentication from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password') views.py for authentication from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password') models.py class NormalUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.IntegerField(default=0) email = models.EmailField() mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return str(self.name) class Mentor(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) name = models.CharField(max_length=30) email = … -
Local Development Server Errors
Exception happened during processing of request from ('127.0.0.1', 56261) Traceback (most recent call last): File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
My pipenv is not recognized whenever i try to create a virtual environment, how do i solve this?
I've installed pipenv on my terminal, however whenever I try to start pipenv shell to create a virtual environment this error shows up "pipenv : The term 'pipenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + pipenv shell + ~~~~~~ + CategoryInfo : ObjectNotFound: (pipenv:Strin g) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException" what is wrong and how do I get around it? -
how to get dropdown selected value and not text while submitting form in django views?
i have a dropdown list which you can see on left side. i want to fetch the value of dropdown in my views.py but when i cleaned_data['city'] it gives me the text of the selected value and not the value . how can i get this? can anyone help me models.py from django.db import models from .validator import validate_age # Create your models here. class City(models.Model): city_name=models.CharField(max_length=200) def __str__(self): return self.city_name class Employee(models.Model): name = models.CharField(max_length=200) pan_number = models.CharField(max_length=200, unique=True, null=False, blank=False) age = models.IntegerField(validators=[validate_age]) gender = models.CharField(max_length=10) email = models.EmailField() city = models.ForeignKey(City, on_delete=models.DO_NOTHING) def __str__(self): return self.name def clean(self): if self.name: self.name =self.name.strip() views.py def employee(request): context = {} if request.POST: form = EmployeeForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] pan_number = form.cleaned_data['pan_number'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] city = form.cleaned_data['city'] gender = form.cleaned_data['gender'] print(city) with connection.cursor() as cursor: cursor.callproc('insert_employee', [name, pan_number, age, gender, email, city]) # qs_add = Employee(name=name, pan_number=pan_number, email=email, age=age, city=city, gender=gender) # qs_add.save() messages.add_message(request, messages.INFO, 'Employee save successfully') context['form'] = context['form'] = EmployeeForm() else: context['form'] = EmployeeForm(request.POST) else: context['form'] = EmployeeForm() return render(request, 'app/employee.html', context) -
How to insert into multiple postgres tables connected with foreign keys in Django ORM
I want to insert into two tables one table is Invoices other one is products. Invoice table connected to product table with product_id fk. A invoice can have multiple products at the same time and invoice detail and product details shall be insert at the same time (there is no existing product on products table) so I have to models: class Invoice(models.Model): ... product = model.Foreignkey (products, releted_name="invoice_product", on_delete=models.CASCADE) ... class Products(models.Model): id = models.Charfield() name = models.Charfield() ... -
How to set date limit to a user for a particular package in Django
I have a model named as Plans which is independent of user but when user buys a plan it stored in UserPlanSubscription model so problem is when user buys particular plan user will get that plan for a Month, Year or 6 Month so I want to set expiry of that plan for example if I buyed a Plan for 6 Month so it should expire after 6 Month how can I do this. this is my UserPlanSubscription model class UserPlanSubscription(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE,null=True,blank=True) plan = models.ForeignKey(Plans, on_delete=models.CASCADE,null=True,blank=True) paid = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False,null=True) and this is my Plans model class Plans(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) plan_name = models.CharField(max_length=255, null=True) plan_note = models.CharField(max_length=255, null=True) plan_price = models.CharField(max_length=255, null=True) access_to = models.ManyToManyField(Add_e_office) -
i am getting multivaluedictkeyerror while getting values from the form
i wanted some details to update in user details model but when i try to read valued in th request it show the multivaluedictkeyerror. error image error image 1, error image 2 views.py @csrf_exempt def updateuser(request): myuser=request.user obj=User.objects.get(id=myuser.id) if request.method == 'POST': p=request.POST['phone'] a=request.POST['add'] e=request.POST['edu'] em=request.POST['email'] c=request.POST['country'] s=request.POST['state'] userdetails.objects.create(user=obj,phone=p,address=a,edu=e,country=c,state=s) return render(request,'profile.html') html code <form action="updateuser" method="POST"> {% csrf_token %} <div class="row mt-3"> <div class="col-md-12"><label class="labels">PhoneNumber</label><input type="tel" class="form-control" placeholder={{uobj1.phone}} name="phone" required></div> <div class="col-md-12"><label class="labels">Address</label><input type="text" class="form-control" placeholder={{uobj1.address}} name="add" required></div> <div class="col-md-12"><label class="labels">Email ID</label><input type="email" class="form-control" placeholder={{uobj.email}} name="email" ></div> <div class="col-md-12"><label class="labels">Education</label><input type="text" class="form-control" placeholder={{uobj1.edu}} name="edu" required></div> </div> <div class="row mt-3"> <div class="col-md-6"><label class="labels">Country</label><input type="text" class="form-control" placeholder={{uobj1.country}} name="country" required></div> <div class="col-md-6"><label class="labels">State/Region</label><input type="text" class="form-control" value="" placeholder={{uobj1.state}} name="state" required></div> </div> <div class="mt-5 text-center"><button class="btn btn-primary profile-button" type="submit">Save Profile</button></div> </form> -
Page not found (404) on django
I am using django 3.2 to build a personal e-commerce project, Got Error-Page not found (404) on visiting my products page url Method:GET URL:http://127.0.0.1:8000/products Using the URLconf defined in main.urls. I have followed all the conventions and the other pages are all working but this one is giving me a[urls[\views][1][browser display] hard time as i feel everything is correct, i might be wrong, pls help and if u need to see more of my code, please let me know. This is my code for urls from django.urls import path from django.views.generic.detail import DetailView from django.views.generic import * from main import models, views app_name = 'main' urlpatterns = [ path('', views.home, name='home'), path('about_us/', views.about_us, name='about_us'), path('contact-us/', views.ContactUsView.as_view(), name='contact_us'), path( "products/<slug:tag>/", views.ProductListView.as_view(), name="products" ), path("product/<slug:slug>/", DetailView.as_view(model=models.Product), name='product'), ] my code for views from django.views.generic.edit import FormView from .forms import ContactForm from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.shortcuts import get_object_or_404 from main import models class ProductListView(ListView): template_name = "main/product_list.html" paginate_by = 4 def get_queryset(self): tag = self.kwargs['tag'] self.tag = None if tag != "all": self.tag = get_object_or_404( models.ProductTag, slug=tag ) if self.tag: products = models.Product.objects.active().filter( tags=self.tag ) else: products = models.Product.objects.active() return products.order_by("name") then my browser Page not found (404) … -
when I try to run my django server I get an error
The error is django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: something apparently I have 2 applications that are the same but I don't I checked. Not sure how to fix this.