Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why my pc not able to install pip packages and also shows no command found when run pip commands?
I tried everything thing but no command found comes everytime, uninstall ..reinstall I have the 3.10.1 version in system also, my script folder shows empty please help me as my Django work hinders due to this -
Django Channels does not work inside a DjangoQ jobs or hooks handler
I am trying to trigger a websocket message when a DjangoQ job ends, but it doesn't work. The same code works inside a views.py APIView that queues the job, but does not work inside my jobs.py handler. It does not generate error. It does nothing. views.py # works (calls consumer handler, websocket event emitted and logged on browser console) from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def event_trigger(): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'event_sync', { 'type': 'send_message_to_frontend', 'message': "event_trigered_from_views" } ) Same code called from hooks.py does not work. Does nothing. hooks.py from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def event_trigger(): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'event_sync', { 'type': 'send_message_to_frontend', 'message': "event_trigered_from_hooks" } ) def import_wallet_completed(task): ic(task.result) event_trigger() Invite.objects.update_or_create( emoji_key=task.result['emoji_key'], defaults={ 'job_status': 'wallet_imported' } ) What could be going on? -
Can I insert data from phpmyadmin even after launching the website to the internet?
I am using Django framework, MySQL through xampp and inserting data from phpmyadmin. Can I keep on inserting data from phpmyadmin even after launching the website to the internet or is it necessary to register my models in admin.py and then create a superuser to insert data to a already hosted website? -
Django + Docker: connection to server at "localhost" (127.0.0.1), port 5432 failed
I am trying to run my Django app (Nginx, Gunicorn) in docker. But for request http://167.99.137.32/admin/ I have error: (full log https://pastebin.com/0f8CqCQM) onnection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Address not available Is the server running on that host and accepting TCP/IP connections? I was trying answers from Can't run the server on Django (connection refused) but didn't solve my problem settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lk_potok_2', 'USER': 'postgres', 'PASSWORD': 'post222', 'HOST': 'localhost', 'PORT': 5432, }, docker-compose.yml version: '3.9' services: django: build: . # path to Dockerfile command: sh -c "gunicorn --bind 0.0.0.0:8000 potok.wsgi:application" volumes: - .:/project - static:/project/static expose: - 8000 environment: - DATABASE_URL=postgres://postgres:post222@localhost:5432/lk_potok_2" - DEBUG=1 db: image: postgres:13-alpine volumes: - pg_data:/var/lib/postgresql/data/ expose: - 5432 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=post222 - POSTGRES_DB=lk_potok_2 nginx: image: nginx:1.19.8-alpine depends_on: - django ports: - "80:80" volumes: - static:/var/www/html/static - ./nginx-conf.d/:/etc/nginx/conf.d volumes: pg_data: static: nginx-conf.nginx upstream app { server django:8000; } server { listen 80; server_name 167.99.137.32; location / { proxy_pass http://django:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /var/www/html/static/; … -
How do I get the actual image instead of getting url when editing the Modelforms in django template?
html <div> {{variant_images_form.display_image|as_crispy_field}} </div> views.py def item_approval(request, pk): if request.method == "GET": product_form = AdminProductForm(request.POST) item = ProductVariants.objects.get(item_num=pk) product_id = item.product_id product = Product.objects.get(product_id=product_id) product_variant_images = ProductVariantsImages.objects.filter(product_variant=item) product_form = AdminProductForm(instance=product) item_form = ProductVariantsForm(instance=item) variant_images_form = ProductVariantsImagesForm(instance=product_variant_images[0]) return render(request, 'loom_admin/product_details.html', {'item_form':item_form, 'product':product, 'item':item, 'product_form':product_form, 'variant_images_form':variant_images_form, }) How to render the model form with the actual image instead of showing the URL path. -
1054, "Unknown column 'work_waterlevel.id' in 'field list'" in django
I am trying to display my mysql data on a HTML page everything is working fine but when i try to display the data from mySQL tohtml page its showing 1054, "Unknown column 'work_waterlevel.id' in 'field list'") this error how to resolve this error my models.py is from django.db import models # Create your models here. class waterlevel(models.Model): time=models.DateTimeField() status=models.CharField(max_length=50) level=models.DecimalField(max_digits=12,decimal_places=6) -
How to mark Oscar Product as Available
I successfully added a product in Django Oscar, I successfully added price to the product but am unable to mark order as available to the public for sales. the product still remain unavailable. I have no clue on how to make the added product available for purchase even after product price is added. this documentations couldn't even help me. https://django-oscar.readthedocs.io/en/3.1/topics/prices_and_availability.html I couldn't find any help after reading this documentation above. the image is the current description of the current product. -
Ajax not returning data to server(Django) on some button clicks
Iam building a webpage that contains auto generated buttons using django,I am using ajax to update table values according to each button click.I have implemented ajax,When i try to print request.POST on server side ,it reutrns the value inconsistencly,sometimes it would,sometimes it wont. I have tried putting alert on success method and each time i click a button alert pops up even though it doesnt return an value. Here's the Code: <button name="date" type="submit" value={{d}} onclick="sendData(event)""> Ajax code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> function sendData(event){ event.preventDefault(); $.ajax({ type : "POST", url: "", data: { date : event.target.value, csrfmiddlewaretoken:'{{ csrf_token }}', }, success: function(data){ }, failure: function() { } }); } -
Cache function or view?
I want to use django-rest-framework with cache. @cache_page(10 * 60) @api_view(['GET']) def get_num(request): if request.method == "GET": res = ["ok"] return Response(res) It works well. So actually I want to cache not view but function @cache_page(10 * 60) def getCalc(num): return num * 10 @api_view(['GET']) def get_num(request): if request.method == "GET": res = getCalc(request.query_params.get('num')) return Response(res) There comes error TypeError: _wrapped_view() missing 1 required positional argument: 'request' Is it possible to use cache for function?? -
Failed to create a seller instance using django signals
I'm building a website with 2 user types and still new to django. And I want to add the functionality to add the seller of the product whenever a product is sold. I'm sorry that I couldn't explain it better. Here's the code of models.py: class Ordered(models.Model): products = models.ForeignKey(Products, on_delete = models.SET_NULL, null = True) seller = models.ForeignKey(SellerProfile, on_delete = models.SET_NULL, null = True) buyer = models.ForeignKey(CustomerProfile, on_delete = models.CASCADE) ordered_on = models.DateTimeField(auto_now_add = True) And this is the signal code: @receiver(post_save, sender = Ordered) def new_order_for_seller(sender, instance, created, *args, **kwargs): seller = Ordered.seller.sellerprofile if created: Ordered.objects.create(seller = seller) Any suggestion or correction of the code will be really helpful. Thank you -
In case of Django model,
In the django code in order to make a model, for example, class Student(models.Model): name = models.CharField(ax_length = 200) Why models.CharField(ax_length = 200). Why can't we write only name=CharField(ax_length = 200) -
How to fix error testing Authentication user?
I'm learning Drf, I'm figuring out to Athuenticate user login Testapi in Drf, it showing error Not valid view function or pattern name. Can Anyone suggest what is wrong with the code? URLS.PY urlpatterns = [ path('admin/', admin.site.urls), path('', include('college.urls')), path('auth',include('rest_framework.urls'), name='rest_framework'), ] TEST.PY USER_URL = reverse('auth') class StudentsDetailsTestCase(APITestCase): def test_login_user(self): self.assertTrue(self.client.login(username='***', password='***')) response = self.client.get(USER_URL) self.assertEqual(response.status_code,status.HTTP_200_OK) traceback error Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Users\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\Users\collegedjango\MYSITE\college\tests.py", line 35, in <module> USER_URL = reverse('auth') File "C:\Users\collegedjango\venv\lib\site-packages\rest_framework\reverse.py", line 47, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File "C:\Users\collegedjango\venv\lib\site-packages\rest_framework\reverse.py", line 60, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "C:\Users\collegedjango\venv\lib\site-packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\collegedjango\venv\lib\site-packages\django\urls\resolvers.py", line 729, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'auth' not found. 'auth' is not a valid view function or pattern name. ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) -
Embedded HTML code in Python string doesn't appear properly in Django
I'm facing a problem when I embed HTML code in my python's view.py Basically, my objective is to customize the color of certain words only (based on the input). I want to do it by modifying the view.py For example (my view.py): def home(request): form = request.POST.get('uncorrected') texts = str(form) + '<span style="color: red">test text but this section is red</span>' return render(request, 'corrector/home.html', {'text': texts}) Inside my index.html: <textarea type="text" id="textarea" name="uncorrected"> {{ text }} </textarea> However, when I type "my text" in the textarea it displays only: my text <span style="color: red">test text but this section is red</span> It doesn't make the text red, it directly displays the code. How can I make it work? -
Why does Django store charfield as a tuple?
Say I have a simple model in django class Customer(models.Model): session_id = models.CharField(max_length=200) nuts3 = models.CharField(max_length=200) To save a model object I will do this Customer.create(session_id = "unique_session_id", nuts3 = "some text") Now say that I need to overwrite the nuts3 in the saved model object with some other text customer = Customer.objects.filter(session_id = "unique_session_id") customer = customer[0] customer.nuts3 = "some new text" customer.save() When viewing the saved customer object in admin, I see a tuple in the nuts3 charfield ('some new text',). I have expected in the field only to have the string without a tuple. How come that Django added the string as a tuple? -
How to Convert This Sql Query TO Django Query
I want Get UID Based on Email Filtering Like "(select Uid From User_master where email = 'xyz.gmail.com')" How to Convert This Sql Query TO Django Query -
"version" key not founded in connect django and elastic-apm
i want to connect my django project with elastic apm but when i run my project, i see this line : No version key found in server response but my elastic server response have this key : { "name" : "something", "cluster_name" : "elasticsearch", "cluster_uuid" : "ikPV-LjKQ2mxKz3Nr0pNTQ", "version" : { "number" : "7.16.2", "build_flavor" : "default", "build_type" : "deb", "build_hash" : "2b937c44140b6559905130a8650c64dbd0879cfb", "build_date" : "2021-12-18T19:42:46.604893745Z", "build_snapshot" : false, "lucene_version" : "8.10.1", "minimum_wire_compatibility_version" : "6.8.0", "minimum_index_compatibility_version" : "6.0.0-beta1" }, "tagline" : "You Know, for Search" } and this is my django settitngs : ELASTIC_APM = { 'SERVICE_NAME': 'apm-inolinx', 'DEBUG': env('DEBUG'), 'SERVER_URL': 'http://127.0.0.1:9200', } -
Optimizing Database Population with Django
I have a 10GB csv file (34 million rows) with data(without column description/header) that needs to be populated in a Postgres database. The row data has columns that need to go in different Models. I have the following DB schema: Currently what I do is: Loop through rows: Create instance B with specific columns from row and append to an array_b Create instance C with specific columns from row and append to an array_c Create instance A with specific columns from row and relation to B and C, and append to an array_a Bulk create in order: B, C and A This works perfectly fine, however, it takes 4 hours to populate the DB. I wanted to optimize the population and came across the psql COPY FROM command. So I thought I would be able to do something like: Create instance A with specific columns from the file for foreign key to C create instance C with specific columns from the row for foreign key to B create instance B with specific columns from the row Go to 1. After a short research on how to do that, I found out that it does not allow table manipulations while copying … -
How to not change value if an input is empty
I have wrote this code for a form I was working on. <div class="col-md-6"><label class="labels">Doğum Günü:</label><input method="POST"name="birtdate" class="form-control" {% if student.birtdate%} type="text"value="{{student.birtdate}}" onfocus="(this.type='date')"onblur="(this.type='text')" {%else %}type="date" {% endif %}></div></div> It should show the initial value when blur and turn into a date field when focused. The problem is when I click on it and then click away it shows an empty value. I need to somehow check that and make it not change the value if the input is empty. How can I do that? -
Why am I not able to click my InlineRadios with CrispyForms?
For some reason I can't click the InlineRadio buttons that I'm creating with my crispy forms. When i click on them, nothing happens. I don't have any error messages in the console in the browser. Can someone help me figure out what is causing this? Forms.py class NewsEmailForm(forms.ModelForm): class Meta: model = NewsEmail fields = ('province', 'municipality', 'areas', 'interval', 'ad_type') help_texts = { 'areas': 'Håll in cmd (mac) eller ctrl (windows) för att markera flera', 'interval': 'Hur ofta du vill få ett mail med nya annonser i valt område.', } def __init__(self, *args, **kwargs): super(NewsEmailForm, self).__init__(*args, **kwargs) self.fields['province'].required = True self.fields['municipality'].required = True self.fields["interval"].choices = list(self.fields["interval"].choices)[1:] self.fields["ad_type"].choices = list(self.fields["ad_type"].choices)[1:] self.helper = FormHelper() self.helper.layout = Layout( Row( Column('province', css_class='form-group col-2 mb-0'), Column('municipality', css_class='form-group col-2 mb-0 ml-4'), Column('areas', css_class='form-group col-3 mb-0 ml-4'), Column( InlineRadios('interval'), css_class='form-group col-1 mb-0 ml-4' ), Column( InlineRadios('ad_type'), css_class='form-group col-1 mb-0 ml-4' ), Column( FormActions( Submit('submit', 'Spara bevakning', css_class='btn btn-sm btn-primary'), ), css_class='form-group col-1 mt-4 mb-0 ml-4' ), ), ) Models.py class NewsEmail(models.Model): INTERVAL_CHOICES = ( (1, "Veckovis"), (2, "Dagligen"), ) AD_TYPES_CHOICES = ( (1, "Hund erbjudes"), (2, "Hund sökes"), ) user = ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) province = ForeignKey(Province, on_delete=models.CASCADE, verbose_name='Landskap', null=True, blank=True) municipality = ForeignKey(Municipality, on_delete=models.CASCADE, verbose_name='Kommun', … -
How to make a query in Django that counts foreign key objects?
Hi all! New in Django, and confused, help is appreciated! I'm trying to create a table, like: Organization Total amount of appeals Amount of written form appeals Amount of oral form appeals Organization 1 3 1 2 Organization 2 2 1 1 Have three models: class Organization(models.Model): organization_name = models.CharField(max_length=50) class AppealForm(models.Model): form_name = models.CharField(max_length=50) class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE) applicant_name = models.CharField(max_length=150) Objects of Organization model: organization_name Organization 1 Organization 2 Objects of AppealForm model: form_name In written form In oral form Objects of Appeal model: organization appeal_form applicant_name Organization 1 In written form First and Last name Organization 1 In oral form First and Last name Organization 1 In oral form First and Last name Organization 2 In written form First and Last name Organization 2 In oral form First and Last name How to make a complex query, to retrieve info from Appeal model? And place to exact fields of the table above?:( -
How to prevent direct URL access in Django?
I am new to Django and I am doing a simple web application and I need to force users to enter their usernames and passwords to access the next page. I do not want them to get direct access to any page without logging in. I used the @login_required decorator, however, when I write (http://127.0.0.1:8000/logindata/) in the browser it gives me an error "Page not found". Would you help me, please? views.py: from django.shortcuts import render from django.http import HttpResponse from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc def index(request): if 'Login' in request.POST: rows = [] username = request.POST.get('username') if username.strip() != '': rows = getLogin(username) if len(rows) > 0: return render(request, 'login/welcome.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') def getLogin(UserName=''): command = 'EXEC GetLogin\'' + UserName + '\'' cursor = connection.cursor() cursor.execute(command) rows = [] while True: row = cursor.fetchone() if not row: break userName = row[0] password = row[1] name = row[2] email = row[3] rows.append({'userName': userName, 'password': password, 'name': name, 'email': email}) cursor.close() return rows @login_required(login_url='/index/') def readLogin(request): rows = getLogin() return render(request, 'login/loginsdata.html', {'rows': rows}) The app urls.py: from django.urls import path from . … -
Django Strawberry Graphql Bad request 'str' object has no attribute 'execute_sync'
So I have a simple django model class County(models.Model): '''County''' name = models.CharField(max_length=100, null=False, blank=False) class Meta: verbose_name_plural = "Counties" ordering = ['name'] def __str__(self): return self.name here is my types.py import strawberry from strawberry.django import auto from . import models @strawberry.django.type(models.County) class County: id: auto name: auto and my schema.py import strawberry from .types import * @strawberry.type class Query: county: County = strawberry.django.field() counties: List[County] = strawberry.django.field() schema = strawberry.Schema(query=Query) For url.py" from main.schema import schema from strawberry.django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), path('graphql', GraphQLView.as_view(schema='schema'), name='graphql'), ] Running the terminal gives me: Unable to parse request body as JSON Bad Request: /graphql [08/Jan/2022 03:28:08] "GET /graphql HTTP/1.1" 400 113111 When I go into the graphql terminal at http://localhost:8000/graphql there is no documentation in the documentation explorer. If I type a query like: { counties{ id name } } I get this: Internal Server Error: /graphql Traceback (most recent call last): File "C:\Users\00\Envs\eagle\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\00\Envs\eagle\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\00\Envs\eagle\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\00\Envs\eagle\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\00\Envs\eagle\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, … -
Django 3.2 Migrations - "NoneType" object has no attribute "_meta"
$ docker-compose exec myapp python manage.py migrate I've got this error after modifying my model, how can I rollback or fix the issue ? Traceback (most recent call last): File "/src/manage.py", line 21, in <module> main() File "/src/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/venv/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 268, in handle emit_post_migrate_signal( File "/opt/venv/lib/python3.10/site-packages/django/core/management/sql.py", line 42, in emit_post_migrate_signal models.signals.post_migrate.send( File "/opt/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/opt/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/opt/venv/lib/python3.10/site-packages/adminactions/models.py", line 9, in create_extra_permissions_handler p.create_extra_permissions() File "/opt/venv/lib/python3.10/site-packages/adminactions/perms.py", line 34, in create_extra_permissions content_types = ContentType.objects.get_for_models(*models) File "/opt/venv/lib/python3.10/site-packages/django/contrib/contenttypes/models.py", line 89, in get_for_models opts_models = needed_opts.pop(ct.model_class()._meta, []) AttributeError: 'NoneType' object has no attribute '_meta' -
Django REST Framework: COUNT query generated by PageNumberPagination is slow
I don't want to run count queries on views where count is not needed. How can I turn it off? I found the following workaround in another post on stackoverflow. The count query is not fired, but I can see pages that have no data. (I can see up to ?page=10000, even though there are only about 10 pages.) #settings.py REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 20, ... } import sys from django.core.paginator import Paginator from django.utils.functional import cached_property from rest_framework.pagination import PageNumberPagination class CustomPaginatorClass(Paginator): @cached_property def count(self): return sys.maxsize class CustomPagination(PageNumberPagination): django_paginator_class = CustomPaginatorClass -
How to fix this error failed to import test module while testing?
Here I'm writing some TestCase for some queryset to view in api and getting error not a valid function or pattern name. I didn't get any idea what missing here! Is there any solution for this? views.py class StudentView(generics.ListAPIView): queryset = StudentDetails.objects.raw('SELECT * FROM collegedetails.college_studentdetails LIMIT 3;') serializer_class = StudentDetailsSerializers test_views.py from rest_framework.test import APITestCase from rest_framework.reverse import reverse from rest_framework import status STUDENT_URL = reverse('student/') class StudentsDetailsTest(APITestCase): def test_details(self): response = self.client.get(STUDENT_URL, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) college/urls.py urlpatterns=[ path('student/',views.StudentView.as_view(), name='student'), ] traceback error Found 1 test(s). System check identified no issues (0 silenced). E ====================================================================== ERROR: college.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: college.tests Traceback (most recent call last): File "C:\Users\\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Users\\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\Users\\collegedjango\MYSITE\college\tests.py", line 33, in <module> STUDENT_URL = reverse('student') File "C:\Users\\collegedjango\venv\lib\site- packages\rest_framework\reverse.py", line 47, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File "C:\Users\\collegedjango\venv\lib\site- packages\rest_framework\reverse.py", line 60, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "C:\Users\\collegedjango\venv\lib\site- packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\\collegedjango\venv\lib\site- packages\django\urls\resolvers.py", line 729, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'student' not found. 'student' is not a valid view function or pattern …