Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple model instance django rest-framework
I was trying to find a way to create multiple objects with one API request in a django-rest based API. I found many answers to that and I came up with overriding ViewSet.get_serializer method as follows def get_serializer(self, *args, **kwargs): data = kwargs.get('data', None) if data: kwargs['many'] = isinstance(data, list) return super().get_serializer(*args, **kwargs) I also overrided serializer.to_representation in order to add some useful data to representation. Problem is that doing that when I create a single object per request everything's fine, but when I try to create multiple objects I get errors in serializer.to_representation method. I tried to debug the error and seems that when serializer is initialized with many=True instance passed to serializer.to_representation is a OrderedDict rather than the actual instance, so I cannot access properties of the instance like related fields, etc. def to_representation(self, instance): if self.context['request'].method == 'POST': print(type(representation), type(instance)) return super().to_representation(instance) This will output <class 'collections.OrderedDict'> <class 'main.models.Expenditure'> as expected for single object post request but for multiple object (which still are correctly created) requests output is more complex. <class 'collections.OrderedDict'> <class 'main.models.Expenditure'> <class 'collections.OrderedDict'> <class 'main.models.Expenditure'> <class 'collections.OrderedDict'> <class 'collections.OrderedDict'> <class 'collections.OrderedDict'> <class 'collections.OrderedDict'> in this example I tried to create two objects. The second … -
Django async view - how do I know its running async?
I can create an async view and inquire as to whether the method thinks it's a coroutine, and it is. However, looking at the stack it looks like my view is being called by asgiref's SyncToAsync. I am using Gunicorn with Uvicorn worker and an asgi.py script that starts with: from channels.routing import get_default_application channel_layer = get_default_application Plus, I am trying to discover if any of my middleware is running sync or even with a (forced) sync middleware I am not hitting (logger.debug('Synchronous %s adapted.', name)) Makes no sense. -
my django site is not opening under jammu and kashmir area in airtel network , it is on digital ocean
my site is not opening under Jammu and Kashmir area in India in Airtel network.In other network its opening.In Airtel every other site is opening , only my site not opening . -
Can't start project file Django using django-admin startproject mysite
so I am learning how to work with Django and for some reason I always get this error: I installed Django with py -m pip install Django==2.0.4 and then I updated it with command. It always create empty folder without any file inside of it. I have no idea why is this happening. Any help would be blessing. -
Difference between hosting Postgresql database on Railway or on AWS/Azure
I'm working on a django application I need to put online. For now I've only been working on personal projects that I never deployed. Searching for the best solutions, I found that Railway seems to be the easiest choice, and that I can even host the app and the database on it (and even the static files!). I don't know so much about databases, that's why I wonder if there are differences between hosting everything (the code + the database) on Railway or hosting the code on Railway, and connect it to a database hosted on AWS, Azure etc... It seems "too easy" for me to be possible to do that. Maybe the databases on Railway are great only for small usages ? I didn't find anything on the internet comparing those services and talking about the possible limits of Railway. Thanks a lot in advance for your help. -
Forbidden (CSRF cookie not set.): /auth for obtaining_auth_token
I am trying to get an auth token for the client (OrderClient.py). This keeps failing with Forbidden (CSRF cookie not set.): /auth. Here is my views from rest_framework.decorators import api_view,permission_classes,authentication_classes from rest_framework.response import Response from .serializers import OrderSerial from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated @api_view(['POST']) @authentication_classes([SessionAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def make_order(request,*args,**kwargs): user1=request.user serializer = OrderSerial(user=user1) print(serializer.is_valid()) data={'abc':'cde'} return Response(data=data) Here is my urls.py from django.urls import path from Products.views import home_view,Phone_input_view,Phone_list_view,Phone_edit_view from Products.api.views import make_order from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('',home_view), path('auth/', obtain_auth_token), path('createPhone/',Phone_input_view), path('viewPhoneList/',Phone_list_view), path('edit/<int:id>',Phone_edit_view), path('order/', make_order) ] I have added the 'rest_framework.authtoken' to installed apps in settings. I was expecting to retrieve the token and successfully sign in -
Django function view rewriting to Class View UpdateView problem with Multiple Forms
Im trying to rewrite my whole app from function views to class views. Right now Im struggle with UpdateView I know that it can only accept one parameter of FORM. But I wonder after rewriting the code from topics (like mine) how to do it correctly and make it works. And Does it make sense to interfere with the intentions of the Django Developers? Or just leave this view as a view function? This how its looks right now views.py @login_required def edit_user_info(request): user = get_object_or_404(User, id=request.user.id) user_profile = get_object_or_404(UserProfile, profile=request.user) if request.method == "POST": user_form = UserForm(request.POST, instance=user) profile_form = UserProfileForm(request.POST, instance=user_profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, "Your profile is updated successfully") return redirect(to="profile") else: user_form = UserForm(instance=user) profile_form = UserProfileForm(instance=user_profile) context = { "user_form": user_form, "profile_form": profile_form, } return render(request, "web/update_user_info.html", context) forms.py class UserForm(forms.ModelForm): email = forms.EmailField(required=False,label="Updated email address if different", widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ("email",) class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ("about_user","user_photo",) and what I would like to make with UpdateView or other class View MultiModelFormView, TemplateView Also, I would like to leave the auto filled with forms, with user data class EditUserView(MultiModelFormView): form_classes = { … -
How can i upload videos using django rest api with cloudinary
Well im doing a project in django rest for backend and react as front end, i want to do 2 post modals one for video and another for images, the image is fine but the video dont work, when i set filefield i get an error saying is not a valid image file, also tried to do with cloudinary where all my images are stored, i cant figure it out how to do it, tried countless times but with no avail the video post model ` class VideoPost(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.TextField(max_length=100, blank=True) content = models.TextField(blank=True) video = models.FileField(upload_to='images/', blank=True) post_categorys_filter = models.CharField( max_length=50, choices=post_categorys, default='normal' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] def __str__(self): return f'{self.id} {self.title}' the serializer class VideoPostSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') is_author = serializers.SerializerMethodField() profile_id = serializers.ReadOnlyField(source='author.profile.id') profile_image = serializers.ReadOnlyField( source='author.profile.image.url') comments_count = serializers.ReadOnlyField() likes_count = serializers.ReadOnlyField() dislikes_count = serializers.ReadOnlyField() video = serializers.FileField() def get_is_author(self, obj): request = self.context['request'] return request.user == obj.author class Meta: model = VideoPost fields = [ 'id', 'author', 'is_author', 'profile_id', 'profile_image', 'content', 'created_at', 'updated_at', 'post_categorys_filter', 'video', 'likes_count', 'comments_count', 'dislikes_count' ] ` -
Trying to find a good example to create a html button in django to run a python function and display result
I've trying for a while now to learn django mostly for my own curiosity. My current goal is to have an button on screen that when pressed does some simple python function at first. Something like display a string value or a random number on the screen. I've found some examples but they're not helping my understanding of the problem. Most examples have been building like buttons or similar. I've tried looking into ajax calls for python but I can't seem to find writeups that help me with the basics and any video tutorials I find on this topic there is a language barrier which is not helping me learn. Sorry for asking probably a basic question. -
Why data not loading from db?
There are model: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) boss = models.ForeignKey('self', null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return f'<{self.pk}> {self.name} - {self.position}' There are view: class EmployeeView(ListView): model = Employee context_object_name = 'employees' template_name = 'employees-list.html' def get_queryset(self): return Employee.objects.all() I have 5 people in my db, but then i try to load my url from pattern: path('', EmployeeView.as_view()), I got this in my console: "GET /employees/ HTTP/1.1" 200 55 And <> - on web page, why data not loading? -
i want use the value of incremated 'i' from second file
this is first file that contains value of i class Qury: i=0 def makedb(self): self.making_key() def making_key(self): global i for t in range(12): self.i+=1 def making_key2(self): global i for t in range(14): self.i+=1 print(self.i) first file that making object from django.core.management.base import BaseCommand from Qurys import Qury Q=Qury() print(Q.i) class Command(BaseCommand): global Q def handle(self,*args,**kwargs): Q.makedb() print(Q.i) second file the real problem is here from django.core.management.base import BaseCommand from home.management.commands.make_db import Q class Command(BaseCommand): def handle(self,*args, **kwargs): Q.making_key2() this is django project i want to user the increment value of i to add in user in database (cassandra) i want make a command that can add user but start from increment value of i -
How to turn ROM objects into hashes when using a raw query with a join, and get only a subset of DB fields?
I have a query with the following format: query_str = """ SELECT A.id, A.location::bytea, A.author_id, B.username FROM A JOIN B ON A.author_id = B.id """ for p in Database.objects.raw(query_str): # how to get the hashes here? How can I get hashes here that only contain the field that are SELECTed in the raw query? I tried model_to_dict but that returns all fields and only fields from table A. -
Contact() got an unexpected keyword argument 'listing'
`from django.shortcuts import render, redirect from .models import Contact from django.contrib import messages Create your views here. def Contact(request): if request.method == 'POST': listing_id = request.POST['listing_id'] listing = request.POST['listing'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] user_id = request.POST['user_id'] realtor_email = request.POST['realtor_email'] contact.save() messages.success( request, 'Your request has been submitted, a realtor will get back to you soon') rn redirect('listings'+listing_id) ` i'm trying to save the data from database. but give the error TypeError. -
How To Update Value From Views ? and How to Parse Id to get_success_url for DetailView ? In Django
How To Update Value From Views ? And Parse Id to DetailView ? Problem Update Value I Try to write query.attendance and query.status, to get data from database. but the error said "'QuerySet' object has no attribute 'attendance' / 'status'" Problem Parse Id I dont now how to parse this id to get_success_url 1. home/views.py class HomeView(FormView): template_name = 'home/index.html' form_class = TicketForm def form_valid(self, form): getId = form.cleaned_data['nomor_ticket'] query = Graduates.objects.filter(ticket_id=getId) if query: **#FIRST ERROR (attendance and status has no attribute)** print(query.attendance == timezone.now()) print(query.status == True) **#FIRST END ERROR** print('ticket available') else: print('no ticket not found ') print(query) return super().form_valid(form) def get_success_url(self): return reverse('attendance:index' + how to get id ?) 2. attendance/models.py class StudyProgram(models.Model): study_program_id = models.IntegerField() name = models.CharField(max_length=100) def __str__(self): return self.name class Graduates(models.Model): ticket_id = models.CharField(primary_key=True, max_length=16, unique=True, default=custom_id) graduate_number = models.IntegerField() student_id = models.IntegerField() full_name = models.CharField(max_length=100) study_program = models.ForeignKey(StudyProgram, on_delete=models.CASCADE) attendance = models.DateTimeField(blank=True, null=True, editable=False) status = models.BooleanField(default=False) 3. attendance/views.py class Attendance(DetailView): model = Graduates template_name = "attendance/index.html" 4. attendance/urls.py from django.urls import path from . import views app_name = 'attendance' urlpatterns = [ path('<pk>/', views.Attendance.as_view(), name='index'), ] -
Django REST Framework pagination changing model ordering
For some reason when I run paginate_queryset(queryset) the ordering changes, and is not the order I want. I have the model: class MyModel(models.Model): name = models.CharField(max_length=100) history_date = models.DateTimeField() class Meta: managed = False db_table = 'myapp_historicalmymodel' ordering = ("-history_date",) With the ordering field set. Then I have an extra action in a ViewSet: class MyModelViewSet(viewsets.ModelViewSet): serializer_class = MyModelSerializer permission_classes = [permissions.IsAuthenticated] queryset = MyModel.objects.all() @action(detail=False, methods=['get'], url_path='history', url_name='history') def history(self, request): items = HistoricalMyModel.objects.all() print(items) # FIRST PRINT page = self.paginate_queryset(items) print(page) # SECOND PRINT if page is not None: serializer = HistoricalMyModelSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) serializer = HistoricalMyModelSerializer(items, many=True) return Response(serializer.data) The first print prints out items in the configured order, using ordering = ("-history_date",), like: <QuerySet [<HistoricalMyModel: HistoricalMyModel object (4)>, <HistoricalMyModel: HistoricalMyModel object (3)>, <HistoricalMyModel: HistoricalMyModel object (2)>, <HistoricalMyModel: HistoricalMyModel object (1)>]> There you can see the order 4,3,2,1. But the second print prints items out in some default Postgres order it seems: [<HistoricalMyModel: HistoricalMyModel object (3)>, <HistoricalMyModel: HistoricalMyModel object (4)>, <HistoricalMyModel: HistoricalMyModel object (1)>, <HistoricalMyModel: HistoricalMyModel object (2)>] There you can see the order 3,4,1,2. Why is it changing the order of items after running self.paginate_queryset(items)? -
"32 - Could not authenticate you." error in tweepy
I was working with tweepy with Django and the code was working fine. But, when I deployed the code on railway (similar to Heroku), the app showed these logs: File "/app/tweet_scrapper/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/venv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/venv/lib/python3.9/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/app/tweets/apps.py", line 10, in ready from . import jobs File "/app/tweets/jobs.py", line 85, in <module> scrap() File "/app/tweets/jobs.py", line 69, in scrap searched_tweets = api.search_tweets( File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 33, in wrapper return method(*args, **kwargs) File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 46, in wrapper return method(*args, **kwargs) File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 1309, in search_tweets return self.request( File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 263, in request raise Unauthorized(resp) tweepy.errors.Unauthorized: 401 Unauthorized 32 - Could not authenticate you. Traceback (most recent call last): File "/opt/venv/lib/python3.9/site-packages/gunicorn/arbiter.py", line 502, in spawn_worker worker.init_process() File "/opt/venv/lib/python3.9/site-packages/gunicorn/workers/base.py", line 114, in init_process self.wsgi = self.app.wsgi() File "/opt/venv/lib/python3.9/site-packages/gunicorn/app/base.py", line 66, in wsgi self.callable = self.load() File "/opt/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/opt/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/opt/venv/lib/python3.9/site-packages/gunicorn/util.py", line 356, in import_app __import__(module) File "/app/tweet_scrapper/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/venv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/venv/lib/python3.9/site-packages/django/__init__.py", line … -
Axios giving 401 (Unauthorized). I am trying to get userdata through react frontend passed to DRF Social Oauth2. Same working on POSTMAN
Below are the two files LoginScreen.JS which has a submit handler that submits the input. Here we import the axios instance from login.JS. I have also attached the same working example from PostMan. login.js const baseURL='http://127.0.0.1:8000/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { 'Content-Type': 'application/json', accept: 'application/json' }, }); export default axiosInstance LoginScreen.js const submitHandler = (e) => { e.preventDefault() axiosInstance .post(`auth/token/`,{ username: email, password: password, grant_type: 'password', client_id: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz', client_secret: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz' }) .then((res) => { localStorage.setItem('access_token', res.data.access); localStorage.setItem('refresh_token', res.data.refresh); }); }; -
How to Create personal jwt token for user login through googl or facebook into app using django allauth
Hi I have created an app where I want to use social login through Django all auth package I can log in successfully to my app but how i can create a personal jwt token for the user who loggin through google Account -
Django Imagekit I/O operation on closed file
I'm using Imagekit to resize pictures on a website i'm developing with Django, I've used Imagekit before without any issues but I have a strange problem. I am using S3 for Media/Static files. When I upload an image in admin and refresh the template serving the images i get ValueError at / I/O operation on closed file error page. Then if I refresh the page it loads fine without a problem. I am using an ImageSpec field to resize images and using {{ image.thumbnail.url }} in my template. I am very much a beginner with Django so looking for some direction. Why will it work on a page reload and not when initially uploaded? Here are the relevant fields in my model. class Media(models.Model): image = models.ImageField(upload_to="media") thumbnail = ImageSpecField([Adjust(sharpness=1.1), ResizeToFill(800, 650)], source='image', format='JPEG', options={'quality': 100}) -
Cors problem in dockerized angular and django project
I have a problem that solves all day. I'm learning in a range of web development. Currently I'm learning docker. I dockerized my project in Angular using the nginx server. Same as my Django API where my Angular application connects to it. However, when angular uses the GET method the course error in the JS console. JS console Access to XMLHttpRequest at 'http://127.0.0.1:8000/api2/zdjecia/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Django console Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 31, 2022 - 14:12:10 Django version 3.2.16, using settings 'lobialogard.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [31/Oct/2022 14:14:14] "OPTIONS /api/aktualnosci/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:14] "OPTIONS /api3/archiwum/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:15] "OPTIONS /api/aktualnosci/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:15] "OPTIONS /ustawienia/strony/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:18] "OPTIONS /ustawienia/strony/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:18] "OPTIONS /api/aktualnosci/ HTTP/1.1" 200 0 I unlocked all the methods and origins as below: My nginx.conf file server { listen 80; server_name localhost; location / { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; … -
URLValidator throws ValidationError exception in case of a correct url
I am validating a long url in my views.py original_url = request.POST.get('original_url') validator = URLValidator() try: validator(original_url) except ValidationError: return HttpResponse("Invalid URL") But even if the URL is syntactically correct, I see the ValidationError exception being executed. After placing print() statements in try block I also noticed that the code never gets into the try block but straightaway executes the exception. I have a finished code that is using this same approach but don't see any errors there. I am wondering what am I missing? -
How to create an instance from the parent model in Django
sorry if my question looks petty, I have a problem in making an instance from the below parent model below , I wanted to get doctor's name into the patient's table but in turn this error: Cannot assign "'Ann Lindsey'": "Patientinfo.Referred_doctor" must be a "Doctor" instance (is there a way I can make field (Referred_doctor) an instance of DOCTOR model?) any help please. here is my code; models.py class Doctor(models.Model): Profile_picture = models.ImageField(null=True, default='avatar.png', upload_to='images/') First_Name = models.CharField(max_length=200) Last_Name = models.CharField(max_length=100) Doctor_Bio = models.TextField(null=True) Admission_Date = models.DateTimeField(auto_now=True) Date_of_Birth = models.DateField() Doctor_Category = models.CharField(max_length=200) def __str__(self): names = (self.First_Name, self.Last_Name) stringified = ' '.join(names) return stringified class Patientinfo(models.Model): Name = models.CharField(max_length=255) Gender = models.CharField(max_length=200) Marital_Status = models.CharField(max_length=100) Telephone = models.CharField(max_length=30) Admission_date = models.DateTimeField(auto_now=True) Patient_Status = models.CharField(max_length=200) Symptoms = models.TextField() Referred_deparment = models.CharField(max_length=200) Referred_doctor = models.ForeignKey(Doctor, on_delete=CASCADE) def __str__(self): return self.First_Name views.py def padmform(request): patientdata = Patientinfo.objects.all() doctors = Doctor.objects.all() if request.method == 'POST': Name = request.POST.get('Name') Gender = Request.POST.get('Gender') Marital_Status = Request.POST.get('Marital_Status') Telephone = Request.POST.get= Request.POST.get('Telephone') Patient_Status = Request.POST.get('Patient_Status') Symptoms = Request.POST.get('Symptoms') Referred_deparment = Request.POST.get('Referred_deparment') Referred_doctor = Request.POST.get('Referred_doctor') patientdata = Patientinfo(Name=Name, Gender=Gender, Marital_Status=Marital_Status, Telephone=Telephone, Patient_Status=Patient_Status, Symptoms=Symptoms, Referred_deparment=Referred_deparment, Referred_doctor=Referred_doctor) patientdata.save() messages.success(request, 'New patient successfully admitted') return redirect('Patients') context = {'patientinfo':patientdata, 'doctors':doctors} return … -
How to access to Django ORM DB in pytest?
I am writing a smoke test for a POST request to API Django using pytest. With a Post request, I write the value to the DB and check that it appears. The data from POST request appears in the database, but the test fails due to the error below. import requests from datetime import datetime from json_import.models import Sensor import pytest BASE_URL = "http://localhost:8000" POST_URL = "/api/write_values" @pytest.mark.django_db class TestAPI: def test_smoke(self): body = { "timestamp": f"{datetime.now()}", "sensor_values": [ { "sensor_id": "sensor1", "value": "1.1" } ] } response = requests.post(f'{BASE_URL}{POST_URL}', json=body) sensor1 = Sensor.objects.get(sensor_id='sensor1') sensor_value1 = sensor1.sensor_values.last() assert sensor_value1.sensor_value == 1.1 Received error E json_import.models.Sensor.DoesNotExist: Sensor matching query does not exist. /usr/local/lib/python3.9/site-packages/django/db/models/query.py:435: DoesNotExist Migrations are done, py test.ini is created. What could be the problem? I was looking for a solution to the problem in the documentation and on the forum. -
Django Python - Can`t install fixtures in test database
HiEveryone Got some problem why trying to load fixtures in Django test database. I made fixture of DB by exec command python manage.py dumpdata misxapp --format=yaml --indent=4 > misxapp/fixtures/misxapp.yaml In misxapp.tests.py I use StaticLiveServerTestCase class property "fixtures" fixtures = ['misxapp'] Then I run test python manage.py test misxapp.tests.TestAuthorization.test_login and get exception psycopg2.errors.UndefinedColumn: ERROR: column "date" in table "misxapp_insurancepolicy" doesn't exist. LINE 1: ..., "organization_id_id" = 34, "person_id_id" = 23, "date" = '... !!! BUT !!! column "date" exists both in models.py file and Postgresql database I assume that the problem is in the naming of the date field in Postgresql, but not sure at all. please tell me in which direction to dig, thanks!!! -
Website creates a new non-existent webpage after I visit website/class_id
My website creates a new non-existent website, after I visit my website/näytä_luokka/# (also, class_id). If I try to go to a page that is in the same urls.py file, I get an error because it tries to find a page website/näytä_luokka/luokat instead of going to website/luokat. This happens through navbar. If I try to go to a link that is in another urls.py, everything works fine. Switching from /luokat to other pages works also fine. I am using django to create website. So, here's a couple examples from my urls.py from django.urls import path from . import views urlpatterns = [ path('näytä_luokka/<luokka_id>', views.näytä_luokka, name="näytä-luokka"), path('luokat', views.kaikki_luokat, name="luokat"),' ] and .views def näytä_luokka(request, luokka_id): luokkalistaus = luokka.objects.get(pk=luokka_id) return render(request, 'tietokanta/näytä_luokat.html', {'luokkalistaus': luokkalistaus}) def kaikki_luokat(request): luokkalista = luokka.objects.all().order_by('nimi') return render(request, 'tietokanta/luokat.html', {'luokkalista': luokkalista}) ** the navbar.** </li> <li class="nav-item"> <a class="nav-link" href="luokat">Luokat</a> </li> I tried adding / after id number, but id didn't do anything. Thank you if you can help me figure this out.