Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unique constraint violation on auth_user_pkey in Wagtail
I created a user import view (with Django's User model) for a new Wagtail app, which works well. I did a few tests, and ended up with IDs for my test users in the range of 140-150 on my development machine. Afterwards, I transferred the DB to a test machine. When I tried to create a new user via the Wagtail admin interface on the test machine, a unique constraint violation for auth_user_pkey was returned. But the offending new ID was close to the highest existing ID, so after three more tries, I arrived at an unused ID and was able to create the new account. What is going on here? Why does Wagtail try to (re-)use existing IDs, and how can I prevent the issue? -
I am new to python and django, therefore, having encountered this error, I do not know how to solve it TemplateDoesNotExist at /users/login/
settings: enter image description here urls.py - learning_log: enter image description here urls.py - users: enter image description here login.html: enter image description here The way to login.html: enter image description here According to the book, it should look something like this enter image description here But it throws such an error enter image description here -
In django DRF using JWT, why does postman properly block access to some views but they are available from my Angular front-end without authentication?
I’m trying to restrict access to some views of my API using Django Rest Framework and simpleJWT https://django-rest-framework-simplejwt.readthedocs.io/ The issue I’m facing is that postman correctly blocks access to my views when I do not provide a valid JWT to my API but my Angular front-end does not and gives access to all the views of my DRF API. { "detail": "Authentication credentials were not provided." } Here is a beginning of a view with from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.authentication import JWTAuthentication from ..serializer import General_emission_group_serializer_years from django.db import connection class EmmissionGroup(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): Here is my settings.py from pathlib import Path import os import environ from django.contrib.auth import get_user_model from django.contrib.staticfiles import handlers class CORSStaticFilesHandler(handlers.StaticFilesHandler): def serve(self, request): response = super().serve(request) response['Access-Control-Allow-Origin'] = '*' return response handlers.StaticFilesHandler = CORSStaticFilesHandler # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() environ.Env.read_env(os.path.join(BASE_DIR, ".env")) SECRET_KEY = env("SECRET_KEY") DEBUG = True ALLOWED_HOSTS = ["127.0.0.1"] INSTALLED_APPS = [ "corsheaders", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', #"rest_framework.authtoken", "django_filters", "camping", "admin_honeypot", "axes", ] AUTHENTICATION_BACKENDS = [ 'rest_framework.authentication.TokenAuthentication', # Token-based authentication for API 'django.contrib.auth.backends.ModelBackend', # Default … -
The response content must be rendered before it can be accessed
I am trying to make the custom response format for that i have done below mentioned code middleware from django.utils.deprecation import MiddlewareMixin from rest_framework.response import Response from rest_framework.exceptions import APIException class CustomResponseMiddleware(MiddlewareMixin): def process_response(self, request, response): from adminPanel.serializers import MyCustomException if not isinstance(response, Response): return response response.render() if 'data' in response.data: return response response_data = { 'status': response.status_code, 'message': 'Success', 'error': False, 'data': response.data, 'error_message': None, } if isinstance(response, MyCustomException): error_message = response.detail.get('error_message', None) response_data = { 'status': response.status_code, 'message': 'Error', 'error': True, 'data': None, 'error_message': error_message, } return Response(response_data, status=response.status_code) in setting.py 'adminPanel.middleware.custom_response.CustomResponseMiddleware', serializers.py class LoginSerializer(serializers.Serializer): username_or_email = serializers.CharField() password = serializers.CharField(write_only=True) access_token = serializers.CharField(read_only=True) refresh_token = serializers.CharField(read_only=True) user_type = serializers.CharField(read_only=True) request_source = serializers.CharField(read_only=True, default='mobile') def validate(self, data): username_or_email = data.get('username_or_email') password = data.get('password') if not username_or_email or not password: raise MyCustomException(detail={"error_message": "Must include 'username_or_email' and 'password'."}, status_code=status.HTTP_400_BAD_REQUEST) user = authenticate( request=self.context.get('request'), username=username_or_email, password=password ) if user is None: raise MyCustomException(detail={"error_message": "Invalid username/email or password."}, status_code=status.HTTP_400_BAD_REQUEST) if not user.is_active: raise MyCustomException(detail={"error_message": "User is inactive."}, status_code=status.HTTP_400_BAD_REQUEST) if not user.email_verified: email_otp = ''.join([str(randint(0, 9)) for _ in range(6)]) user.email_otp = email_otp user.save() send_registration_email.delay( 'Welcome to Your Website', 'email.html', {'code': email_otp}, settings.EMAIL_HOST_USER, [user.email], ) raise MyCustomException(detail={"error_message": "Please verify your email first"}, status_code=status.HTTP_400_BAD_REQUEST) … -
How can I use email with django-allauth without mail server?
I'd like to configure django-allauth in such a way that users have to register with email and password but the Django project does not have to provide a mail server and no emails are transmitted (no registration confirmation, no password reset link, etc.). How do I have to configure django-allauth. -
Value is not copying properly in input tag
I am trying to add or edit the form in django by creating customized form using html and css. Now it works fine for add product form but when i trying edit one of field in the form,image url does not passing to input tag and when i submit the form it says image tag is empty. How to recitfy it? ` Cake image {% if Product.product_img %} <img src="{{ Product.product_img }}" alt="Product Image"> {% endif %} <input type="file" name="product_img" accept="image/*" id="product_img"> </div>` -
Is it possible to change the display of a Binaryfield model attribute in the Django admin panel, based on the value of another attribute?
I'm working on a project where I have a model which stores some BinaryField in the database. class Entry(models.Model): ... params = models.JSONField() body = models.BinaryField() ... params will have a tag with the type of the body item. For example it might be html, and the body will be the html text or an image, and the body could be an image etc. Right now, the details of Django admin show something like this: Body: <memory at 0x7355581f0e80> Is it possible to change how django admin displays this info, based on the info I have from the other attributes? Thanks for your time! -
How to change structure of articles in django-wiki?
I am new to django-wiki and want to change the structure of article form. As default has Title, contents and summary. I want to add 2 more fields for "main" and "history". How can do that? Thanks in advance. I tried looking it up on the internet but sources are scarce. -
Render request for html page changes url link to #
I am using Django to render html pages. When it renders, it works fine but it changes link to #. Let me explain views.py def index(request): return render(request, 'index.html') urls.py router = routers.DefaultRouter() router.register(r'users', UserViewSet) .... urlpatterns = [ path('homepage/', views.index, name='homepage'), path('', include(router.urls)), ] When I want to view the html page I go to link named: http://127.0.0.1:8000/api/homepage/ But when it enters the page browser link changes to : http://127.0.0.1:8000/#/ How can I solve this issue? -
unable to decode encrypted bytes data stored in db
I have written 2 functions in python, one for encrypting data and other for decrypting data which are as follows. from app.settings import DATA_KEY import logging from cryptography.hazmat.primitives.ciphers.aead import AESSIV import base64 cipher_suite = AESSIV(DATA_KEY) error_logger = logging.getLogger("error_logger") def encrypt_field(input_text): try: if isinstance(input_text, str): input_text = input_text.encode() enc_text = cipher_suite.encrypt(input_text, associated_data = None) print(f"enc_text is {enc_text}") enc_text_base_64 = base64.b64encode(enc_text) print(f"encrypted_text is {enc_text_base_64}") return enc_text_base_64 except Exception as e: error_logger.error(f"exception in encrypt field {str(e)} on field {input_text}") return input_text def decrypt_field(input_text): try: print(f"input in decrypt field is {input_text} its type is {type(input_text)}") enc_text = base64.b64decode(input_text) print(f"enc text is {enc_text}") decrypted_field = cipher_suite.decrypt(enc_text, associated_data = None) print(f"decrypted_field is {decrypted_field}") return decrypted_field.decode('utf-8') except Exception as e: print(e) error_logger.error(f"exception in decrypt_field {e} on field {input_text}") return input_text I am able to encrypt and store the data in db, however upon reading the data from db and trying to decrypt it, I am getting a utf-8 bytestring instead of original plaintext string back. What am I doing wrong here? My Django version is 5.0, Python version is 3.10.11 and Database is PostgreSQ I have tried storing the data in BinaryField as well TextField of Django models, but to no avail the result is same. I … -
Internal Sever Error 500 and unauthorised 401 error
I am working with Django and NextJS, i keep getting 2 error whenever i try to login: From my AuthContext.js file "500 (Internal Server Error)" From my UseApi.js file "401 (Unauthorised)" whenever i try to login it throws this two errors i have added a authorisation header but still getting the same error Here is how each file are structured: AuthContext.js import { createContext, useState, useEffect } from "react"; import useSWR from "swr"; import { httpWeb } from "../services/http"; import { usePostHog } from "posthog-js/react"; export const AuthContext = createContext(); export default function AuthContextProvider (props) { const [token, setToken] = useState(null); useEffect(() => { // This code runs only on the client side const storedToken = localStorage.getItem('token'); console.log("Token for request:", storedToken); setToken(storedToken); }, []); const posthog = usePostHog() const [ isLoading, setLoading ] = useState(true) const [ isAuthenticated, setAuthenticated ] = useState(false) const [ user, setUser ] = useState(null) const { data: user_data, error: user_err, mutate: refreshUser } = useSWR('/api/auth/user', url => httpWeb.get(url, { headers: { 'Authorization': `Bearer ${token}` } }).then(res => res.data, { errorRetryCount: 0, refreshInterval: 0, shouldRetryOnError: false })) const signOut = () => { httpWeb.post('/api/auth/logout') .then(() => { setAuthenticated(false) setUser(null) setLoading(false) posthog.reset() }) .catch(err => {}) } … -
Connecting problem to another user's PostgreSQL database in Django
I have a question. I'm starting to work on a Django project. I received database credentials for a PostgreSQL database created by a colleague. How can I connect to this database? enter image description here Unfortunately, after starting the Django server, the error shown in the attached screenshot appears in the terminal. Please help. Thank you! -
Migrating to TZ aware datetime in Django, PostgreSQL timestamp
I use Django ORM to access PostgreSQl data. Database is relatively big ~100 tables, some with dozens of millions of records. I'm switching from Django 4.2 to Django 5.0, which has USE_TZ = True by default and I want to keep it that way, so after the migration - hopefully there won't be any naive datetimes in my system. I have models like: class MyExistingModel(BaseModel): name = models.CharField(max_length=100, unique=True, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) ...and what I'm witnessing for the most of my models is the following: In [6]: mem = MyExistingModel.objects.create(name="new record") In [7]: mem.date_created Out[7]: datetime.datetime(2024, 5, 23, 6, 15, 25, 885356, tzinfo=datetime.timezone.utc) In [8]: MyExistingModel.objects.get(name="new record").date_created Out[8]: datetime.datetime(2024, 5, 23, 1, 15, 25, 885356) Same record, same field - two different datetime formats: aware vs naive. Whenever those two are mixed I'm of course getting an error like: TypeError: can't compare offset-naive and offset-aware datetimes This is a big problem as I can hardly control every single place where DateTimeField is used. It seems that the reason behind this is the fact that date_created in my PostgreSQL, which was created by Django long time ago, is of timestamp without time zone. That's what I'm seeing with DB … -
Defining test methods in base class which should not be instanciated directly
I am trying to create test cases which only differ by which user is logged in. Therefore I figured defining the tests in a base class and creating sub classes which log in the user during setUp() would be the way to go. However I cannot find an elegant solution to excluding the tests in the base class from running. from django.contrib.auth.models import User from django.test import TestCase class A(TestCase): @classmethod def setUpTestData(cls): cls.user_a = User.objects.create_user("a", "", "a") cls.user_b = User.objects.create_user("b", "", "b") def setUp(self): # global set up stuff here ... def test_1(self): self.assertEqual(self.user_a.username, "a") class SubA(A): def setUp(self): super().setUp() self.client.force_login(self.user_a) class SubB(A): def setUp(self): super().setUp() self.client.force_login(self.user_b) In the code above I'd want only the inherited tests in the classes SubA and SubB to run, but not the one in A. I have tried: extracting the base class to another module, which is not included by the default search pattern. => still runs the tests since the base class must be imported to inherit from it defining a load_tests(...) function in the package which excludes the base class => same result as above raising unittest.SkipTest in the base class setUp() and catching it in the sub classes' setUp => … -
Cache response from a request in python
I'm writing some backend scripts in python that have to be coupled with a web interface that uses django. The web application allows to view layers that comes from different web services. As part of my tasks I developed a tool that request elevation data from a geoserver (a WCS service) and then, based on the a previous line drew by a user in the front end, is able to generate a cross section of the underlying data. So, in short: when a user draws a line over a layer and then clicks draw-profile, my function request the data, intersects the line when the associated raster/layer and returns a figure to the front-end. The problem with that approach is that each time the user clicks draw-profile, the request is made again, which takes some time. When the request is made, the data is stored in a DTM object (class that I made) in a self.raster property. A simplified version of the function that requests the data is shown below. def get_dtm_from_wcs100( self, raster_source: str = "YY", layer: str = "XX", format: str = "image/tiff", version: str = "1.0.0", resx: int = 1, resy: int = 1, ) -> None: """ … -
Telegram chat bot using python-telegram-bot | Messages between clients and operators are being messed
We have 3 operators and I want them to be busy if they entered to chat with someone. When chat is ended with client, operator will be free for other clients and can chat. I accidentally removed the part of code where operator after entering to chat will become busy (is_available=False) and after ending chat becomes available (is_available=True). Stack: Django, python-telegram-bot models.py from django.db import models class CustomUser(models.Model): tg_id = models.IntegerField() tg_first_name = models.CharField(max_length=500, blank=True, null=True) tg_username = models.CharField(max_length=500, blank=True, null=True) name = models.CharField(max_length=500, blank=True, null=True) choosen_lang = models.CharField(max_length=50, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) status = models.CharField(max_length=500, blank=True, null=True) is_operator = models.BooleanField(default=False, blank=True, null=True) is_supervisor = models.BooleanField(default=False, blank=True, null=True) is_available = models.BooleanField(default=True, blank=True, null=True) def __str__(self): return self.tg_first_name class Chat(models.Model): is_closed = models.BooleanField(default=False) client = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='client_of_chat', blank=True, null=True) operator = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='operator_of_chat', blank=True, null=True) created = models.DateTimeField(auto_now_add=True) class Appeal(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) body = models.TextField(blank=True, null=True) def __str__(self): return self.body buttons.py from main.models import * lang_btn = [ ["O'zbek"], ["Русский"], ] main_page_btn_uz = [ ["Savol"], ["Shikoyat"], ] main_page_btn_ru = [ ["Вопрос"], ["Жалоба"], ] chat_btn_uz = [ ['Onlayn opertor'], ] chat_btn_ru = [ ['Онлайн-оператор'], ] main_btn_operator = [ ["Открытие чаты"], ["Закрытие чаты"], ] … -
TypeError: user.models.CustomUser() got multiple values for keyword argument 'email'
So, I'm trying to create a custom user model in Django for a personal project, but the terminal is throwing this error while trying to create a super user via python3 manage.py createsuperuser Traceback (most recent call last): File "/home/Henkan/main_store/manage.py", line 22, in <module> main() File "/home/Henkan/main_store/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 87, in execute return super().execute(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 232, in handle self.UserModel._default_manager.db_manager(database).create_superuser( File "/home/Henkan/main_store/user/managers.py", line 18, in create_superuser return self.create_user(email, password = None, **extra_fields) File "/home/Henkan/main_store/user/managers.py", line 9, in create_user user = self.model(email=email, **extra_fields) TypeError: user.models.CustomUser() got multiple values for keyword argument 'email' Here's the managers.py code; from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password = None, **extra_fields): if not email: raise ValueError('Email is required') extra_fields['email'] = self.normalize_email('email') user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self.db) def create_superuser(self, email, password = None, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) return self.create_user(email, password = None, **extra_fields) -
No static files over Nginx + Django
I know there are many such questions. But I've tried a lot of what I've found and nothing helps. I have a combination of Django + uWSGI + Nginx + PostgreSQL. Static file was collected by python manage.py collectstatic in movies_admin/static directory. I'm logging into Django admin at a local address via nginx 127.0.0.1/admin. The page itself is loaded, but only the text, fields and the like. No graphics - that my problem. My docker-compose file: version: '3' services: django: restart: always build: movies_admin/. env_file: - .env ports: - "8000:8000" container_name: work_django depends_on: - postgres postgres: restart: always env_file: - .env image: 'postgres:${PG_VER}' environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} container_name: work_database ports: - "5432:5432" volumes: - ${DB_VOLUME_CATALOG_PATH}:/var/lib/postgresql/data/ nginx: image: 'nginx:${NGINX_VER}' volumes: - ${NGINX_CONF_FILE}:/etc/nginx/nginx.conf:ro - ${NGINX_CONFD_CATALOG}:/etc/nginx/conf.d:ro - ${STATIC_PATH}:/var/www/static/:ro container_name: work_nginx depends_on: - django ports: - "80:80" I checked. The static directory is mounted in the '/var/www/static/' directory of the nginx container. My site.conf: server { listen 80 default_server; listen [::]:80 default_server; server_name _; location /static/ { alias /var/www/static/; } location @backend { proxy_pass http://django:8000; } location ~* \.(?:jpg|jpeg|gif|png|ico|css|js)$ { log_not_found off; expires 90d; } location / { try_files $uri @backend; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; … -
can't find the page URL
I got the same error while writing code. enter image description here started making this project using a video tutorial on YouTube I think the problem is in the Url files, but I can’t find this problem myself. Essentially the problem is that when I go to the site and press a certain button, this error appears and does not find this page, why? my urls.py there may be a mistake here, but that's for sure from django.urls import path from . import views urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('', views.home, name='home'), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>',views.userProfile,name="user-profile"), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>/', views.updateRoom, name="update-room"), path('delete-room/<str:pk>/', views.deleteRoom, name="delete-room"), path('delete-message/<str:pk>/', views.deleteMessage, name="delete-message"), ] my views.py from django.shortcuts import render, redirect from django.db.models import Q from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth import authenticate,login,logout from .models import Room, Topic, Message from django.contrib.auth.forms import UserCreationForm from .forms import RoomForm #rooms = [ # {'id': 1, 'name': 'Lets learn python!' }, # {'id': 2, 'name': 'Design with me' }, # {'id': 3, 'name': 'Frontend developers' }, #] def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == … -
Best approach to build a filterable table with Django
I have created a Template where you have a HTML-table and a iframe that's rendering pdf's that a user has previously uploaded: The goal is that a user can match the table entries to a pdf / multiple pdf's. This part is done. But now I would like to know what's the best approach to filter my table data. I have created the table this way: {% extends "website/base.html" %} {% block content %} {% load static %} {% load evidence_extras %} <script src="{% static 'evidence/matching_final.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'evidence/css/style.css' %}"> <script src='https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.8/axios.js'></script> <div class="container"> {% csrf_token %} <div class="row"> <div class="col-8"> <div class="row"> <div class="col-12"> <table class="table"> <thead class="table-dark"> <td> id </td> ....... </thead> <tbody> {% for piece in transactions %} <tr onclick="handleRowClick(this, {{piece.id}})"> <td> {{ piece.id }} </td> ...... </tr> {% endfor %} </tbody> </table> </div> </div> <div class="row"> <div class="col-12"> <button onclick="handleMatch(this)" class="btn btn-primary" style="width: 100%;">Match</button> </div> </div> </div> <div class="col-4 overflow-scroll" style="height: 60em;"> {% for evidence in evidences %} <div class="row"> <div class="col-12"> <div class="card" id="evidence_{{evidence.id}}"> <div class="card-header">{{ evidence.name}}</div> <div class="card-body"> <iframe src="/evidence/pdf/{{evidence.id}}" id="pdf_frame" width="100%" height="400"></iframe> <ul> <li maxlength="20"> file: {{evidence.file}} </li> <li maxlength="20"> hash: {{evidence.hash}} </li> </ul> <div class="row"> <div class="col-6"> <button … -
Django model.objects.filter SQL searching more columns than given
So I am trying to use this def get_queryset(self, *args, **kwargs): return OrderItem.objects.filter(order_id=self.kwargs['pk']) To search my OrderItem by object and return only the ones linked to a specify order by an order_id. However using the Django debug_toolbar I can see what the sql query is doing and it is doing the following: SELECT "littlelemonAPI_orderitem"."id", "littlelemonAPI_orderitem"."order_id", "littlelemonAPI_orderitem"."menuitem_id", "littlelemonAPI_orderitem"."quantity" FROM "littlelemonAPI_orderitem" WHERE ("littlelemonAPI_orderitem"."order_id" = 2 AND "littlelemonAPI_orderitem"."id" = 2) LIMIT 21 In this case I passed 2 as the PK in my API endpoint but I don't understanding why it is searching by the id when I only want it to search by the order_id. These are my database tables: enter image description here enter image description here Also these are how these two models are defined: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) delivery_crew = models.ForeignKey(User,on_delete=models.SET_NULL,related_name='delivery_crew',null=True) status = models.BooleanField(db_index=True, default=0) total = models.DecimalField(max_digits=6,decimal_places=2) date = models.DateField(db_index=True,auto_now_add=True) def __str__(self): return f"{self.id}" class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADEAlso) menuitem = models.ForeignKey(MenuItem,on_delete=models.CASCADE) quantity = models.SmallIntegerField() class Meta: unique_together = ('order','menuitem') def __str__(self): return f"{self.order_id}"``` And these are the serializers I am and will be using but I am not sure how these would cause this issue: class OrderSerialzier(serializers.ModelSerializer): user = UserSerializer class Meta: model = … -
Python Reply To an email message
I have a Django app which we developed to manage our Hotel reservation inquiries and requests. We are receiving Emails directly from our django-mailbox modal. Now the problem I am facing is that when I receive an email, I want to reply to the same email message so that when the recipient opens that email they can see the previously sent or received message on the same page, like Gmail. How to do that here is my code: def reply_inquiry_email_to_hotel(request, reservation_pk): try: reservation = Reservation.objects.get(pk=reservation_pk) rooms = ReservationRoom.objects.filter(reservation=reservation) hotel = reservation.hotel email_server = CompanyEmailServer.objects.get(company=reservation.company) # Set email settings settings.EMAIL_HOST = email_server.email_server settings.EMAIL_PORT = email_server.email_port settings.EMAIL_HOST_USER = email_server.email_username settings.EMAIL_HOST_PASSWORD = email_server.email_password settings.EMAIL_USE_TLS = email_server.email_use_tls settings.EMAIL_USE_SSL = email_server.email_use_ssl settings.DEFAULT_FROM_EMAIL = "Reservations | " + reservation.company.name_en + " <" + email_server.email_username + ">" subject = f'New Reservation Request No: {reservation.reservation_no} For {hotel.name_en} From {reservation.guest_name} On {reservation.request_date}' html_message = render_to_string('email/message.html', {'reservation': reservation, 'message': request.POST['message']}) plain_message = strip_tags(html_message) to_email = [hotel.email] headers={ 'In-Reply-To': request.POST['in_reply_to'], 'References': request.POST['in_reply_to'] } email = EmailMultiAlternatives(subject, plain_message, settings.DEFAULT_FROM_EMAIL, to_email, headers=headers) email.attach_alternative(html_message, "text/html") email.send(fail_silently=False) mailbox = Mailbox.objects.get(pk=email_server.mailbox.pk) mailbox.record_outgoing_message(email.message()) messages.success(request, _('Email sent successfully')) return redirect(reverse('hotel_reservation_mailbox', args=[reservation.pk,])) except Exception as e: print(('Failed to send email: ') + str(e)) return redirect(reverse('hotel_reservation_mailbox', args=[reservation.pk,])) Send message as … -
Django CSRF_TRUSTED_ORIGINS and http/2
I suspect websites that use http/2 protocol are not sending the Host header in the requests, eg going to /admin/ This leads to Django complains about Origin checking failed - does not match any trusted origins) even though posting to the exact same domain. This error won't come up with websites that using http/1 protocol on Django 4.2 Apart from adding the actual domain to CSRF_TRUSTED_ORIGINS, is there anything else I can do? -
Summernote Widget not displaying on inheriting from UpdateView
urls.py path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), views.py: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = PostForNewsFeed fields = ['post','title','content', 'tags','visibility'] template_name = 'feed/create_post.html' widgets = { 'content': SummernoteWidget(), } def form_valid(self, form): if form.is_valid(): data = form.save(commit=False) data.user_name = self.request.user data.save() messages.success(self.request, f'Posted Successfully') return redirect('home2') def test_func(self): post = self.get_object() if self.request.user == post.user_name: return True return False @python_2_unicode_compatible class PostForNewsFeed(models.Model): post = models.CharField(max_length=50, choices=POSTTYPE_CHOICES, default='Just a Mesage') #fullname = models.CharField(max_length=50, blank=True, null=True, default=None) title = models.CharField(max_length=100, blank=False, null=False) content = models.TextField(default=None) Summernote Widget wont render on PostupdateView -
continues error on "Could not find 'Price' Did not find price on detail page" in django
im begginer in django , leanring through coursera , django for everyone course , while doing my assignment repeated error throwing contiusely while submitting this is error,and i checked everthing but its still throwing error but "price" is there in web here my view.py in django- from ads.models import Ad from ads.owner import OwnerListView, OwnerDetailView, OwnerCreateView, OwnerUpdateView, OwnerDeleteView class AdListView(OwnerListView): model = Ad class AdDetailView(OwnerDetailView): model = Ad class AdCreateView(OwnerCreateView): model = Ad fields = ['title', 'text', 'price'] class AdUpdateView(OwnerUpdateView): model = Ad fields = ['title', 'text', 'price'] class AdDeleteView(OwnerDeleteView): model = Ad and here is my ad_detail.html --- {% extends "base_menu.html" %} {% block title %}{{ settings.APP_NAME }}{% endblock %} {% load humanize %} <!-- https://docs.djangoproject.com/en/3.0/ref/contrib/humanize --> {% block content %} <span style="float: right;"> ({{ ad.updated_at|naturaltime }}) {% if ad.owner == user %} <a href="{% url 'ads:ad_update' ad.id %}"><i class="fa fa-pencil"></i></a> <a href="{% url 'ads:ad_delete' ad.id %}"><i class="fa fa-trash"></i></a> {% endif %} </span> <h1>{{ ad.title }}</h1> <p> {{ ad.text }} </p> <p> {{ ad.price }} </p> <p> <input type="submit" value="All Ads" class="btn btn-primary " onclick="window.location.href='{% url 'ads:all' %}';return false;"> </p> {% endblock %} im using pythonanywhere for django and assignment python manage.py check --ok python manage.py makemigrations --ok python …