Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the Queryset with values_list in django?
Here I have a model Zipcodes for zipcodes ,states and cities. I have another model which has Foregin Key to the Zipcodes. Here I want to display distinct states in the create_person template.For this I did values_list, flat=True but in order to create the person model I need Zipcode Pk but values_list don't give the pk So I tired using list_comprehension and ohter method too which are below as a comment. I want to pass the queryset to the template with the distinct state values.How can I do it here ? class Zipcodes(models.Model): zip_code = models.CharField(max_length=100, db_column='zipcode') city = models.CharField(max_length=200) state = models.CharField(max_length=200) class Person(models.Model): state = models.ForeignKey(Zipcodes, on_delete=models.CASCADE) full_name = models.CharField(max_length=255) views class CreatePersonView(SuccessMessageMixin, generic.CreateView): model = Person fields = '__all__' template_name = 'create_person.html' success_url = reverse_lazy('list_persons') success_message = 'Created Successfully.' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) all_states = Zipcodes.objects.values_list('state', flat=True).distinct() # context['states'] = Zipcodes.objects.filter(state__in=all_states) # context['states'] = [state for state in all_states if Zipcodes.objects.filter(state=state)] # for state in all_states: # context['states'] = Zipcodes.objects.filter(state=state) return context Template <label class="pending--option">State</label> <select name="state" class="form-control"> {% for state in states %} <option value="{{state.pk}}"> {{state.state}} </option> {% endfor %} </select> -
Full config path vs app name in Django INSTALLED_APPS
In the Django documentation, a line reads: New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS. This suggests I should require users of my app (let's called it sports) to use the following string in their INSTALLED_APPS list: "sports.apps.SportsConfig" However, all of the Django apps I use (django-rest-framework, django-cors-headers, django-celery-results) use default_app_config and only require me to specify the first part of the string (in my case "sports"). So how should I write my app? (1) Follow the advice in the docs and force users to write the entire string "sports.apps.SportsConfig" or (2) Follow what all of the other apps in the Django universe are doing and allow users to write only the first part of the string "sports". -
I'm not able to perform validation for the input data in my mongoengine model class
class TextBoxValues(DynamicDocument): entity_id = StringField(max_length=200, required=True) textbox_type = StringField(max_length=1000, required=True) regexp = re.compile('[A-Za-z]') entity_value = StringField(regex=regexp,max_length=None, required=True) I was using the regex parameter to perform validation which is not working for me,it still takes input in any format, why? -
Query to find maximum in django
I need to find maximum score of user id with the maximum quiz score in a category. My Model: class QuizCat(models.Model): cid = models.IntegerField(unique=True) c_name = models.CharField(max_length=200) class Quiz(models.Model): Qid = models.IntegerField() cat_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE) name = models.CharField(max_length=200) class UserDetails(models.Model): user_id = models.IntegerField() Qid = models.ForeignKey(Quiz, on_delete=models.CASCADE) score = models.IntegerField() I tried: category_id = request.GET.get('category_id') result = UserDetails.objects.all().values('user_id').annotate(score=Sum('score')).filter(Qid__cat_id=category_id) But the above did not work. -
How to annotate custom functions about dates in Django queryset
I have a shitf_days which is IntegerField, I hope to annotate a Expected_date, it will be today's date plus shitf_days My code is as follows: import arrow class list_A(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request).annotate( shitf_days=ExpressionWrapper( F("Field_A") / F("Field_B"), output_field=IntegerField() ), Expected_date=ExpressionWrapper( arrow.now().shift(days=F("shitf_days")).datetime.date()), output_field=DateField() ) ) return qs But I get the following error: TypeError: unsupported type for timedelta days component: CombinedExpression -
How to connect Django Python to SQL Server 2017 using VS Code on Windows System
I'm trying to establish a connection between Python Django and MS SQL using Visual Studio Code on Windows 10 system. I can't seem to find good resources/tutorials/references. Any help would be highly appreciated. -
'mysql.connector.django' isn't an available database backend Django Version 3.+
After Upgrading the version of Django from 2.+ to 3.+ then the error occur after upgrading. Django==3.0.4 mysql-connector==2.2.9 mysql-connector-python==8.0.19 mysqlclient==1.4.6 PyMySQL==0.9.3 and this is the error message: django.core.exceptions.ImproperlyConfigured: 'mysql.connector.django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Django CRUD Ajax
I am building an application where I want users to be able to create posts. However, when I added the functionalities nothing happens after creating the 'Post' button, I can see that Django is not getting the url in the console. Here is my Ajax code for Creating, Updating and Removing, the Update and remove work fine however the create is not working. $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } } }) return false; } // create $(".show-form-create").click(ShowForm); $("#modal-post").on("submit",".create-form",SaveForm); //update $('#post-list').on("click",".show-form-update",ShowForm); $('#modal-post').on("submit",".update-form",SaveForm) //delete $('#post-list').on("click",".show-form-delete",ShowForm); $('#modal-post').on("submit",".delete-form",SaveForm) }); This is my views.py: @login_required def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) @login_required def post_create(request): if request.method == 'POST': form = PostForm(request.POST) else: form = PostForm() return save_all(request, form, 'home/post_create.html') And this is the button I use: <button … -
Fullcalender display events in Django
I am using full calendar in my in my Django project and I was wondering how I would get the model data to load as an event within the calendar. The issue is whenever I try to load the template into my code it loads up a white page with text in JSON format. I was wondering if it was possible to get by this. This is how my model looks like: class CalenderEvent(models.Model): event_name = models.CharField(max_length = 30) start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) event_description = models.TextField() def __str__(self): return self.event_name This is how my view looks like: def calender(request): events = CalenderEvent.objects.all() if request.method == 'GET': form = ContactToAddEventForm() event_arr = [] for i in events: event_sub_arr = {} event_sub_arr['title'] = i.event_name start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) return HttpResponse(json.dumps(event_arr)) context = { "events" : events } return render(request, 'calender.htm', {'form': form}, context) This is how my template looks like: <link rel="stylesheet" href="{% static "fullcalender/daygrid/main.css" %}" > <link rel="stylesheet" href="{% static "fullcalender/timegrid/main.css" %}" > <link rel="stylesheet" href="{% static "fullcalender/core/main.css" %}" > <script rel="stylesheet" href="{% static "fullcalender/core/main.js" %}" ></script> <script src="{% static "fullcalender/core/main.js" %}"></script> <script src="{% static "fullcalender/daygrid/main.js" %}"></script> <script … -
Django Admin Template add custom link under app
I would like to add a Transaction history link within my app , for example i have an Administration app with 1 model like so: I would like to add a link under Log entries So i created file /appname/templates/admin/appname/index.html and following the django index.html template i override it like so: {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}">{% endblock %} {% block coltype %}colMS{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} <div id="content-main"> {% if app_list %} {% for app in app_list %} <div class="app-{{ app.app_label }} module"> <table> <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">{{ app.name }}</a> </caption> {% for model in app.models %} <tr class="model-{{ model.object_name|lower }}"> {% if model.admin_url %} <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th> {% else %} <th scope="row">{{ model.name }}</th> {% endif %} {% if model.add_url %} <td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td> {% else %} <td>&nbsp;</td> {% endif %} {% if model.admin_url %} {% if model.view_only %} <td><a href="{{ model.admin_url … -
How to call a function with different args when testing django
I have a function that checks whether correct kwargs have been passed something like below def check_kwargs(**kwargs): arg_1 = kwargs.get('arg_1', None) arg_2 = kwargs.get('arg_2', None) if arg_1 is None or arg_2 is None: raise Exception() I need to test the if statements (the case where arg_1 and arg_2 was not passed. I know that mock can simulate a return value and side_effect can completely replace the function. However, what I want to do is to call the original function just with different arguments (no arguments). How do I achieve this? -
How to get changing VPN IP in file format
I am having 400 machines and all are connected to VPN network and i want to deploy an application(available on server).Here i am facing problem how to collected all VPN IP in one file and evaluate how many of them are offline OR how many of them coming and also thinking about business logic(code). Please let me know if any suggestion OR steps. -
Raise an error on a field based on a ForeignKey field of the model DJANGO
Thanks for your time: i've got a model to get more user information by OneToOneField and the username becomes the Pets.pessoa field when saving it bascally i'd like to raise an error if the foreignkey field(Pets.pessoa) starts with 'a' and Pets.tipo == 2 i'm getting the object created even when the error should appear Models.py: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) Forms.py: class PetForm3(forms.ModelForm): #SELECIONAR FORM PELO FORMS.PY field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO') ] nome = forms.CharField(max_length=100) custo = forms.DecimalField(max_digits=7, decimal_places=2) tipo = forms.ChoiceField(choices=field_choices) def clean(self, *args, **kwargs): pessoa_data = self.cleaned_data.get('pessoa') pessoa_string = slugify(pessoa_data) tipo_data = self.cleaned_data.get('tipo') if pessoa_string.startswith('a') and tipo_data==2: raise ValidationError('User começando com A não pode ter gato') return super(PetForm3, self).clean(*args, **kwargs) Views.py: def create_pet_form(request): if request.method == 'POST': form = PetForm3(request.POST) if form.is_valid(): pet = form.save(commit=False) pet.pessoa = request.user.person form.save() else: form = PetForm3() context = { 'form': form } return render(request, 'petform3.html', context) -
(Django)(Important)(Short) How can I roll back DB that changed in unwanted way after renaming fields in models.py
I have a question in Django. I renamed fields in my models.py on my editor. After renaming the name of fields, I made makemigrations and did 'migrate' on cmd. After 'migrate', I checked my database on DB broswer and I found that not only the name of fields changed, but the data of the fields also changed into the name of fields I just changed as just lowercased. i.e.) Original name of field was ingredient and I changed the name to Essential_ingredient. I checked DB and turned out that all of data for the column of changed field is essential_field like picture. Database after renaming fields I posted this question on FB page and one said I can roll back(revert) by doing "migrate ". So I tried it and then it turned out that the field came back correctly to purposedly migrated file, but the data of the field still haven't changed back yet. Database after reverting migrations I guess this problem happened because, when I renamed fields, I renamed two of them at the same time. I saw a comment on stackoverflow that I'm supposed rename the one field at a time, but this was after I'd changed names … -
How to change the name of objects in Django admin?
I am using this code: def __str__(self): return self.title But the names of each objects are still not changing: What to do? -
Django raw query syntax and parameters
What is the correct syntax for raw queries in Django? I always see those easy kind of examples like: lname = 'Doe' connection.execute('SELECT * FROM table WHERE last_name = %s', [lname]) It's awesome how less one parameter explains if you dive into deeper detail! How about: set_var = ((0,'val',3.5),(1,'tadaa',5)) connection.execute("INSERT INTO table VALUES (%s)",[set_var[0]]) or: head = [col1 int(11), col2 int(12), col3 varchar(255)] connection.execute("CREATE TABLE IF NOT EXISTS `%s` %s", [table, '('+str(', '.join(head))+')']) and then there is: query = """SELECT %s FROM special_table""" connection.execute(query, ["*"]) or I could write everyhting simple into a string? connection.execute("SELECT "+injection+" FROM yetAnotherTable") Do I have to use anywhere ';' in the End of the query? And I also saw, that people used {}. format() for querystrings ... And what's the point about backticks? Why shall I not use them? How can I handle a tablename including a "-" ? I'm super confused about the syntax for writing raw queries. Especially about the parameter part. What is allowed? And what is not allowed? Could somebody delight the topic a bit more than the explanations of the Django doc, please! -
How to set environment variables for Django settings.py with Jenkins
I have a settings.py file for my Django project that reads in environment variables for some fields. This works great for local development. I'm not sure of how to make this work for my Jenkins build (Freestyle project). An extra layer of complexity is that some of these variables contain sensitive data (passwords, etc.) and so need to be secured. So far, I have been able to use Credentials Binding Plugin to set up a secret .env file and can successfully access that as an environment variable. How do I go about setting all the 'actual' variables from that file? Or is this bad practice? If it's not bad, wouldn't those variables continue living on the server after the build has finished? If it is bad, what is the better way to do this? I can update the settings.py file easily enough if needed to make this work. -
Bootstrap cards showing on the right side of the page
I want to add 3 cards, but when I try, the cards appear on the right side of the page maybe it is an error on the code before the cards. This is the code of the cards. <div class="card-deck mb-3 text-center"> <div class="card mb-4"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> <div class="card"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> </div> This is what I am getting, I want it to be at the middle. This is the page. -
Difference between using querying data and creating one through admin page?
I made some models and filled them with fields i.e. CharField and TextField. I registered my model in admin.py so that admin has the ability to create and edit the models in the admin page. Why do people use the terminal shell to query the database rather than using the admin page to simply create it there without the little hassle of importing the model and querying the database in the shell? -
Can't launch docker composer
I have this rep with a Django app and Docker, but docker-compose up is not working. This is my output: Starting covidoff-web_db_1 ... done Starting covidoff-web_webapp_1 ... done Starting covidoff-web_webserver_1 ... done Attaching to covidoff-web_db_1, covidoff-web_webapp_1, covidoff-web_webserver_1 db_1 | 2020-03-20 00:50:54.601 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2020-03-20 00:50:54.601 UTC [1] LOG: listening on IPv6 address "::", port 5432 webapp_1 | HOST: db:5432, DB: None, USER: postgres db_1 | 2020-03-20 00:50:54.605 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" webapp_1 | ==> Django setup, executing: flush db_1 | 2020-03-20 00:50:54.620 UTC [24] LOG: database system was interrupted; last known up at 2020-03-20 00:25:37 UTC db_1 | 2020-03-20 00:50:54.802 UTC [24] LOG: database system was not properly shut down; automatic recovery in progress db_1 | 2020-03-20 00:50:54.804 UTC [24] LOG: invalid record length at 0/16538C0: wanted 24, got 0 db_1 | 2020-03-20 00:50:54.804 UTC [24] LOG: redo is not required db_1 | 2020-03-20 00:50:54.817 UTC [1] LOG: database system is ready to accept connections webapp_1 | ==> Django setup, executing: migrate webapp_1 | Operations to perform: webapp_1 | Apply all migrations: admin, announcements, auth, contenttypes, sessions, tracker webapp_1 | Running migrations: webapp_1 | No migrations … -
Django raw queries with large params
I feel like going nuts with raw queries. Always Django complains about my misstakes: I try to write a function to copy a table from one database to another. CODE: def copy_tables(projectname): with connections['DB1'].cursor() as db1cursor: tables = get_all_custom_tables(projectname, 'DB1') for table in tables: with connections['django'].cursor() as db2cursor: db1cursor.execute("SELECT * FROM `" + table + "`") values = db1cursor.fetchall() db1cursor.execute("SHOW COLUMNS FROM `" + table + "`") columns = db1cursor.fetchall() v_col = [] for col in columns: v_col.append("`"+str(col[0]) + "` " + str(col[1])) #db2cursor.execute("DROP TABLE IF EXISTS `" + table + "`") ISSUE HERE----> db2cursor.execute("CREATE TABLE IF NOT EXISTS `%s` (%s)", [table, ", ".join(v_col)]) db2cursor.execute("INSERT INTO `%s` VALUES %s" ,[table, values[0]]) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''userID int(11), TaskID varchar(128), techID varchar(128), `imgI' at line 1") I don't see the error? What is it? Do the execute paramters need to have special types? Does it matter if I always handle Strings? I also had an issue with None for a field before I run into this issue. Can somebody point me at a good ressource for mysql-python syntax. … -
Multiplos models - tres apps
Boa noite prezados... meu projeto de TCC, tem três apps: turmas, salas e alocar. eu preciso fazer as alocações das turmas nas salas, depois de alocadas preciso marcar um boleano da turma como alocada, e um boleano da sala como indisponivel. abaixo envio o codigo para ficar melhor elucidado. como devo implementar isso? estou empacado nesse ponto, confesso que sou inexperiente com django. ''' app turmas class Turma(models.Model): turma = models.CharField('Turma', max_length=20) curso = models.CharField('Curso', null=False, max_length=50) periodo = models.CharField('Periodo', null=False, max_length=50) disciplina = models.CharField('Disciplina', max_length=50) qtdalunos = models.IntegerField('Qtd') professor = models.CharField('Professor', max_length=50) alocada = models.BooleanField('Alocada', default=False) internet = models.BooleanField('Internet', default=False) projetor = models.BooleanField('Projetor', default=False) computador = models.BooleanField('Computador', default=False) ''' ''' #app salas class Sala(models.Model): bloco = models.ForeignKey(Bloco, on_delete=models.PROTECT) sala = models.CharField('Sala: ', unique=True, max_length=50) capmaxima = models.IntegerField('Cap. Máxima: ') disponivel = models.BooleanField('Disponivel', default=True) ocupada = models.BooleanField('Ocupada', default=False) internet = models.BooleanField('Internet', default=False) projetor = models.BooleanField('Projetor', default=True) computador = models.BooleanField('Computador', default=False) #alocar class Alocar(models.Model): data = models.DateField('Data', auto_now=True, blank=True) dias = [ ('A Confirmar', 'A Confirmar'), ('Segunda', 'Segunda'), ('Terça', 'Terça'), ('Quarta', 'Quarta'), ('Quinta', 'Quinta'), ('Sexta', 'Sexta'), ('Sábado', 'Sábado'), ] dia = models.CharField('Dia', max_length=11, choices=dias, default='A Confirmar') horario = models.ForeignKey(Horario, on_delete=models.CASCADE) turma = models.ForeignKey(Turma, on_delete=models.SET()) sala = models.ForeignKey(Sala, on_delete=models.SET())ode here Obrigado pela … -
Django change extablished column with values into a ForeignKey
I have the following model in place: class IssueDescription(models.Model): no = models.CharField(max_length=10, primary_key=True) title = models.CharField(max_length=200, blank=False) confirm = models.TextField() remedy = models.TextField() subsystem = models.CharField(max_length=50, blank=False) It already lives in Postgres DB, and is populated with values. The values held in it came from a .csv file (including subsystem values). What I realized, is that I would like to make subsystem column into a ForeignKey, and move all the values from it into a separate table, e.g.: class Subsystems(models.Model): subsystem = models.CharField(max_length=50, blank=False) class IssueDescription(models.Model): no = models.CharField(max_length=10, primary_key=True) title = models.CharField(max_length=200, blank=False) confirm = models.TextField() remedy = models.TextField() subsystem = models.ForeignKey(Subsystems, on_delete=models.PROTECT, blank=False) What would be the cleanest way of moving already established values in the original IssueDescription model's subsystem column to a newly created Subsystems table, and drawing all the links via ForeignKey field in a new IssueDescription model? -
Django-Filters , Django-tables autocomplete search
Im quite new to django so not very familiar with things. Im trying to autocomplete one of the files and clients filters for django-tables. I was trying to use django-autocomplete-light ( dal). Using Python3 also and django version 2.2.8. Im finding that dal.autocomplete doesnt have Select2QuerySetView or ModelSelect2. Im using django-tables 2 example to filter the table by fields but my 'exact' filterset like files and clients are long lists and hard to read so i want to be able to autocomplete search in the filter forms. Any help is much appreciated. filters.py class ClientFilesFilter(FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) requestdatetime = django_filters.IsoDateTimeFromToRangeFilter( lookup_expr=('icontains'), widget=django_filters.widgets.RangeWidget( attrs={'type':'datetime-local'} ) ) #file = django_filters.ModelChoiceFilter(queryset=Files.objects.all(), # widget=autocomplete.ModelSelect2(url='files-autocomplete')) class Meta: model = ClientFiles fields = {"client": ["exact"], "httpstatus": ["exact"], "objectsize": ["gte"], "referrer": ["icontains"]} views.py class FileAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Files.objects.filter(name='file_name.zip') return qs class FilteredPersonListView(ExportMixin, SingleTableMixin, FilterView): table_class = ClientFilesTable model = ClientFiles template_name = "bootstrap_template.html" filterset_class = ClientFilesFilter export_formats = ("csv", "json") def get_queryset(self): return super().get_queryset() def get_table_kwargs(self): return {"template_name": "django_tables2/bootstrap.html"}. urls.py urlpatterns = [ path("", FilteredPersonListView.as_view(), name="filtertableview"), path("api/", include('app.urls')), path("admin/", admin.site.urls), url(r'^file-autocomplete/$', FileAutocomplete.as_view(), name='file-autocomplete') ] -
Page not found when rendering page on Django
Trying to render a page but keep getting page not found error message despite trying different patterns on urls to define the path. This is what I have in my urls.py path('students/', include(([ path('', students.dashboard, name='quiz_list'), path('edit_user', students.edit_user, name='edit_user'), path('mentors', students.mentor_list, name='mentors'), path('what_is_ml', students.what_is_ml, name="what_is_machine_learning"), ], 'classroom'), namespace='students')), In my views (students.py): @login_required @student_required def what_is_ml(request): return render(request, 'classroom/students/what_is_machine_learning.html') and in my html: <i class="fa fa-fw fa-circle text-green-300" href="{% url 'students:what_is_machine_learning' %}"></i>What is Python This is the structure of my template files classroom -->students >what_is_machine_learning.html I am confused because this is how I defined every other page I am rendering. I have also tried this <i class="fa fa-fw fa-circle text-green-300" href="{% url 'students:what_is_ml' %}"></i>What is Python</i> and <i class="fa fa-fw fa-circle text-green-300" href="{% url 'what_is_ml' %}"></i>What is Python</i> But get the NoReverseMatch error messages