Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a store with Django and Python that can handle millions of products?
Suppose I want to create a store with Django and Python. In each store, there are some products with a title, an amount of inventory, and some common features. However, there are some unique features for each product. For example, the features of a refrigerator are different from those of a dishwasher. It is not correct to define a separate model for each type of product when we may have millions of products like Amazon. What solution do you suggest for this problem? -
How can I ensure that user registration data is stored in both the 'Register' and 'Login' tables in my database?
Why is the user registration data only being stored in the 'Register' table and not in the 'Login' table in my Django application with MySQL? How can I modify my code to ensure that the registration data is stored in both tables when a user registers? I have separate tables for registration and login, where the 'Register' table contains columns such as 'Ent_ID', 'Username', 'Email_ID', and 'Password', and the 'Login' table contains columns such as 'Login_ID', 'Ent_ID' (foreign key referencing 'Register' table), 'Email_ID', and 'Password'. Any insights or suggestions on how to resolve this issue would be greatly appreciated. Thank you! I have created two tables in my Django application, 'Register' and 'Login', for user registration and login functionality respectively. The 'Register' table has columns like 'Ent_ID', 'Username', 'Email_ID', and 'Password', while the 'Login' table has columns like 'Login_ID', 'Ent_ID' (foreign key referencing 'Register' table), 'Email_ID', and 'Password'. When a user registers, I expected their registration data to be stored in both the 'Register' and 'Login' tables. However, only the data is being stored in the 'Register' table and not in the 'Login' table. As a result, I am unable to perform login functionality using the registered credentials. I have … -
I am getting an error in django saying it might be an issue with circular import but I am not sure how to fix. I think my code is correct
I am very new to coding so I will explain what I did step by step. I created a virtual environment in command prompt and then I installed django in that. Then, I opened the project in vs code and activated the new environment in the terminal. I then create calc by running the command: python manage.py startapp calc This my urls.py file in calc: ** from django.urls import path from . import views #from all import views urlpatterns = [ #setting up the mapping path('',views.home,name='home') #homepage can be represented by '' or '/' ]** and this is my views.py file: ** from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello world")** and my project url.py file: **from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ]** but when i run the command - python manage.py runserver I am getting this error: File "C:\Users\maya\env1\Lib\site-packages\django\urls\resolvers.py", line 725, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'calc.urls' from 'C:\Users\maya\myprojects\firstproject\calc\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. … -
jQuery is not giving output in console
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script> <script> localStorage.setItem('cart', JSON.stringify({})) if (localStorage.getItem('cart') == null) { let cart = {} console.log('Running properly....') } else { cart = JSON.parse(localStorage.getItem('cart')) } buttons = document.querySelectorAll('.cart') for (let button of buttons) { button.addEventListener('click', () => { if (cart[button.id] != undefined) { cart[button.id] += 1 } else { cart[button.id] = 1 } localStorage.setItem('cart', JSON.stringify(cart)) console.log(cart) }) } </script> I was building a ecom platform in Django so I wanted to make a function that whenever I click on my add to cart button the console will return the product number. That is why I wrote this jQuery at the very end of my index.html file but it's not working. Should I download jQuery for this? Because CDN is not working on my computer. -
Are there any functions to get only the language used to display browser UI in Django?
I set 3 languages on Google Chrome, then I set the 2nd language English for displaying the Google Chrome UI as shown below: Then, with request.META['HTTP_ACCEPT_LANGUAGE'], I tried to get only the 2nd language English used to display the Google Chrome UI because for users, I want to show my website in their languages used to display their browser UI by translation when they visit my website but I got all the languages set in Google Chrome as shown below: # "views.py" from django.http import HttpResponse def test(request): print(request.META['HTTP_ACCEPT_LANGUAGE']) # fr,en;q=0.9,ja;q=0.8 return HttpResponse("Test") So, are there any functions to get only the 2nd language English used to display the Google Chrome UI? -
How to change the default cookie name `django_language` set by `set_language()` in Django?
I could set and use set_language() as shown below: # "core/urls.py" ... urlpatterns += [ path("i18n/", include("django.conf.urls.i18n")) # Here ] Now, I want to change the default cookie name django_language below considering the security because users can easily know that Django is used for the website: So, how can I change the default cookie name django_language? -
Django: psycopg2: Could not translate host name to address: Name or service not known
I am attempting to connect to a PostgreSQL DB using psycopg2 and a django app. The pods running the application report the following error: 127.0.0.1 - - [13/Jul/2023:17:35:05 -0500] "GET /read HTTP/1.1" 301 0 "-" "PostmanRuntime/7.32.3" An error occurred while processing the GET request: could not translate host name "resume-postgresql-primary-hl " to address: Name or service not known Internal Server Error: /read/ When I run it on localhost, it works (connects to the DB and returns the data) Nslookup from the pods is also working: root@resume-backend-677cd68846-m22h8:/srv/app# nslookup resume-postgresql-primary-hl Server: 10.96.0.10 Address: 10.96.0.10#53 Name: resume-postgresql-primary-hl.resume.svc.cluster.local Address: 10.244.0.114 I can't figure out what is going on. Any ideas? -
How to include all fields from foreign key in django model form
I am trying to access the fields related to a foreign key from a model form. I have read the docs and it seems I should be able to access these fields with dot notation. Does what I am attempting make sense? Is there a better way to do this same thing. html form {% csrf_token %} {{ form.room.room_available }} {{ form.renter }} <input type="submit" value="Submit"> </form> Models.py class Room(models.Model): roomNum = models.CharField(max_length=20) room_is_premium = models.BooleanField(default=False) room_available = models.BooleanField(default=False) class BookedRoom(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True) renter = models.CharField(max_length=200) start = models.BooleanField(default=True) end = models.BooleanField(default=True) Views.py def bookRoomNow(request, pk): room = get_object_or_404(Room, pk=pk) if request.method == "POST": form = BookingForm(request.POST or None) if form.is_valid(): form = form.save(commit=False) #this room.instance form.room = room form.save() return redirect('room_details', pk=room.pk) else: form = BookingForm() context= {"form":form} return render(request, 'booker/booking_form.html', context) -
How do resolve error 400 in this case with method POST of Django Rest Framework when I create join method
I am redoing a course on DRFI want to post user, group with join method but I got error 400 when I post this to becoming member. The views, the models and the serializers are below. #Views.py ``` class MemberViewSet(ModelViewSet): queryset = Member.objects.all() serializer_class = MemberSerializer @action(detail=False, methods=['post']) def join(self, request): if 'group' in request.data and 'user' in request.data: try: group = Group.objects.get(id=request.data['group']) user = User.objects.get(id=request.data['user']) member = Member.objects.create(user=user, group=group, admin=False) serializer = MemberSerializer(member, many=False) reponse = {'message': 'Joined group', 'results': serializer.data} return Response(response, status=status.HTTP_200_OK) except: response = {'message': 'Cannot join'} return Response(response, status=status.HTTP_400_BAD_REQUEST) else: response = {'message': 'Wrong params'} return Response(response, status=status.HTTP_400_BAD_REQUEST)``` #models.py ``` from django.db import models, transaction from django.contrib.auth.models import User # Create your models here. class Group(models.Model): name = models.CharField(max_length=50, null=False, unique=False) location = models.CharField(max_length=50, null=False) description = models.CharField(max_length=250, null=False, unique=False) active = models.BooleanField(default=True) class Meta: unique_together=(('name', 'location')) def __str__(self): return self.name @transaction.atomic def disable(self): if self.active is False: return self.active = False self.save() self.events.update(active=False) class Event(models.Model): name = models.CharField(max_length=25, default='Match') team1 = models.CharField(max_length=32, blank=False) team2 = models.CharField(max_length=32, blank=False) time = models.DateTimeField(null=False, blank=False) score1 = models.IntegerField(null=True, blank=True) score2 = models.IntegerField(null=True, blank=True) group = models.ForeignKey(Group, related_name='events', on_delete=models.CASCADE) active = models.BooleanField(default=True) def __str__(self): return self.name class Member(models.Model): group … -
Python Django not able to get the data in a table form in my page instead it is returning a plain json object
my html page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"> <body> <div class="container"> <h1>Product</h1> <table id="products" border="1"> <thead> <th>Id</th> <th>Name</th> <th>Quantity</th> <th>Price</th> </thead> <tbody> <tr> <td id="product-id"></td> <td id="product-Name"></td> <td id="product-quantity"></td> <td id="product-price"></td> </tr> </tbody> </table> <br><br> <a href="{% url 'index' %}"><button id="back-button">Back</button></a> </div> <script> fetchProductDetails(); function fetchProductDetails() { const productId = getProductIdFromUrl(); fetch(`/product/${productId}`) .then(response => response.json()) .then(data => { const productData = data; const productTable = document.getElementById('productId'); const tbody = productTable.querySelector('tbody'); const row = document.createElement('tr'); row.innerHTML = ` <td>${productData.id}</td> <td>${productData.Name}</td> <td>${productData.quantity}</td> <td>${productData.price}</td> `; tbody.appendChild(row); }) .catch(error => { console.error('Error:', error); }); } function getProductIdFromUrl() { const urlSegments = window.location.href.split('/'); return urlSegments[urlSegments.length - 2]; } </script> </body> and my urls.py line which redirects me to the method path('product/<int:id>/', views.product_detail, name='product_detail'), and corresponding views method from the urls.py def product_detail(request, id): try: product = Product.objects.get(id=id, user=request.user) product_data = { 'id': product.id, 'Name': product.Name, 'quantity': product.quantity, 'price': product.price } return JsonResponse(product_data) except Product.DoesNotExist: return HttpResponseNotFound() and my urls.py path('product/<int:id>/', views.product_detail, name='product_detail'), I am getting the response like this when i hit http://127.0.0.1:8000/product/9/ I am not able to render my getbyid.html page, any suggestions? … -
One large model or two smaller models
I'm developing a database that holds financial information. I have two models: Company (~30 fields) CompanyFinacials (~120 fields) CompanyFinacials includes a field with Company as a primary key to maintain the relationship. I need to 10 add investment rounds to CompanyFinacials. Each round will have 12 fields. So, the question is, do i build it like this: class CompanyFinancials(models.Model): company = models.OneToOneField(Company, on_delete=models.CASCADE, primary_key=True) date_added = models.DateTimeField(auto_now=True) financial_start_year = models.CharField(max_length=2000, default='NONE', blank=True) ... ... ... ... class fundingRound(models.Model): company_obj = models.OneToOneField(Company, on_delete=models.CASCADE, primary_key=True) funding_stage = models.CharField(max_length=2000, default='NONE', blank=True) target_size_of_raise = models.CharField(max_length=2000, default='NONE', blank=True) invest_amount = models.CharField(max_length=2000, default='NONE', blank=True) investment_vehicle = models.CharField(max_length=2000, default='NONE', blank=True) discount_percent = models.CharField(max_length=2000, default='NONE', blank=True) pre_money_valuation = models.CharField(max_length=2000, default='NONE', blank=True) dilution = models.CharField(max_length=2000, default='NONE', blank=True) post_money_valuation = models.CharField(max_length=2000, default='NONE', blank=True) equity_percent = models.CharField(max_length=2000, default='NONE', blank=True) or like this: class CompanyFinancials(models.Model): company = models.OneToOneField(Company, on_delete=models.CASCADE, primary_key=True) date_added = models.DateTimeField(auto_now=True) financial_start_year = models.CharField(max_length=2000, default='NONE', blank=True) ... ... ... round1_funding_stage = models.CharField(max_length=2000, default='NONE', blank=True) round1_target_size_of_raise = models.CharField(max_length=2000, default='NONE', blank=True) round1_invest_amount = models.CharField(max_length=2000, default='NONE', blank=True) round1_investment_vehicle = models.CharField(max_length=2000, default='NONE', blank=True) round1_discount_percent = models.CharField(max_length=2000, default='NONE', blank=True) round1_pre_money_valuation = models.CharField(max_length=2000, default='NONE', blank=True) round1_dilution = models.CharField(max_length=2000, default='NONE', blank=True) round1_post_money_valuation = models.CharField(max_length=2000, default='NONE', blank=True) round1_equity_percent = models.CharField(max_length=2000, default='NONE', blank=True) round2_funding_stage = models.CharField(max_length=2000, default='NONE', blank=True) round2_target_size_of_raise … -
Retrieve model fields related which are related to another model (even with intermediate models/foreign_keys)?
I have model A, B and C. Model C has field X, which is a foreign key to field X_1 in model B. Model B has field Y, which is a foreign key to field Y_1 in model A. In a form, I want to retrieve only the related fields from model C, which relate to model A (in whatever way). Basically, in a form I select the function is on model C, but I select the parent is Model A (this has to do with identifying the sequence of presenting the fields). What I want to, is from model C, which field(s) relate to model A, and in which way? In this case, I would post the parent is A, the child is C, and would expect the function to return X_1__Y_1. Where X_1 represents the object in model B, and Y_1 represents the related(/parent) object in model A. What I can think of, is a seperate model, to capture all relations to other models (through a cron/celery and invoke on first setup, or through manage.py after a migration), through a breadt-first-search or something. Than I guess I could do with 4 fields: Model, Field, Destination_Model, Relation. But it … -
Trying to understand ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
My specific question is, how do I fix this import error so that I can run the python manage.py runsever command? For some reason my environment did get deleted and I was not pleased about that but when I reinstalled everything I had these issues. I have searched on stack overflow articles and come up empty. So far I have: I asked chat gpt what a python enviornment variable is: The PYTHONPATH environment variable in Python contains a list of directories where Python looks for modules and packages to import. It allows you to specify additional directories that Python should search when importing modules. It went on to say run pip install django. Which I have done, I also activated my virtual enviornment. How do I see my python environment variables? How do I add Django to it? Any advice? https://github.com/strikeouts27/mysite -
Duplicate validation message in Django contact form with Bootstrap 5 and Crispy Forms
I have a contact form in Django that I've styled using Bootstrap 5 and Crispy Forms. The form includes validations on fields, such as email validation and required fields. The issue I'm facing is that the validation message is being duplicated on the page when an error occurs. For example, if I submit the form without filling in the email field, two identical error messages appear. I've reviewed my code and templates multiple times, but I can't seem to find the cause of the duplication. Here's my relevant code: [forms.py] from crispy_bootstrap5.bootstrap5 import FloatingField from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Submit from django import forms from django.core.validators import EmailValidator class CustomSubmit(Submit): field_classes = "btn btn-outline-primary" class FormularioContacto(forms.Form): nombre = forms.CharField( label='Nombre', max_length=50, required=True, ) email = forms.EmailField( label='Email', required=True, validators=[EmailValidator()], error_messages={'invalid': 'Correo electrónico no válido'}, ) contenido = forms.CharField( label='Mensaje', widget=forms.Textarea(), required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'formularioContacto' self.helper.form_class = 'formulario' self.helper.form_method = 'post' self.helper.attrs = {'novalidate': True} # Add 'novalidate' attribute to the form self.helper.layout = Div( Div( Div( FloatingField('nombre'), FloatingField('email'), FloatingField('contenido'), Div( CustomSubmit('Enviar', 'submit', css_class='btn-lg'), css_class='text-center mt-3' ), css_class='col-md-6 mx-auto' ), css_class='row' ), css_class='container my-4' ) [views.py] import smtplib … -
How should I add custom validation to the Django admin for a non-standard model field?
I have a non-standard Django model field (pg vector list/array) which is resulting in a validation error when the admin application attempts to naively validate it: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I have tried specifying a vector-specific validation function using the model field's validators list, overriding the models clean method, etc. without success. What would be the appropriate way of handling this? -
How to define a Django model for your historical table,
Let's assume the model is named RateHistory and contains the fields rate and updated_date from django.db.models import F def get_rate_changes(): previous_rate = None rate_changes = [] for record in RateHistory.objects.order_by('updated_date'): if previous_rate is not None and previous_rate != record.rate: rate_changes.append(record.updated_date) previous_rate = record.rate return rate_changes After implementing the code and calling the get_rate_changes function, you should expect to retrieve a list of updated dates when the rate changed in your RateHistory table -
GitHub Action Error: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' while deploying on Azure App Service
I built a simple Django application and am trying to deploy it using Azure App Service and GitHub Actions CI/CD. While deploying, I am getting the error- Here is my project directory structure- Can somebody please help me understand what the issue is here? I came accross this answer but this is not working for me- GitHub for Django on Azure: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' -
trying to Dockerize a Django/Pyhton project, with no success
I'm trying to dockerize a backend project, made with django/python and postgreSQL It works as an api, its structure is: backend api models.py urls.py views.py ... menu_back manage.py settings.py Dockerfile requirements.txt But I get an error saying that moule backend can't be found This is my Dockerfile: # Use an official Python 3.11.2 runtime as the base image FROM python:3.11.2 # Set the working directory in the container WORKDIR /app/backend # Copy the requirements file into the container COPY requirements.txt . # Install the Python dependencies RUN pip install --no-cache-dir -r requirements.txt # Copy the Django project code into the container COPY . . # Set environment variables for PostgreSQL ENV POSTGRESHOST=db ENV POSTGRESPORT=5432 ENV POSTGRESUSER=postgres ENV POSTGRESPASSWORD=mypassword ENV POSTGRES_DB=mydatabase CMD python menu_back/manage.py runserver 0.0.0.0:8000 # Expose the port on which the Django server will run EXPOSE 8000 I move to the backend directory and execute 'docker build -t backend-image -f Dockerfile .' it runs ok, but when trying to run it with 'docker run -p 8000:8000 backend-image', I get this error: ModuleNotFoundError: No module named 'backend' In the file manage.py, I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.menu_back.settings") I don't know how to fix it, even chatgpt is cycling with answers but the … -
Adding Embedded HTML to Email Messages in Django
I'm trying to add an Embedded HTML to an Email to send an Image in it, but image doesn't seem to appear in here, I reviewed another solutions but nothing seems to result views: img_path = os.path.join(settings.BASE_DIR, 'Mods\Surveys\static\images\Survey.jpg') print(img_path) html_content = render_to_string('email_template.html', { 'survey': survey, 'url': survey.url, 'path': img_path, }) msg = EmailMultiAlternatives( subject=survey.subject, body=strip_tags(html_content), from_email='my email', to=[respondant.email] ) msg.attach_alternative(html_content, "text/html") msg.send() template: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <h1>{{ survey.subject}}</h1> <p>{{ survey.body}}</p> <a href="{{ url }}"><img src="{{ path }}" alt="Image"></a> </body> </html> Email is sent with subject body and the url, but image doesn't appear As I said, I reviewed another solutions but nothing seems to help -
How to create a manytomany relation in django to models with different data type primary key
I have a model whose primary key is of Integer field datatype and I want to have a manytomany field inside it of another model whose primary key is of Char field. class A(models.Model): count = models.IntegerField(default=0) link = models.ManyToManyField(B, null=True) class B(models.Model): test = models.CharField(primary_key=True, max_length=36) When I used this method I got this error: (errno: 150 "Foreign key constraint is incorrectly formed") I got to know that a association table is required, but don't know how to apply it. -
Django: ModuleNotFoundError. No module named 'myApp'
I am using termux I created a virtual environment, started django project, cd into the second directory of my project, and started an app. Here is the arrangement of my dir. and files I added the app to the INSTALLED_APP in setting.py INSTALLED_APPS in settings.py When I run 'python manage.py runserver, I get an error: ModuleNotFoundError. No module named 'myApp_name' Error message after running 'python manage.py runserver' Please help me resolve this issue. I am a beginner and have been on this for two days I am stuck and can't learn further. I expect 'python manage.py runserver' to run without an error, since I started an app and added its name to INSTALLED_APP -
How to run celery in django from docker
I learn docker and don't understand why celery can't connect to rabbitmq. I've created 2 images for rabbitmq and django, here is my docker-compose: version: "3.0" services: # WEB django: build: . volumes: - media_volume:/website/journal_website/media - static_volume:/website/journal_website/static - database_volume:/website/journal_website/database ports: - "8000:8000" depends_on: - rabbit # RabbitMQ rabbit: hostname: rabbit container_name: rabbitmq image: rabbitmq:3.12-rc-management environment: - RABBITMQ_DEFAULT_USER=simple_user - RABBITMQ_DEFAULT_PASS=simple_password ports: # AMQP protocol port - "5672:5672" # HTTP management UI - "15672:15672" restart: always volumes: media_volume: static_volume: database_volume: my broker configuration in settings.py in django: CELERY_BROKER_URL = 'amqp://localhost:5672' celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") celery_application = Celery("website") celery_application.config_from_object("django.conf:settings", namespace="CELERY") celery_application.autodiscover_tasks() entrypoint.sh that's used as entrypoint in Dockerfile: #!/bin/bash # Start Celery celery -A website worker -l info # Run Django server python3.11 manage.py runserver 127.0.0.1:8000 and Dockerfile: # Many many commands to install python and all dependencies in ubuntu 20.04 # Run Django server EXPOSE 8000 ENTRYPOINT ["/entrypoint.sh"] I use Docker Desktop on Windows 10, when I run docker compose up or run container in desktop application I get such error: [Date: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused., I've checked that localhost is 127.0.0.1. What should I … -
Django: Implementing a dependent dropdown list in a form
Hello StackOverflow community! I am new to programming and am currently working on a Django-based website for ITSM ticket management. My site has two main components: A ticket manager that displays created tickets, their status, address, assigned technician, problem description, etc. An administrative part in Django, which only certain users have access to. I am having trouble implementing a ticket creation or update form. I am trying to implement a dependent dropdown list functionality: when a district is selected in the ticket creation form, only a list of technicians associated with that district should be displayed in the "Technician" field. I am unsure of how to correctly implement this functionality. Maybe I should use JavaScript or AJAX, or is there a way to do this directly in Django? Your guidance or pointers would be highly valuable. Thank you for your assistance! **models.py** `from django.db import models from django.utils import timezone from django.utils.formats import date_format from django import forms class Ticket(models.Model): STATUSES = ( ('new', 'Новый'), ('in_progress', 'В работе'), ('overdue', 'Просрочен'), ('deferred', 'Отложенный') ) DEVICE_CHOICES = [ ('Выберите тип прибора', 'Выберите тип прибора'), ('Stemax', 'Stemax'), ('Приток', 'Приток'), ('Болид', 'Болид'), ('Альтоника', 'Альтоника'), ] title = models.CharField(max_length=200, default='Default Title') # Добавлено новое поле … -
Cache API for requested ID for specific time / Django admin filter
I'm learning python for few weeks and I'm creating hockey app. I have two problems. text In this API we have about 1000 players with specific ID. I know how I get specific value and how I create for loop for all values, but I don't want send request for all players (ofc) and store this values in a database or send request every time when some app user want it. So when user send request for example for Ovechkin, for McDavid..., how I could cache this for some time because data should be updated - if they play another match? Should I do something in Redis or django-cache? I created models in Django - Team, League, Fixture. I added teams and assign them League(NHL, SHL, DEL etc.) and for fixture? I chose league NHL and saw all teams(included from Germany, Sweden) still. How I can create live filter in Django Admin when I click on NHL = all non-NHL teams disappear. class League(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Team(models.Model): name = models.CharField(max_length=128, unique=True) league = models.ForeignKey(to=League, on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Fixture(models.Model): league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='fixtures') home_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_games') away_team = … -
Django NoReverseMatch - content doesn't load properly
I have a blog app in my Django project that is based on this tutorial. With the link to the blog placed in my main.html template, the site throws a NoReverseMatch error. I can't seem to figure it out. Here's the HTML: <li class="nav-item"><a href="{% url 'blog' %}" class="nav-link" id="header">Blog</a></li> Here's the urls.py code: from django.contrib import admin from main import views from django.conf.urls import include from django.urls import path from main.views import dashboard, register, about, blog from django.conf import settings from django.conf.urls.static import static app_name = 'main' urlpatterns = [ path('', views.main, name='main'), path('admin/', admin.site.urls), path('dashboard/', dashboard, name='dashboard'), path('accounts/', include('django.contrib.auth.urls')), path('register/', register, name='register'), path('about/', about, name='about'), path('blog/', include('blog.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Here's the other urls.py: # main/urls.py from django.urls import path, include from main.views import dashboard, register app_name = 'main' urlpatterns = [ path('blog/', blog, name='blog'), ] Here's the views.py code: # main/views.py from django.http import HttpResponse from django.contrib.auth import login as auth_login from django.shortcuts import redirect, render from django.urls import reverse from main.forms import CustomUserCreationForm # Create your views here. def main(request): return render(request, 'main.html', {}) def dashboard(request): return render(request, 'users/dashboard.html') def admin(request): return render(request, 'admin') def login(request): return render(request, 'registration/login.html') def register(request): if request.method == 'GET': …