Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
where should i add the csrf token in this?
i really don`t understand what most of this html does as i am not comfortable with html. along with the location of where to add the token if one could explain to me what most of this does it would be greatly appreciated <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" href="static/css/body.css"> <body> <div class="bgimg w3-display-container w3-text-black"> <div class="w3-display-middle w3-jumbo"> <button class=" w3-button w3-white">HSEA STOCK</button> </div> <div class="w3-display-topleft w3-container w3-xlarge "> <p><button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button></p> </div> </div> <div id="id01" class="modal"> <form class="modal-content animate" action="/login" method="POST"> {% csrf_token %} <div class="imgcontainer"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="username" required <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="passwword" required> <button type="submit">Login</button> <label> <input type="checkbox" checked="checked" name="remember"> Remember me </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button> <span class="psw">Forgot <a href="#">password?</a></span> </div> </form> </div> <script> // Get the modal var modal = document.getElementById('id01'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> </body> sorry if this seams very obvious but i did not make this page and i am having trouble adding β¦ -
Django: User able to sign up in custom registration form even if the email address is already used by another user
In my web app, I have a custom registration and login form which I made using HTML/CSS and not Django's form.as_p and Bootstrap. I have the following code in views.py: def loginUser(request): logout(request) if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/dashboard/') #otherwise show the user an error message else: login_message = "Your username or password is incorrect." return render(request, 'Meetings/index.html', {'login_message': login_message}) return render(request, 'Meetings/index.html') def signUp(request): if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password_confirm = request.POST['password-confirm'] if(valid_form(username, email, password, password_confirm)): #create the new user user = CustomUser(name=username, email=email, username=username) user.set_password(password) user.save() user = authenticate(username=username, password=password) login(request, user) return redirect('/dashboard/') else: message = "Something went wrong." return render(request, 'Meetings/index.html', {'message': message}) return render(request, 'Meetings/index.html') I have a CustomUser model in models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True) password = models.CharField(max_length=50, null=True) When a user signs up, a CustomUser is created and they are logged in to the app. However, if another user signs up using an email address that is already taken by another existing user, they are β¦ -
Make form fields wider in Django+Bootstrap
I was wondering how I can make the form inputs themselves take up the same portion of the second column; I want the labels to be in one column and the inputs to take up the same percentage of the second column Here is my code in my HTML template: <form method="POST" class="form mt-3 mb-3"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="{{ field.name }}" class="col-sm-4 col-form-label">{{ field.label_tag }}</label> <div class="col-sm-6"> {{ field }} </div> </div> {% endfor %} {% buttons %} <button type="submit" class="btn btn-success float-right mb-3"><i class="fa fa-plus" aria-hidden="true"></i> Create</button> {% endbuttons %} </form> -
Django Populate Dropdown Menu With Choices From Many To Many Database
I would like to populate my dropdown menu with records from the Subject table which is a many to many choices field that is populated with subjects by adding them manually from the admin page. A course can have many subjects such as "business" and "marketing". Code: https://dpaste.de/825n How would I do that with django-select2 or use a form with model select or multiple model select? https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelchoicefield https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelmultiplechoicefield https://django-select2.readthedocs.io/en/latest/ Or maybe I could do it with a for loop on the template? For loops I have tried but no luck: https://dpaste.de/5MVi Desired Result: https://imgur.com/a/Iw9lk6I Can someone please help me figure it out? I have been stuck for a while now. -
How do I use the input of one field in multiple places on a form?
I'm very new to Django, so please forgive me if I'm using some of the terminology incorrectly. In one of my templates, I'm trying to use a form that has multiple input fields. In this specific case, the value of the two fields will always be the same (userName and userID will always match if they are at this template) and I do not want to alter the form itself. For this reason, I want to customize the form in this template so that there is only one place for the user to provide input, and use that in both fields of the form so that the user doesn't need to type in their ID twice. This is the code fragment I'm currently using: <form method="post"> {% csrf_token %} <label>ID:</label> <input type="text" name="userID" id="userID" placeholder="Type your ID number here."> <input type="hidden" name="userName" id="userName" value=userID> <button type="submit">Login</button> </form> I know that the issue is with the "value=userID" bit, but I've been searching and I can't figure out how to use information from one input field in multiple places. How do I take the userID and submit it as the userName without requiring the user to input it twice? -
Django: what is the better way to get users info from models in view or template?
I have few django models and I want display some information the for several users in the template. Below are the models: class CustomUser(AbstractUser): def __str__(self): return self.email class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_url = models.URLField(max_length = 200, blank = True) slug = models.SlugField(unique=True, blank=True) class subscription(models.Model): creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',) booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster') sub_value = models.FloatField(blank = True) sub_id = models.TextField(blank = True) status = models.BooleanField(default=False) dateSubscribed = models.DateTimeField(default=timezone.now) dateSubscriptionEnded = models.DateTimeField(default=timezone.now) paymentCount = models.FloatField(default= 0) I want to pass few users to template and display how many posts and subscriptions each user has? I am wondering what is the best way to do it? Is better number of posts and subscribers information in the view and just pass those things to template or pass users get that information in the template? Thanks! -
Getting column from table as an array to using context_processor on webpage
I am trying to pull column data from DB table using a Django context_processor. This table column contains different versions of the primary data. So need to collect all versions and pass it as context to the html page. The context processor function is as below. I am able to get all the versions, but the format is weird. Any idea how to clean and only get the versions in an array? There are 2 versions currently Version1.9 and Version2.0 in the Column. context_processor.py def Version(request): value = ModelName.objects.values_list('version') if value: return { 'getVersion' : value } else: print("Unable to get Version") return { 'getVersion' : "" } Console Output: &lt;QuerySet [(&#39;Version1.9&#39;,), (&#39;Version2.0&#39;,), (&#39;Version1.9&#39;,), (&#39;Version2.0&#39;,)]&gt; -
Page not found (404) - The current path, editEstHab/, didn't match any of these
I have a problem when I want to update an existing object... in another project, I used a similar lines of code, but now, it doesn't work when I'm going to save the actual information... models.py class habitacion(models.Model): nroHabitacion = models.IntegerField(null=False) tipoHabitacion = models.CharField(max_length=70, null=True) tipoCama = models.ForeignKey(tipoCama, on_delete=models.CASCADE, blank=True, null=False) accesorios = models.CharField(max_length=70, null=True) precio = models.IntegerField(null=False) estado_habitacion = models.ForeignKey(estadoHab, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.tipoHabitacion forms.py class UpdateHabForm(forms.ModelForm): class Meta: model = habitacion fields = [ 'estado_habitacion' ] views.py def editHab(request,id_habitacion): # llamando datos de habitacion seleccionada hab = habitacion.objects.get(id=id_habitacion) if request.method == 'GET': form = UpdateHabForm(instance=hab) else: form = UpdateHabForm(request.POST, instance=hab) if form.is_valid(): form.save() context = { 'form' : form, 'hab' : hab } return render(request,"editEstHab.html",context) urls.py path('editEstHab/<id_habitacion>', views.editHab, name="editEstHab"), enter image description here the more stranger thing is... at the end says The current path, editEstHab/, didn't match any of these., but when I search on my project, the only time that I use editEstHab/ is in urls.py... So... help :( I don't have any clue about what is my mistake. -
SAXO Bank API ERROR json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) for
Hi I have been having a lot of problems trying to consume the api from SAXO Bank. Basically I am trying to achieve the GET request, however I am not very familiar with web api's. Instead of getting the data, I got this error instead : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). Below are my codes from flask import Flask, render_template, request import json import requests app = Flask(name) @app.route('/api', methods=['GET']) def temperature(): r = requests.get('https://gateway.saxobank.com/sim/openapi/port/v1/balances?AccountKey=Y8lhERGA9duVrD1IY-7cpA==&ClientKey=Y8lhERGA9duVrD1IY-7cpA==') json_object = r.json() return r.json(result) if name == 'main': app.run(debug=True) -
Broken migrations with Django sites framework to restrict URLs access
I want to share single code-base Django (2.2) over 2 URLs : foo.domain.ltd & bar.domain.ltd. on foo.domain.ltd: all the Django URLs are available on bar.domain.ltd: only some URLs are available, all other return 403 error I expected using the sites framework (django.contrib.sites) to reach this goal : 1 code base 2 domains configured in the sites framework 2 gunicorn instances with appropriate configuration : core.settings.foo with SITE_ID = 1 core.settings.bar with SITE_ID = 2 1 nginx server listening clients and forwarding requests to the appropriate gunicorn instance depending the xxx.domain.ltd used The issue I encountered is that sites framework looks like model oriented : You can associate models to one, two (β¦) sites. I try to set urls depending on the sites, but I broke the ./manage migrate toolβ¦ 1) Settings the sites framework to my project and a dualsite app to host associated code : core.settings : INSTALLED_APPS = [ # (β¦) "django.contrib.sites", "dualsite.apps.DualsiteConfig", ] core.settings.foo : from core.settings import * SITE_ID = 1 core.settings.bar : from core.settings import * SITE_ID = 2 dualsite.migration.0001_set_sites : from django.db import migrations def my_sites(apps, schema_editor): Site = apps.get_model("sites", "Site") initial_site = Site.objects.get(id=1) initial_site.domain = "foo.domain.ltd" initial_site.name = "foo" initial_site.save() Site.objects.create(domain="bar.domain.ltd", name="bar") class β¦ -
Loop in template without context variables
Is possible to use a loop using just numbers and not context variables in the template something like: {% for (int i = 22; i < 65; ++i) %} <input id="name_{{i}}" type="number" value="{{i}}"> {% endfor %} If is possible to do how can I do it? thanks in advance. -
Django I'm trying to get the latest added/edited element to the top of the page. It works with editing but not when I add new element
I am getting highest integer value of model integer field and then adding +1 to it and saving it as a form. When I am adding new element I use ModelForms like that: view.py class IndexView(TemplateView): template_name = 'titracker/index.html' def get(self, request): form = addTicketForm() return render(request, self.template_name, {'form':form, 'tickets_to_load':Ticket.objects.all().order_by('-ticket_position')}) def post(self, request): form = addTicketForm(request.POST) if form.is_valid(): from django.db.models import Max result = Ticket.objects.all().aggregate(Max('ticket_position')) my_list = [] for key,value in result.items(): my_list.append(value) max_pos = my_list[0] form.ticket_position = max_pos + 1 form.save() form = addTicketForm() return HttpResponseRedirect(reverse('titracker:index')) else: return render(request, self.template_name, {'form':form, 'tickets_to_load':Ticket.objects.order_by('-ticket_position')}) And it doesn't work, but when I don't use ModelForms it does work html template <div class='container'> <form class="form-horizontal" role="form" method="post" enctype="multipart/form-data"> {% csrf_token %} <input class="u-full-width" type="text" name="t_title" value="{{ticket.ticket_title}}"/> <textarea class="form-control" rows="3" name='t_body'> {{ticket.ticket_body}}</textarea> <button type="submit" value='post' class="btn btn-info">Submit</button> <button type="submit" value='post' name='delete' class="btn btn-info">Delete</button> <select id='status' value='post' name='status'> {% if ticket.ticket_status == 0 %} <option>Open</option> <option value='1'>In progress</option> <option value='2'>Closed</option> </select> {% elif ticket.ticket_status == 1 %} <option>In progress</option> <option value='0'>Open</option> <option value='2'>Closed</option> </select> {% elif ticket.ticket_status == 2 %} <option>Closed</option> <option value='0'>Open</option> <option value='1'>In progress</option> </select> {% endif %} </form></div> </div></center> </body> </html> view def editer(request, ticket_id): tick = get_object_or_404(Ticket, pk=ticket_id) if request.method == β¦ -
Celery - raise socket.error(last_err) OSError: [Errno 61] Connection refused
This is my project structure myproj β βββ app1 βββ __init__.py βββ tasks.py gettingstarted βββ __init__.py βββ urls.py βββ settings.py β βββ manage.py |-- Procfile In gettingstarted/settings: BROKER_URL = 'redis://' In Procfile: web: gunicorn gettingstarted.wsgi --log-file - worker: celery worker --app=hello.tasks.app In hello/tasks.py from __future__ import absolute_import, unicode_literals import random import celery import os app = celery.Celery('hello') @app.task def add(x, y): return x + y Please help....I've been trying to solve this for 24 hours straight now..... -
How to filter by an aggregation of the last N records of a related model
My goal is to develop a query using the Django ORM that will return all users in the system for which less than half of their last 50 posts have been liked. I've developed a query which gives me all of the users which have less than half of ALL of their posts liked, but I can't figure out how to limit the scope of the posts I'm looking to only the last 50 posts by that user. I'd prefer to keep the operation in a single query for performance reasons if at all possible. Dumbed Down versions of my models class User(models.Model): pass class Post(models.Model): author = models.ForeignKey( "user.User", related_name="posts", on_delete=models.CASCADE ) My Existing Query unpopular_users = User.objects.annotate( posts_created=Cast( Count('posts'), output_field=FloatField() ), posts_liked=Cast( Count(Case(When(posts__likes__gt=0, then=1))), output_field=FloatField() ) ).exclude(posts_created=0).annotate( liked_rate=F("posts_liked") / F("posts_created") ).filter(liked_rate__lt=Decimal('0.5')) -
Can not delete superuser in django and a resulting error django.db.utils.OperationalError: no such column: infrastructure_profile.slug
I wanted to add a slug field to my model Profile after I had several profiles created, then an error appeared when reaching the profile page with the slug in the url saying : Django OperationalError: no such column: infrastructure_profile.slug so I looked here and saw this answer and it suggested I delete all my migrations files to restart the database , so I did and then I got the same error , so I thought I should delete all the users I already have that didn't had the slug field already including the superuser. so I followed this answer and I got that error django.db.utils.OperationalError: no such column: infrastructure_profile.slug any idea what's going on ? -
Storing a Name for Your Project and Calling It in a Template
I've recently started a new Django project and was wondering where to store data like the name of my project/website/brand. If my Django project was called "foo_bar" e.g., I wanna be able to save something like "FooBar" as my brand name somewhere and then use it in templates for titles etc. What is the best practise for achieving that? -
Having trouble increasing item quantity when multiple of the same item are added to cart
The image attachment: when i try to increase the quantity of the second item, the quantity of the first item increases to 2, instead of the quantity of the second item. You can watch the video i uploaded here for better understanding: https:// web.facebook.com/groups/1378481325739503/permalink/2373521109568848/ See views and template here: https://codeshare.io/GLp0Rg VIEWS @login_required def add_to_cart(request,slug): item = get_object_or_404(Item, slug=slug) item_var = [] #item variation if request.method == 'POST': for items in request.POST: key = items val = request.POST[key] print(key,val) try: v = Variation.objects.get( item=item, category__iexact=key, title__iexact=val ) item_var.append(v) except: pass order_item_qs = OrderItem.objects.filter( item=item, user=request.user, ordered=False ) if len(item_var) > 0: for items in item_var: order_item_qs = order_item_qs.filter( variation__exact=items, ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user=request.user, ordered=False ) order_item.variation.add(*item_var) order_item.save() order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if not order.items.filter(item__id=order_item.id).exists(): order.items.add(order_item) messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to cart.") return redirect("core:order-summary") TEMPLATE ORDER SUMMARY <td data-th="Quantity"> <div class="quantity buttons_added"> <a href="{% url 'core:remove-single-item-from-cart' order_item.item.slug %}"><input type="button" value="-" class="minus"></a> <input type="number" value="{{ order_item.quantity }}" class="input-text qty β¦ -
Posting foreign key IDs in Django Rest Framework
I'm working on a Django API using Django Rest Framework. I have two related entities, Event and Venue. An Event takes place in a Venue. By using nested serialization I'm able to return the following to my API users: { "id": "1234", "name": "My event", "venue": { "id": "5678", "name": "My venue" } } This is all as expected. However, I'm now trying to POST an event and reference the venue as a parameter: POST /api/events/ { "name": "My new event", "venue_id": "5678" } But I'm struggling to make this work. I'm trying both venue_id and venue as attribute names (I'd prefer _id as it would be more correct, but it wouldn't be a big deal). I'm using the following serializers: class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = ['id', 'name', 'created_at', 'updated_at'] class EventSerializer(serializers.ModelSerializer): venue = VenueSerializer() class Meta: model = Event fields = ['id', 'name', 'venue', 'created_at', 'updated_at'] What would be the correct approach to achieve this? -
django ajax json response
I come from PHP frameworks, but I want to format my response as if the username is invalid "login_message": "error_message" and send it to the page as msg, so I can use it later for ajax stuff , but it seems nothing to work as I want to class Login(LoginView): authentication_form = CustomAuthenticationForm form_class = CustomAuthenticationForm template_name = 'login.html' def form_valid(self, form): if form.is_valid(): user = authenticate( self.request, username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password') ) if user is not None: if user.is_active: login(self.request, form.get_user()) else: return render(self.request, 'profile.html',{'login_message' : 'The user has been removed',}) else: return render(self.request, 'profile.html',{'login_message' : 'The user has been removed',}) return HttpResponseRedirect(self.get_success_url()) #login(self.request, form.get_user()) #return HttpResponseRedirect(self.get_success_url()) forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Email','required': True,'autofocus' : True})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password','required': True})) login <form method="post"> {% csrf_token %} <h2 class="sr-only">Login Form</h2> <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div> <div class="form-group">{{ form.username }}</div> <div class="form-group">{{ form.password }}</div> {{ login_message }} <div class="form-group"><button class="btn btn-primary btn-block" type="submit">Log In</button></div><a href="#" class="forgot">Forgot your email or password?</a></form> -
Running collectstatic from Heroku runs successfully, but fails to push the files to AWS, run locally it's successful
I'm trying to run a basic django app from Heroku using S3 to serve both static and media files. When I run the server locally with python3 manage.py collectstatic the static files are collected and placed into a newly created /static/ folder in my S3 bucket. When I run heroku run python3 manage.py collectstatic I am told that the static files have been collected and copied to /app/staticfiles (on build with collectstatic not disabled it's collected and copied to /tmp/build_[id]/staticfiles). Nothing is added to my S3 bucket; looking at the app filestructure on Heroku there is no folder /app/staticfiles; the app has no folder called /staticfiles; and I only have one S3 bucket, so I'm not accidentally pushing to the wrong bucket. Finally, I've quadruple checked that the dev and prod environment settings match (where appropriate). My hunch is that django.contrib.staticfiles has a very strong opinion about where the static files should end up and is overriding my settings for aws (aws_settings.py) once in production. Any pointers about how to resolve this, gratefully received! settings.py import os import dj_database_url import dotenv import django_heroku BASE_DIR = os.path.dirname( os.path.dirname( os.path.abspath(__file__))) dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): #DEV_ENV dotenv.load_dotenv(dotenv_file) os.environ['ENVIRONMENT']='DEV' from .envsettings.dev_settings import β¦ -
upload_to based off foreign key value
I have an Image model. I want it to upload to a folder depending on which category the user chooses. For example if the user chooses the "apples" category I'd like it to upload to a media folder called "apples". class Image(models.Model): image = models.ImageField(upload_to=category) category = models.ForeignKey(Category, on_delete=models.CASCADE) -
Django REST Framework - How to apply permission_classes to APIRootView (browsable API)
according https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy on a regular APIView you set permissions via attribute permission_classes: from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): permission_classes = [IsAdminUser] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) I would like to limit access to the APIRoot view (the browsable API) to only admin users. I tried via from rest_framework.permissions import IsAdminUser from rest_framework.views import APIView class APIRootView(APIView): permission_classes = [IsAdminUser] with no success :| some suggestions to get this to work? -
Recursively going through a model
I have a model like so: class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(blank=True) def lastfolder(self): try: return self.folder_set.all().order_by('-created_at')[0] except IndexError: return None def lastdrive(self): try: return self.drive_set.all().order_by('-created_at')[0] except IndexError: return None def lastfile(self): try: return self.drive_set.all().order_by('-created_at')[0] except IndexError: return None def save(self, *args, **kwargs): self.slug = slugify(self.user.username) return super().save(*args, **kwargs) def get_absolute_url(self): kwargs = {'slug' : self.slug} return reverse('', kwargs=kwargs) def __str__(self): return self.user.username class Drive(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=64) cover_picture = models.ImageField(upload_to=f'media/{user_path}', default="media/drive.png") created_at = models.DateTimeField() slug = models.SlugField(blank=True) def get_absolute_url(self): kwargs = {'slug' : self.slug} return reverse('', kwargs=kwargs) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) class Meta: unique_together = [['owner', 'name']] ordering = ('name',) class Folder(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) drive = models.ForeignKey('Drive', on_delete=models.CASCADE) name = models.CharField(max_length=64) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) cover_picture = models.ImageField(upload_to=f'media/{user_path}', default="media/folder-white.png") created_at = models.DateTimeField() path = models.CharField(max_length=2048, blank=True) slug = models.SlugField(blank=True) def __str__(self): return self.name def get_absolute_url(self): kwargs = {'slug' : self.slug} return reverse('', kwargs=kwargs) def get_path(self): yield self.name try: yield from get_path(self.parent) except: pass def complete_get_path(self): text = [] for i in self.get_path(): text.append(i) text.reverse() return "/".join(text) def save(self, *args, **kwargs): self.slug = slugify(self.name) self.path = self.complete_get_path() return super().save(*args, β¦ -
Django: 404 Error Appears While Trying to Use Slug in URLs
I am a beginner in Django. Right now, I am learning the framework by building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. Right now, I am trying to use slug in URLs. I have successfully used slug in two of my templates, which are index.html and phonemodel.html. However, I am facing issues with the third template, which is details.html. When I go to http://127.0.0.1:8000/index, I see this page: When I click on Samsung, I see this page: Up to this is fine. But when I click on any phone model, like Galaxy S10, I get 404 error. It looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/details/galaxy-s10 Raised by: PhoneReview.views.ReviewView No review found matching the query You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 β¦ -
How I can resolve this guys? Python.exe no such or fille directory
I use python 3.8 on Windows 10 I would like to beginning a djangoprojects. Manege.py can't run; no such or fille directory. Please how can resolve this.