Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to run the django server
i'm trying to laucn the django with the command python manage.py runserver but i got this error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is Fa is False. here is my settings project: DEBUG = True ALLOWED_HOSTS = [] i've tried all the solution proposed by others on the relative question with mine but the difference is that i've not change the settings variable Debug so their solution don't work for me. like to change the value of list settings variable ALLOWEG_HOSTS but it's not working for me. -
Django-Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
There some questions related to this but no answers are helped. I often come accross errors like that but cannot figure out what causes problems. My projects has been running fine but suddenly all of them which using postgresql are stopped, giving following error. Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/psycopg/connection.py", line 728, in connect raise ex.with_traceback(None) psycopg.OperationalError: connection is bad: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 74, in inner with self._recreate_cm(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/transaction.py", line 198, in __enter__ if not connection.get_autocommit(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 464, in get_autocommit self.ensure_connection() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/utils.py", … -
pathlib.py" is overriding the stdlib module "pathlib"
Creating a Django app in a condo virtual environment(djenv) created the html, updated views.py and urls.py when updating settings.py, getting a problem for this line of code from pathlib import Path "C:\test1\djenv\Lib\pathlib.py" is overriding the stdlib module "pathlib" when I renamed pathlib.py, Django doesn't work properly Is there a way override the stdlib pathlib and use the virtual environments pathlib.py or are there any other fixes for this problem -
Django join tables with two or more FK conditions
I want to join models B and C with two conditions, data_a and human in model_B, and data_a and autor in model_C, but how do I do it with Django ORM class user(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_A(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_B(models.Model): data_a = models.ForeignKey(model_A) human = models.ForeignKey(user) data_2 = models.IntegerField() class model_C(models.Model): data_a = models.ForeignKey(model_A) author = models.ForeignKey(user) data_1 = models.CharField(max_length=5) data_2 = models.IntegerField() additional conditions on join in django I've seen this place, but I don't know if it's applicable to my situation -
Django bulk_create() with inexistent ForeignKey
I have 2 models. For simplicity, I deleted all unnecessary fields. class User(models.Model): id = models.CharField(max_length=36, primary_key=True, null=False) age = models.IntegerFiels(default=-1) and class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Through the API, I receive information about devices and create a list with devices. devices = [] for device_data in data: devices.append( Device( user_id=device_data("user_id") ) ) Once I have the list of devices, I add it to the database. Device.objects.bulk_create(devices, ignore_conflicts=True) The problem is that if, when creating a Device, I specified a user_id that is not in the database, I will get a crash because I am trying to link with a non-existent id. Now to get around this I do the following: devices = [] users = [] for device_data in data: users.append( User( id=device_data("user_id", age = -1) ) ) devices.append( Device( user_id=device_data("user_id") ) ) Then, when saving: User.objects.bulk_create(users, ignore_conflicts=True) Device.objects.bulk_create(devices, ignore_conflicts=True) User.objects.filter(age=-1).delete() How can I make sure that when saving, if the specified user_id does not exist, this device is not added? Or add a device, while creating a User with this user_id, but with the rest of the fields by default, and then, at the end, I will delete all users, and with them all devices, where age … -
Django queryset not filtering correctly based on end_date and current_time
I'm encountering an issue with my Django project where I have a model Service with an end_date field. I want to filter services based on whether their end_date is in the future, but I'm facing unexpected behavior. model.py: from django.db import models from apps.user.models import CustomUser from apps.location.models import City from django.utils import timezone class Area(models.Model): name = models.CharField(max_length=70,unique=True) def __str__(self): return self.name class Type_of_housing(models.Model): name = models.CharField(max_length=100,unique=True) areas = models.ManyToManyField(Area,blank=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Subcategory(models.Model): name = models.CharField(max_length=100,unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Service(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) type_of_housing = models.ForeignKey(Type_of_housing, on_delete=models.CASCADE) area = models.ForeignKey(Area, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) location_address = models.CharField(max_length=100) city = models.ForeignKey(City,on_delete=models.CASCADE) is_visible = models.BooleanField(default=True) end_date = models.DateTimeField() def __str__(self): return self.title def save(self, *args, **kwargs): if not self.end_date: # Calculate the end date as 14 days from the current date and time self.end_date = timezone.now() + timezone.timedelta(days=14) super().save(*args, **kwargs) class ServiceImage(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) image = models.ImageField(upload_to='service_images/') def __str__(self): return f"Image for Service: {self.service.description}" and view.py: def service_list(request): current_time = timezone.now() print("Current Time:", current_time) services = Service.objects.all() for service … -
How to get python implemented in Django
I have already defined a function and now wanted to use it on my website and have already tried this <img src="{{ get_pop_img(0) }}" class="card-img-top" alt="jpg"> and my function is def get_pop_img(number): response = requests.get('https://api.jikan.moe/v4/top/manga?filter=bypopularity') img = response.json()['data'][number]['images']['jpg']['image_url'] return img but i only getting errors I also importet my python file in the views.py -
Why does the variable not change its value after admin action has been triggered?
I have two admin actions for the Feedback Model in the admin panel, approved and unapproved. The value for approved in the Feedback Model is default to False. When admin use the action to approve, it turns this value to True and unapproved will turn True to False. This works on the admin panel on the deployed site, however when I'm trying to do the test for the admin.py I ran into an error where the test_approve is passing, while the test_unapprove failed. When I try to debug the test_unapprove I set the approved value as True and then check the value of feedback.approve before the response and it came out as True, which is expected. Then I check again after the response and it still came out as True where it should come out as False. Please have a look if you have any clue why this is happening. If you need any more info please let me know! admin.py @admin.register(Feedback) class FeedbackAdmin(admin.ModelAdmin): list_display = ('username', 'body', 'lesson_id', 'created_on', 'approved') list_filter = ('approved', 'created_on') list_display_links = ('username',) search_fields = ['username', 'user_id', 'body'] actions = ['approved_feedback', 'unapproved_feedback'] def approved_feedback(self, request, queryset): queryset.update(approved=True) def unapproved_feedback(self, request, queryset): queryset.update(approved=False) test_admin.py class TestAdmin(TestCase): … -
Django data problem : new salons always with all users
Problem is that I want to create a new salon, so beginning with only the user who created it. But, when I consult my django database (with localhost:8000/admin/), I notice that every user (UserSalon) is present in every 'Salon'... However, when I print all the users of this salon in the terminal, I can see there is only this one. So wtf? I have this in my models.py: class UserSalon(models.Model): # etc. class Salon(models.Model): salon_users = models.ManyToManyField(UserSalon) # etc. and this is a part of code from my view.py: user_salon_id = request.session.get('user_salon_id') if request.method == 'POST': create_salon_form = CreateSalonForm(request.POST) try: user_salon = UserSalon.objects.get(id=user_salon_id) except UserSalon.DoesNotExist: user_salon = None if create_salon_form.is_valid(): created_id_salon = create_salon_form.cleaned_data['id_salon'] created_key_salon = create_salon_form.cleaned_data['key_salon'] new_salon = Salon.objects.create(id_salon=created_id_salon, key_salon=created_key_salon) new_salon.salon_users.clear() new_salon.salon_users.add(user_salon) new_salon.save() -
How to assign the result of a conditional to a variable in a Django template?
There are two django models, "Production" and "Season". Production has a foreign key to Season (i.e. in rails-speak Season has_many Productions, Production belongs_to Season). I have a detail view for Production, and the page sidebar has the list of all productions in the current season. {% for p in season.production_set.all %} <li class="nav-item"> <a class="nav-link d-flex align-items-center gap-2" href="{% url 'production_detail' season.id p.id %}"> {{p.name}} </a> </li> {% endfor %} {% endblock %} But I would like the nav item to be disabled for the current production being viewed. That means adding the 'disabled' class to a element, and setting the "aria-current" attribute as well. I can use if/else takes, but it ends up being quite verbose and also repetitive, given that I need this logic twice in the same html tag <a class="nav-link d-flex align-items-center gap-2 {% if p.id is not production.id %} active {% else %} disabled {% endif %}" aria-current="{% if p.id is production.id %}true{%else%}false{%endif%}" href="{% url 'production_detail' season.id p.id %}"> So I tried to assign a variable like {% with p.id is not production.id as current %} but no syntax I have tried allowed me to assign a boolean expression to a variable. Is there a … -
Cannot turn PIL.Image.Image to tensor using tochvision transforms.ToTensor in Django
I'm doing a AI service using django app served by uWSGI in docker which setup from my senior. And it's always 504 time-out when reach img_tensor = transforms.ToTensor()(img_resized) This is views.py from django.apps import apps from rest_framework import status from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response import os, shutil import gc import uuid from PIL import Image from multiprocessing import Pool import torch from fairseq import utils from torch.utils.data import DataLoader from torchvision import transforms from HTR.serializers import HTRSerializer from HTR.Backend.main import generate_text class HTRViewSet(APIView): permission_classes = [permissions.AllowAny] config = apps.get_app_config('HTR') def post(self, request, format=None): serializer = HTRSerializer(data=request.data) if serializer.is_valid(): # input_text haven't use now image = serializer.validated_data['image'] input_text =serializer.validated_data['text'] unique_id = str(uuid.uuid4()) directory_path = os.path.join(os.getcwd(), 'HTR', 'Backend', 'image', unique_id) doc_list = generate_text(image, directory_path, self.config.TrOCR, self.config.device) gc.collect() doc = '\n'.join(doc_list) corrected = None full_doc = doc.replace('\n', '<br>') return Response({'document': full_doc, 'corrected': corrected}, status=status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) main.py for running AI model from fairseq.data import Dictionary from fairseq import utils from torch.utils.data import DataLoader import torch import os, shutil try: from .bpe import GPT2BPE from .dataset import STRDataset from .Preprocess.main import processing except ImportError: from bpe import GPT2BPE from dataset import STRDataset from Preprocess.main import processing … -
How to Post Video source from react native camera component to Django server
How can i post video source(Which formate) from react native to Django server after processing video then return to react native Component In my Camera Component try { const response = await axios.post('http://localhost:8000/my-post-view/', {videoSource}); setApivideo(response.data); } catch (error) { console.error('Error:', error); } In My Django View def my_post_view(request): if request.method == 'POST': video_uri = request.data.get('videoUri') //Im Processing video Here actually its not reading video_uri - cap = cv2.VideoCapture(video_path) //After processing the video return HttpResponse({'processedData': cap}) I tried above Using Post method but im confused about how to post video source and get Processed video return back to my react native component -
Python import modules in a script is not working
import json import os import django import openai import sys # Ensure the DJANGO_SETTINGS_MODULE is set to your project's settings module. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tastify_backend.settings") django.setup() from recipe.models import Ingredient, IngredientCategory, MeasuringUnit, Recipe print(Ingredient.objects.all().select_related('ingredient_category').filter(ingredient_category=1)) The import of the model does not work, there is the following: Here is the error traceback, so that you can check what I am missing. Traceback (most recent call last): File "/Users/patrickvogele/Desktop/tastify_backend/recipe/scripts/generate_ingredients.py", line 9, in <module> django.setup() File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tastify_backend' Why is that? -
Why does it give an error when trying to do django logging writing its handlers?
settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'database': { 'level': 'DEBUG', 'class': 'megabot.log.DatabaseHandler', }, }, 'loggers': { 'main': { 'handlers': ['database'], 'level': 'DEBUG', 'propogate':True } }, } log.py import logging from .models import Log class DatabaseHandler(logging.Handler): def emit(self, record): log = self.format(record) level = record.levelname message = record.getMessage() Log.objects.create(level=level, message=message) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = DatabaseHandler() formatter = logging.Formatter('%(levelname)s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) models.py class Log(models.Model): level = models.CharField(max_length=50) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I'm trying to set up recording errors directly to my application Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/artemivasenko/Library/Python/3.9/lib/python/site-packages/django/utils/log.py", line 76, in configure_logging logging_config_func(logging_settings) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/logging/config.py", line 809, in dictConfig dictConfigClass(config).configure() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/logging/config.py", line 571, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'database' -
how to log the user in Directus from a different domain and login form then authenticate him in the Directus admin page
now I have created a Directus application, and am using it as a back-end .. and am letting the user log in from another external domain and form Django app and sending post request to be able to login .. how to stop Derictus from asking him to log in again after i redirect him to the Directus admin panel link after login success ? here are some of the codes I have used for the whole process : docekr-compose.yaml for the Directus part : version: "3" services: db: image: ${DB_IMAGE} container_name: ${DB_CONTAINER_NAME} volumes: - ${DB_VOLUME} ports: - '${DB_PORT}:5432' restart: always environment: - POSTGRES_DB=${DB_DATABASE} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} # - PGDATA=/tmp directus: image: directus/directus:10.7.1 container_name: ${WEB_CONTAINER_NAME} ports: - ${APP_PORT}:8055 restart: always volumes: - ./uploads:/directus/uploads environment: KEY: ${KEY} SECRET: ${SECRET} ADMIN_EMAIL: ${ADMIN_EMAIL} ADMIN_PASSWORD: ${ADMIN_PASSWORD} DB_CLIENT: ${DB_CLIENT} DB_FILENAME: ${DB_FILENAME} DB_HOST: ${DB_HOST} DB_PORT: 5432 DB_DATABASE: ${DB_DATABASE} DB_USER: ${DB_USER} DB_PASSWORD: ${DB_PASSWORD} WEBSOCKETS_ENABLED: true depends_on: - db and my Django logic : def authenticate_user(request): print("function called") if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') # Create a JSON payload data = { "email": email, "password": password } # Send a POST request to the external API url = "http://<my_domain>:<port>/auth/login" headers = {'Content-Type': 'application/json'} … -
Djnago Admin : Country/State/City Dropdown
I'm trying to do a chained dropdown of Country/State/City in Django Admin I know there is lot of post about this, And this is very basic problem. Is there any good solution or builtin solution that Im missing, Can anyone tell, How to solve it or guide in proper direction? -
Sending emails with Django, not receiving email
I am trying to implement a contact form in Django. It works locally in the terminal if i change EMAIL_BACKEND to console rather than smtp. I have set up 2FA in Gmail and using this as the password, I am also deploying to Heroku where I have set up the correct config vars. Can anyone see why this might not be working? setting.py file # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER') SERVER_EMAIL = os.environ.get('EMAIL_HOST_USER') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = False EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASS = os.environ.get('EMAIL_HOST_PASS') views.py from django.shortcuts import render, redirect from django.core.mail import EmailMessage, get_connection from django.conf import settings # Create your views here. # https://opensource.com/article/22/12/django-send-emails-smtp def send_email(request): if request.method == "POST": with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=settings.EMAIL_HOST_USER, password=settings.EMAIL_HOST_PASS, use_tls=settings.EMAIL_USE_TLS ) as connection: name = request.POST.get("name") email_from = settings.EMAIL_HOST_USER recipient_list = [request.POST.get("email"), ] message = request.POST.get("message") EmailMessage(name, message, email_from, recipient_list, connection=connection).send() return render(request, 'contact.html') contact.html <section class="container"> <div class="row justify-content-md-center"> <div class="col-sm-6 center-form"> <h1>Contact Us:</h1> <form method="POST" action="{% url 'mail' %}" id="contact-form"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name" id="name" placeholder="Name" required> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" name="email" id="email" placeholder="Email" required> </div> … -
Add multiple category for one post (drf+React)
I have a blog website built with Django and React. I'm currently working on adding a new blog post feature, and I want to allow users to select one or multiple categories for their blog post. Here's what I have done so far: Fetched all the categories from the database and displayed them in a dropdown/select field. Users can select one or multiple categories from the dropdown. Now, I need help with the next steps. How can I send the selected categories to the database and save them for the new blog post? Any guidance or code examples would be greatly appreciated. import React, { useEffect, useState } from 'react'; import Dashboard from './Dashboard'; import useAxios from '../../utils/useAxios'; function AuthorCreateBlogs() { const baseurl = "http://127.0.0.1:8000/api/posts/v1"; const [selectedCategories, setSelectedCategories] = useState([]); const api = useAxios(); const [categoriesData, setCategoriesData] = useState([]); const [blogData, setBlogData] = useState({ "title": "", "slug": "", "body": "", "tags": "", "categories": [], "img": "", }) const handelInputChange = (event) => { const { name, value } = event.target; setBlogData((blogData) => ({ ...blogData, [name]: value })); }; const handleFileChange = (event) => { setBlogData((blogData) => ({ ...blogData, ['img']: event.target.files[0] // Match the key used in FormData })); }; const … -
Sitemaps in Django
I'm trying to get the dynamic sitemap generator working in my Django blog. I've followed the directions given here, I even went so far as to create a new "recipes" project and worked through the tutorial. I got the sitemap to work in the tutorial, but I can't get it to work in my blog. Can anyone help? Here's the project-level urls.py: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import TemplateView from django.contrib.sitemaps import GenericSitemap from django.contrib.sitemaps.views import sitemap from blog.models import Post # from blog.sitemaps import BlogSitemap info_dict = { "queryset": Post.objects.all(), "date_field": "date_posted", } urlpatterns = [ path('admin/', admin.site.urls), # path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetView.as_view( template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('', include('blog.urls')), path('summernote/', include('django_summernote.urls')), # Robots.txt path('robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), # Sitemap # path('sitemap.xml', sitemap, {'sitemaps': {'blog': BlogSitemap}},), path("sitemap.xml", sitemap, {"sitemaps": {"blog": GenericSitemap(info_dict)}},), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's the blog app's urls.py: from django.urls import path from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, … -
"Origin checking failed - null does not match any trusted origins"
I run two servers with two different PORTs on localhost. (localhost:3000 and localhost:4000) I have a post form in localhost:3000 and want to send to localhost:4000 <form action = "http://localhost:4000/print" method = POST> {% csrf_token %} <input type="file" id="myFile" name="filename"> <input type="submit"> </form> in my views.py of localhost:4000 if request.method == "POST": data = request.POST file = data.get("filename") return render(request,"print_success.html",{"form":file}) Error occurs: Origin checking failed - null does not match any trusted origins I don't know why there is origin:null Already tried cors-headers set up -
Django : IsAuthenticated and TokenAuthentication decorated views getting accessed without any Authentication Token
I have used simple-jwt for JWT authentication in a simple To-Do app. For OTP based authentication i have created a custom user model and also overridden the TokenObtainPairSerializer from simple-jwt. My token urls are working fine but my get-todos view getting accessed without any authentication. Github Repo: https://github.com/ShouravAhmed/django-react-practice-code/tree/main/Django/djtodo following is my code snippets. //urls path('get-todos/', get_todos, name='get_todos'), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), //views.py @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) @api_view(['GET']) def get_todos(request): resp = {'status': 200, 'message': 'success'} try: todos = Todo.objects.all() serializer = TodoSerializer(todos, many=True) resp['count'] = len(serializer.data) resp['data'] = serializer.data except Exception as e: resp['status'] = 400 resp['message'] = 'Exception Occered' resp['exception'] = str(e) return Response(resp) // models.py class User(AbstractUser): id = models.CharField(max_length=15, default="") phone_number = models.CharField( max_length=15, unique=True, primary_key=True) full_name = models.CharField(max_length=73, blank=True, null=True) address = models.TextField(blank=True, null=True) total_purchase = models.IntegerField(default=0) points = models.IntegerField(default=0) visit_count = models.IntegerField(default=0) staff_level = models.IntegerField( choices=StaffLevel.choices, default=StaffLevel.USER) created_at = models.DateField(auto_now_add=True, editable=False) updated_at = models.DateField(auto_now=True, editable=False) is_phone_verified = models.BooleanField(default=False) username = models.CharField(max_length=30, null=True, blank=True) def save(self, *args, **kwargs): self.id = self.phone_number super(User, self).save(*args, **kwargs) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['full_name', 'email'] objects = UserManager() // manager.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('phone number is required') user = … -
Django first() for every item
Suppose I have a model EventParticipant, which stores participant data for a given Event. Now I want to retrieve the next event participance for a list of users. The following: EventParticipance.objects.filter(user__in=userlist, start__gte=timezone.now()).order_by(start) would give me all event participances for all users in userlist that start in the future. However, I only want the first one for each user. In Postgres, this could be achieved (I think) by this: EventParticipance.objects.filter(user__in=userlist, start__gte=timezone.now()).order_by(start).distinct('user'). However, this does not work for sqlite or mysql. Obviously, as shown here, this would work, but I suppose it'd be very slow: next_occurrence_ids = [] for user in userlist: id = EventParticipant.objects.filter(user=user, .....).order_by(start).values('id').first() next_occurrence_ids.append(id) return EventParticipant.objects.filter(id__in=next_occurrence_ids Is there any other strategy I could employ? -
ValueError in django python [closed]
ValueError: not enough values to unpack (expected 2, got 1) I'm getting this value error. Even i tried running server/make migrations by removing models also im getting same value error. Anyone help me to solve this error. -
Recover Bulk Deleted items in django framework
Is it possible to recover multiple deleted files in one go using django framework. If so, what are the ways? I tried latest file recovery, it worked. but not sure on multiple files recovery . I am using IDE as pycharm and django admin view. -
Timezone conversion failed due to winter hour change pytz
in my code I am trying to convert a date with pytz timezone, but due to the change to winter hour at 3 am, my code crash. I have two questions : one, why does changing hours makes the timezone conversion crash ? Two, how to avoid this bug ? Here is my code : purchase_date = make_aware( datetime.strptime( sale.findtext('n:purchasedate', namespaces={'n': ns}), '%d/%m/%Y-%H:%M' ), timezone('Europe/Paris') ) Error returned : Traceback (most recent call last): File "/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ purchase_date = make_aware( ^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/timezone.py", line 287, in make_aware return timezone.localize(value, is_dst=is_dst) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/pytz/tzinfo.py", line 366, in localize raise AmbiguousTimeError(dt) pytz.exceptions.AmbiguousTimeError: 2023-10-29 02:08:00 Knowing that my code was executed at 3:02 am and the change of hour happened at 3:00 am. Thanks in advance for any response !