Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modification of UserCreationForm
My problem is that I am trying to modify the Django default UserCreationForm and its default messages, but it does not work. I also heard that some of the checks and initial messages are defined separately and should be customized separately, but I did not find a lot on that. I tried to search around, but most of what I found was either old and not working for current django version or did just modify the fields and not the error messages. I am importing the UserCreationForm in forms.py like this: from django.contrib.auth.forms import UserCreationForm And then I tried to modify it like this: The fields and everything is completely functional just the messages are still the default and not the custom I was trying to set. class UserSignUpForm(UserCreationForm): username = forms.CharField(label="custom", error_messages={'required': 'custom.', 'unique': 'custom.'}) password1 = forms.CharField(label="custom", widget=forms.PasswordInput, error_messages={'required': 'custom.'}) password2 = forms.CharField(label="Potvrďte custom", widget=forms.PasswordInput, error_messages={'required': 'custom.', 'password_mismatch': 'custom.'}) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields error_messages = { 'password_mismatch': {"password_mismatch": "custom"}, 'password_too_short': {"password_too_short": "custom"}, 'password_common': {"password_common": "custom"}, 'password_entirely_numeric': {"password_entirely_numeric": "custom"}, } If someone knows how to solve this, please let me know. I would appreciate any feedback. -
Django DRF how do I display not user: 1, but user_id: 1 when sending serialize.data
I came from FastAPI and Laravel and I'm more used to seeing the foreign key id as user_id rather than just user and the like, how can this be done? -
Can't send json reponse in requests mock
I'm looking for a way to test a function called fetch_options that basically renders a returned JSONResponse from an internal API. My approach to this test is to mock requests because the internal API is located in another app which has already tested in a different test suite. I've got a gut feeling that the function is properly patched with the mock but for some reason my render call can't get the response data, I might be wrong about this though. planner/views/meals.py def fetch_options(request, meal, field): if field == "ingredients": index = 1 else: index = 0 try: response = requests.get("log/api/send_" + field) #Trying to mock requests here, request fetches from /log/views/api.py except ConnectionError: requests.raise_from_exception() else: return render(request, {"meal": meal, "options": list(response)[index]}) # throws list index out range in tests /log/views/api.py def send_data(request, option): match option: case "ingredients": data = Log.objects.first().recipe_ingredients case "areas": data = Log.objects.first().recipe_area case "categories": data = Log.objects.first().recipe_categories case "activities": data = Log.objects.first().activities response = JsonResponse(data, status=200, safe=False) return response planner/tests/test_meals_view.py from unittest import MagicMock, patch @patch("planner.views.meals.requests") def test_fetch_options(self, mock_requests): mock_response = MagicMock() mock_response.status_code = 200 mock_response.json_data = [{"id": "357", "strIngredient": "Orange"}] mock_requests.get.return_value = mock_response self.assertContains( fetch_options("request", "breakfast", "ingredients"), status_code=200 ) Can anyone tell me what I'm … -
My Django website (hosted on EC2) is unable to connect with my newly purchased domain (Namecheap) via Rout53 DNS
I have a basic Django website hosted on EC2. It is accessabile over the internet when I use the ipaddress. But I want to use my newly purchased domain example.net (purchased from Namecheap). I configured Rout53 for DNS services. When I try to access my website using example.net it doesn't do anything and gives below error on browser: "This site can’t be reached example.net refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED" When I checked the logs on my EC2 server, it does not show any log if I hit example.net on browser but it shows logs when I hit "ip address". I performed all below checks and all is working fine as expected: DNS Records: Verify DNS records in Route 53. - I checked both A and CNAME record and it is correct Security Groups: Confirm security group rules allow HTTP and HTTPS traffic. - Both HTTP and HTTPS inbound rules are open for all. Verify ALLOWED_HOSTS in Django - This is how my ALLOWED_HOSTS looks like in my Django settings.py ['my EC2 elastic ip', 'example.net'] Firewall Settings: Confirm ufw is inactive or appropriately configured. - I don't have any firewall configured Domain … -
RelatedObjectDoesNotExist when trying to count number of objects in a Query Set
I know that this error is not unique to me. I have come across many posts asking what the error is and how to fix it. One of the answers I saw was to use hasattr on the returned objects in a for loop before you try to get the attribute of the object. The problem is, is that I actually want to count() on the QuerySet. I saw some other post use some Django model aggregate function inside of the query, but I don't think that is appropriate or necessary here. The query should be literally as easy as: font_count = Fonts.objects.filter(origin=location, font_name=font_name).count() but it says: my_app.models.Fonts.origin.RelatedObjectDoesNotExist: Fonts has no origin. Seems straight forward enough - I'll just open the interactive django shell and make sure that I can't get the origin of the Fonts already loaded into the DB... Well, what do you know?! I can access every origin of every font that I have loaded! What is this garbage?! I am on Django version "4.1.dev20211216191317" and python 3.9. origin is a foreign key and font_name is a text field. Thank you :) -
How do I stop field deleting when updating in Django?
I have a form update page. I had originally just been using date fields, but was asked by a user to include a date picker, so I moved to the code below. Now each time I update a date field (say payment 3 date), it updates ok, but it also deletes the other date fields. Any ideas as to why? I'm new to the DateInput() widgets. In views.py: def ParticipantPayments(request, pk): page_heading = "Update Participant's Payments" order = Order.objects.get(pk=pk) payment = ParticipantPayment.objects.get(customer=order.customer) customer = int(order.customer.id) firstname = payment.customer.first_name lastname = payment.customer.last_name form = UpdatePaymentForm(instance=payment) if request.method == 'POST': form = UpdatePaymentForm(request.POST, request.FILES, instance=payment) if form.is_valid(): form.save() messages.info(request, 'Your Form has been successfully submitted. ') return redirect('finance_participants') context = {'form':form,'customer':customer,'page_heading': page_heading, 'order':order, 'firstname':firstname, 'lastname':lastname} return render(request, 'accounts/part_payments.html', context) In models.py file: class ParticipantPayment(models.Model): #other code not relevant customer = models.ForeignKey(Customer, on_delete= models.CASCADE, null = True) fee = models.IntegerField(verbose_name = "Registration Fee", blank=False, default = 750) currency = models.CharField(verbose_name = "Currency", max_length=10, null=True, choices=MONEY,default='GBP') crowd_fund = models.DecimalField(verbose_name = "Crowd Fund Amount", max_digits=5,decimal_places=2, default = 0) ir_discount = models.DecimalField(verbose_name = "Euro Discount Amount", max_digits=5,decimal_places=2, default = 0) bursary = models.DecimalField(verbose_name = "Bursary Amount", max_digits=5,decimal_places=2, default = 0) payment_1_amount = models.DecimalField(max_digits=5, decimal_places=2, default = … -
AWS AppRunner timeout in a Docker image using Django / Gunicorn
I need help with deploy of Docker image (from ECR) where I use Django and Gunicorn. Gunicorn always leaves a "Critical - Timeout" log and apparently the code is never executed. I have already validated that the network has no problems regarding outgoing and incoming connections (use a Netcat image). My Dockerfile has the following: # Use the official Python image # https://hub.docker.com/_/python FROM python:3.7-slim # Needed to capture stderr output # https://github.com/bottlepy/bottle/issues/1130#issuecomment-478096704 # https://stackoverflow.com/a/59812588/109102 ENV PYTHONUNBUFFERED=1 # Set the working directory in the container WORKDIR /app # Intall system level dependencies RUN apt-get update && apt-get install -y \ git \ g++ \ gcc \ gettext \ libxmlsec1-dev \ libxmlsec1-openssl \ && apt-get clean \ && rm -rf /var/lib/apt/lists/\* # Copy the dependencies file to the working directory COPY requirements.txt . # Install dependencies RUN pip install --no-cache-dir -r requirements.txt # Copy the content of the local src directory to the working directory COPY . . # Expose port 8000 to the outside world EXPOSE 8000 CMD ["gunicorn", "MyProject.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "3", "--timeout", "120", "--log-level", "debug"] The health check is successful when configured as TCP but when I configure it as HTTP it fails because it returns timeout. … -
Use of CSRF_COOKIE_MASKED setting while upgrading django version to 4.1?
I am upgrading django version from 4.0 to 4.1, and in the release notes it says: CsrfViewMiddleware no longer masks the CSRF cookie like it does the CSRF token in the DOM. And it gives a setting as well called CSRF_COOKIE_MASKED for transition: The new CSRF_COOKIE_MASKED transitional setting allows specifying whether to mask the CSRF cookie. My question is how to decide whether to use this CSRF_COOKIE_MASKED setting or not while upgrading to 4.1? Also, what kind of testing can I do to verify such changes? -
Trying to deploy Django API to Azure Web app
Currently trying to deploy my Django backend on to Azure. The project runs locally no problem. It also builds and deploys fine on Azure but when I visit the default domain I get a 404 not found. At first I though the issue to be around the settings module as I have 2 depending on local or if its run on Azure like is shown in this Azure tutorial with the code here in the settings.py and production.py files but it seems to be working. I have tried different setups in the production.py and including adding all the modules there but it has no effect. The logs on Azure don't return any errors only a 404 error when I try to access the site. Could the issue have something to do with how I set up the URLS? The api Url look like this from django.urls import path # from .views import * from . import views urlpatterns = [ path("posts/", views.PostsListCreate.as_view(), name="post-view-create"), path("replies/", views.RepliesListCreate.as_view(), name="reply-view-create") ] While the project urls look like this below from django.urls import path, include from django.contrib import admin urlpatterns = [ path('', include("api.urls")), path('admin/', admin.site.urls), ] Here are my views as well from rest_framework … -
How to do a commit from digitalOcean periodically for saving data during the deployment into my django project
I have deploy a django project on digital ocean, the project mainly save documents like xlsx and csv, but while the web app is deploy users send documents to the platform, my question is how could I keep those documents saved aside of downloading one by one from the the admin panel of Django, or how could be the approach for dealing with that? I was thinking in creating a template for downloading all the data with one click, and then do a commit to the repository with that data that I downloaded previously, and digital ocean would take all the repository and make a redeploy, but the main dificulty woulb be that If I do that, I would need to do that manually -
Django - concatenate all the groups for each post
I have 2 model in my Django app: models.py: class Post(models.Model): id = models.CharField(verbose_name="Post ID", max_length=1200, primary_key=True) post_name = models.CharField( verbose_name="Post Name", max_length=1000, blank=True, null=True, ) post_description = models.TextField( verbose_name="Post Description", max_length=600, null=True, blank=True, ) platform = models.CharField( verbose_name="Platform", max_length=25, null=True, blank=True, ) type_dropdown = ( ("Carousel ads", "Carousel ads"), ("Image ads", "Image ads"), ("Video ads", "Video ads"), ("Lead ads", "Lead ads"), ("Follower ads", "Follower ads"), ) type = models.CharField( verbose_name="Type", max_length=15, blank=True, null=True, choices=type_dropdown, default="Type 1", ) link = models.URLField( verbose_name="Link", max_length=4000, blank=True, null=True, ) created_at = models.DateTimeField(default=now, null=True, blank=True) insert_date = models.DateTimeField(null=True, blank=True) user_last_update = models.ForeignKey( User, on_delete=models.PROTECT, null=True, blank=True, ) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return f"{self.post_name}" class Group(models.Model): group_name = models.CharField( verbose_name="Group Name", max_length=150, blank=True, null=True, ) post = models.ManyToManyField( Post, related_name="combo_post", ) created_at = models.DateTimeField(default=now, null=True, blank=True) insert_date = models.DateTimeField(null=True, blank=True) user_last_update = models.ForeignKey( User, related_name="combo_user", on_delete=models.PROTECT, null=True, blank=True, ) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return f"{self.group_name}" I use in CBV (Django Class-Based Views) i i want to get a query set of all the posts with another column that concatenate all the groups for each post. How can i do that? I tried this one but didn't work: from django_mysql.models … -
How to Upload, Edit, and Merge Word Documents in a Django Project?
In my Django project, I need to upload different Word documents for various tests, edit these documents to include the test data, and eventually combine them into a single document. How can I achieve this? I want to know if it's possible to achieve this in Django without creating a form. If yes, then how? I have already implemented this by creating a form, but now the process of handling 100 tests feels redundant and time-consuming -
request data not able to access with this code in wrapper function how can i python3 django decorator
not able to access request data in deorator how can i do this ? in my wrapper function def my_decorator(view_func): def wrapper(request, *args, **kwargs): print('-start-') print(request.data) print(args) print(kwargs) print('-now-') response = view_func(request, *args, **kwargs) return response return wrapper class HandymanCompleteProfileIos(APIView): @my_decorator def post(self, request, format = None): return JsonResponse({"A":"a"}) -
django cannot show user count when i called it
i'm new to django and i'm stuck here, when i want to show my total user excluding is_staff and is_superuser it cannot show what i wanted. Here's the code : Views.py def dashboard_view(request): # Menghitung jumlah user yang bukan staff dan bukan superuser user_count = CustomUser.objects.filter(is_staff=False, is_superuser=False).count() return render(request, 'dashboardowner/index.html', {'user_count': user_count}) Urls.py : path('dashboardowner/index/', views.dashboard_view, name='dashboard_view'), index.html (this file is inside dashboardowner folder, so here is the structure (mysalon->templates->dashboardowner->index.html)) <!-- Sale & Revenue Start --> <div class="container-fluid pt-4 px-4"> <div class="row g-4"> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-line fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Total Bookingan</p> <h6 class="mb-0">$1234</h6> </div> </div> </div> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-bar fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Estimasi Pendapatan</p> <h6 class="mb-0">$1234</h6> </div> </div> </div> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-area fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Jumlah Staff</p> <h6 class="mb-0">$1234</h6> </div> </div> </div> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-pie fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Jumlah User</p> <h6 class="mb-0">{{ user_count }}</h6> </div> </div> </div> </div> </div> <!-- Sale & Revenue End --> What i expected is the number of … -
Django channels error:- Could not connect to ws://192.168.1.21:8000/ws/sc/,
IMO I think it is unable to find the route /ws/sc route but I dont understand why as I have linked it properly. The error is give when I try to establish a connection using postman Following is the postman error:- Could not connect to ws://192.168.1.21:8000/ws/sc/ 12:30:20 Error: Unexpected server response: 404 Handshake Details Request URL: http://192.168.1.21:8000/ws/sc/ Request Method: GET Status Code: 404 Not Found Consumer class :- from channels.consumer import AsyncConsumer, SyncConsumer class MySyncConsumer(SyncConsumer): def websocket_connect(self, event): print("Websocket Connected", event) self.send({ 'type': 'websocket.accept' }) def websocket_receive(self, event): print("Message recieved", event) def websocket_disconnect(self, event): print("Websocket Disconnected", event) Routing class from django.urls import path, re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/sc/$', consumers.MySyncConsumer.as_asgi()), ] Asgi class import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import core.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gs3.settings') application = ProtocolTypeRouter( { "httpa": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( core.routing.websocket_urlpatterns ) ), } ) Settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*3c_890(%*-no1e64qvxtq^1su(8-pyb5t46p-kzpqu=1173%i' # SECURITY WARNING: don't run with debug … -
How to Serve media files on render.com for Django app deployed?
`Below is following render.com documentation for serving static and media when deploying Django webapp. Everything works, except when you upload a profile picture. Below, setting.py, build.sh and render.yaml code. It was deployed via blueprint instance with PostgreSQL. Also useing PGAdmin 4 GUI If you spot an issue, great. If not I have spent A week on my Linux/Ubuntu machine on my wondows laptop trying to get Nginx to server the media files. https://djangocareershifterswebsite.onrender.com (with sqlite 3 db) https://careershiftforum.onrender.com (with postgresql db) setting.py import os import dj_database_url from django.core.management.utils import get_random_secret_key # Generate or retrieve SECRET_KEY from environment variables SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', default=get_random_secret_key()) # Define BASE_DIR to point to the root directory of your Django project BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = os.getenv("DEBUG", "False").lower() == "true" ALLOWED_HOSTS = ['careershiftforum.onrender.com', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'rest_framework', 'corsheaders', ] AUTH_USER_MODEL = 'base.User' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'careershiftforum.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'careershiftforum.wsgi.application' # Use dj_database_url to parse the DATABASE_URL environment variable DATABASE_URL = os.getenv('DATABASE_URL') DATABASES = … -
FilteredRelation with OuterRef not working after updating to Django 5
After updating to Django 5, I have the same problem described in this post: How to use FilteredRelation with OuterRef? My queryset looks as follows: ModelA.objects.annotate( model_b_objects_count=SubqueryCount( ModelB.objects.filter( model_a_id=OuterRef('id') ).annotate( outer_user_id=OuterRef('user_id'), # user_id within ModelA model_c_relation=FilteredRelation('model_c_objects', condition=Q(model_c_objects__user_id=F('outer_user_id') ) ) ) While using Django 4.1, it was working fine, since trying to update, I get the error ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Anyone know how to fix this or is it sth that Django has to fix? I tried the solution provided in the mentioned post, but still got the same error. -
Bonjour la team mon projet en django ne se lance pas voici le messages d'erreur que j'ai au niveau de mon terminal
(GestFibOpt) C:\Users\JOHAN MOLLO\Desktop\GestFibOpt>python manage.py runserver C:\Users\JOHAN MOLLO\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\Users\JOHAN MOLLO\Desktop\GestFibOpt\manage.py': [Errno 2] No such file or directory j'ai essayé de lancer le projet avec la commande python manage.py runserver -
DJANGO ForeingKey selection from the reference table depending on the user
Section -> Complexes -> Line -> Equipment -> Report I need to make sure that when adding a Report, only the equipment Section to which the user belongs and status=true is in the Equipment list. I just started learning Django. Tell me what you need to look at to solve this problem. `class Section(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) def __str__(self): return self.name class Complexes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) section = models.ForeignKey(Section, on_delete=models.SET_NULL, ...) def __str__(self): return self.section.__str__()+" "+self.name class Line(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) complexes = models.ForeignKey(Complexes, on_delete=models.SET_NULL, ...) def __str__(self): return self.complexes.__str__()+" "+self.name class Equipment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) line = models.ForeignKey(Line, on_delete=models.SET_NULL, ...) status = models.BooleanField(default=True, ...) ... def __str__(self): return self.name +" "+ self.explanation +" "+ self.line.__str__() class Report(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) equipment = models.ForeignKey(Equipment, on_delete=models.DO_NOTHING, ...) ...` -
Django stuck after running Docker command as subprocess
When I run this command: manim_command = f'sudo docker run --rm -v {base_dir}/manim/python_code_files:/mnt/code -v {base_dir}/media:/mnt/output manim-image manim -ql /mnt/code/user_code.py -o /mnt/output/{class_name}' using subprocess.run or subprocess.Popen or os.system, It successfully runs(create an image or video file), but it blocks the terminal and prevents the further rendering of the template. If the file is already present, it will successfully display it. But if the file is not present, it will render but not show. I have tried running the docker container in detached mode, but that just renders the template before creating the file. obviously we have to wait till the process is over: while True: if check_file_exists(class_name): break time.sleep(2) print('File created') so, it waits till the file is created, but when I add this block, it waits for the the file to be created, prints 'File created' and then gets stuck just before rendering the template. why doesn't it render? try: # Run the function run_manim_command(class_name) print('function completed') except Exception as e: result_message = f"Error executing shell command: {e}" #after POST request context = {'previous_code': previous_code, 'MEDIA_URL': settings.MEDIA_URL, 'class_name':class_name, 'placeholder': False, } return render(request, 'run.html',context) It even prints 'function completed' I have tried: using thread to run as an asynchronous process … -
Exception occurred in file 'chrome.py', line 64: 'NoneType' object has no attribute 'split'
I am using pyhtml2pdf for converting HTML to PDF which has a requirement of Chrome headless. When the server is run as python manage.py runserver there is no issue. But when the django is run as a service it throws and error regarding split with chrome.py : Exception occurred in file ‘/var/www/myProject/env/lib/python3.11/site-packages/webdriver_manager/drivers/chrome.py’, line 64: ‘NoneType’ object has no attribute ‘split’. -
Sending Checkbox Status via hx-vals to Django
How can I correctly send the status of a checkbox to Django using hx-vals? I attempted the following method: hx-vals='{ "solved": "document.querySelector("input[name="solved"]").checked", "comment": "document.querySelector("input[name="comment"]").checked", "no_solution": "document.querySelector("input[name="no_solution"]").checked", }' In the Django views, I expected to retrieve the values like this: filter_solved = request.GET.get("solved") == 'true' However, I couldn't make this work. How can I fix this? Ty!!! -
Problem with Django class-based LogoutView
Logout Page Not Working ***Here is my user urls.py code *** from django.urls import path from users_app import views from django.contrib.auth import views as auth_views urlpatterns = [ path('register/', views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout'), ] -
Hello! I have a problem. When deleting a comment, the error Post matching query does not exist appears
I have a problem. When deleting a comment, the error Post matching query does not exist appears. And I do not know what to do with it. Thank you in advance! Error: Does Not Exist at /news/post/6 Post matching query does not exist. Note! I use the django framework Here is the code: views.py: from django.shortcuts import render from django.urls import reverse_lazy from .forms import PostForm, CommentForm from .models import Post, Comment from django.views import View from django.views.generic.edit import UpdateView, DeleteView class PostListView(View): def get(self, request, *args, **kwargs): posts = Post.objects.all().order_by('-created_on') form = PostForm() context = { 'post_list': posts, 'form': form, } return render(request, 'news/post_list.html', context) def post(self, request, *args, **kwargs): posts = Post.objects.all().order_by('-created_on') form = PostForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() context = { 'post_list': posts, 'form': form, } return render(request, 'news/post_list.html', context) class PostDetailView(View): def get(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) form = CommentForm() comments = Comment.objects.filter(post=post).order_by('-created_on') context = { 'post': post, 'form': form, 'comments': comments, } return render(request, 'news/details_view.html', context) def post(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() comments = Comment.objects.filter(post=post).order_by('-created_on') context = { 'post': … -
How i can show gis_models map in django templates?
models.py: ADDRESS_WIDGETS = { # ... 'point': gis_forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}), } srid = 4326 class Address(UUIDMixin, models.Model): city = models.ForeignKey(...) street = models.CharField(...) house_number = models.CharField(...) entrance_number = models.SmallIntegerField(...) floor = models.SmallIntegerField(...) flat_number = models.SmallIntegerField(...) point = gismodels.PointField( _('address geopoint'), srid=srid, ) tours = models.ManyToManyField(...) class Meta: # db_table, verbose_name, unique_together forms.py: class SettingsAddressForm(forms.ModelForm): def __init__(self, request: HttpRequest = None, *args, **kwargs) -> None: super(SettingsAddressForm, self).__init__(*args, **kwargs) if request and isinstance(request, HttpRequest): user = Account.objects.get(account=request.user.id) self.fields['city'].initial = user.agency.address.city self.fields['street'].initial = user.agency.address.street self.fields['house_number'].initial = user.agency.address.house_number self.fields['entrance_number'].initial = user.agency.address.entrance_number self.fields['floor'].initial = user.agency.address.floor self.fields['flat_number'].initial = user.agency.address.flat_number self.fields['point'].initial = user.agency.address.point class Meta: model = Address fields = ['city', 'street', 'house_number', 'entrance_number', 'floor', 'flat_number', 'point'] widgets = ADDRESS_WIDGETS views.py: def settings(request: HttpRequest) -> HttpResponse: request_user = request.user user = Account.objects.get(account=request_user.id) address_form = SettingsAddressForm(request) # ... return render( request, 'pages/settings.html', { 'request_user': request_user, 'user': user, 'address_form': address_form, 'style_files': [ 'css/header.css', 'css/body.css', 'css/tours.css', 'css/profile.css', ], }, ) pages/settings.html: {% extends 'base.html' %} {% load static %} {% block content %} <section class="home"> <div class="container"> {% if user.account.is_active %} <div class="left"> <!-- ... --> {% if user.agency %} <div class="agency_info"> <h3>Турагенство</h3> <form method="post"> {% csrf_token %} {{ agency_form.as_p }} <!-- ↓↓↓ here ↓↓↓ --> {{ address_form.as_p }} …