Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
iOS QR Code Scan Results in Timeout Error, Works Fine on Android
I am working on a web application where users can scan a QR code to proceed with a transaction. The following JavaScript functions handle the QR code scan status and redirect the user based on the status: postScanStatusAndRedirect() is called after a QR code is scanned. checkQRStatus() periodically checks the status of the QR code. The problem I'm encountering is that when scanning a QR code on iOS devices (Safari browser), I get a timeout error, and the following SweetAlert message is shown: "Your transaction time has expired. Please scan the QR code again". However, the same code works perfectly fine on Android devices and other browsers. async function postScanStatusAndRedirect() { try { const cacheBuster = new Date().getTime(); // Prevent caching with a unique query parameter const response = await fetch(`https://stg-api.goldatm.in/api/qrcode-status?cb=${cacheBuster}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' // More aggressive cache prevention }, body: JSON.stringify({ status: 1 }), credentials: 'same-origin' // Include credentials if needed }); if (!response.ok) { throw new Error(`Network response was not ok: ${response.statusText}`); } const data = await response.json(); console.log('Scan status posted', data); setTimeout(() => { console.log('Redirecting to:', "{% url 'login' %}"); window.location.href = "{% url 'login' %}"; }, 100); // Adjust delay … -
django-import-export Customize admin import forms do not insert value
I am using django-import-export to manage CSV uploads. I have vanilla import working and now want to insert 'retailer' via admin interface. I can select values, but when I submit data, it does not insert. #admin.py @admin.register(Product) class CustomProductAdmin(ImportMixin, admin.ModelAdmin): resource_class = ProductResource import_form_class = ProductImportForm confirm_form_class = ProductConfirmImportForm def get_confirm_form_initial(self, request, import_form): initial = super().get_confirm_form_initial(request, import_form) if import_form: initial['retailer'] = import_form.cleaned_data['retailer'].id return initial def get_import_data_kwargs(self, request, *args, **kwargs): """ Prepare kwargs for import_data. """ form = kwargs.get("form", None) if form and hasattr(form, "cleaned_data"): kwargs.update({"retailer": form.cleaned_data.get("retailer", None)}) return kwargs def after_import_instance(self, instance, new, row_number=None, **kwargs): if "retailer" in kwargs: instance.retailer = kwargs["retailer"] #forms.py class ProductImportForm(ImportForm): retailer = forms.ModelChoiceField( queryset=Retailer.objects.all(), required=True) class ProductConfirmImportForm(ConfirmImportForm): retailer = forms.ModelChoiceField( queryset=Retailer.objects.all(), required=True) #resource.py class ProductResource(resources.ModelResource): class Meta: model = Product code is simplified I want to choose the retailer myself when importing data -
Django override datetime format in browsers [closed]
I am unable to set a datetime format to my django app and the datetime format does not look the same in different browsers. How to set datetime field format in Django? Currently the datetime field looks like: in MS EDGE datetime field in microsoft edge in Google CHROME datetime field in google chrome I have tried setting datetime field formats in forms.py and I have changed the parameter USE_I18N = False setting.py file. What else could I try to set a datetime field format in my django app? -
Django: managment command for project
I have a django project with several apps; I have registered custom management commands for several of the apps and that works as intended. However now I would like to add a management command for the entire site which is not related to any specific app - is that possible? Have tried putting a managment command in site/management/commands but then manage.py did not find my command. -
Django Rest Framework Token Authentication Not Working in production
I have deployed the Django Application on VPS server with following configuration. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "rest_framework.authtoken", "stocks", "stock_api", ] # REST Framework Configurations REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication", ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I have tested the following code on my local machine and it works well. But in production, it shows an error as Credential not provided. import requests headers = {"Authorization": "Token 0f2c3e612ffba7d7b45164b8c8567dc56c113347"} response = requests.get(endpoint, headers=headers) print(response.status_code) print(response.json()) Error status_code : 401 { "detail": "Authentication credentials were not provided." } I have tested the same Code on my local machine, but it is showing ok status. -
FieldError: Cannot resolve keyword 'username' into field
Using Django 4.2.5, Django-cms 4.1.2, python3.11 I was in the process of trying to enter the content for a static_alias field when I got this error: Internal Server Error: /en/admin/djangocms_alias/alias/1/change/ django.core.exceptions.FieldError: Unsupported lookup 'username' for BigAutoField or join on the field not permitted. django.core.exceptions.FieldError: Cannot resolve keyword 'username' into field. Choices are: created_usergroups, created_users, djangocms_usersettings, email, filer_clipboards, filer_folder_permissions, filer_owned_folders, first_name, globalpagepermission, groups, id, is_admin, is_staff, is_superuser, last_login, last_name, locking_users, logentry, owned_files, pagepermission, pageuser, password, statetracking, student, teacher, user_permissions, version I am using an abstract user model: Models.py class UserProfile(PermissionsMixin, AbstractBaseUser): email = models.EmailField(_('Email Address'), unique=True) password = models.CharField(_('Password'), max_length=255) is_admin = models.BooleanField(default=False, verbose_name='Is Admin') is_staff = models.BooleanField(default=False, verbose_name='Is Staff') first_name = models.CharField( default='', max_length=255, verbose_name='First Name') last_name = models.CharField( default='', max_length=255, verbose_name='Last Name') is_superuser = models.BooleanField( default=False, verbose_name='superuser') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserProfileManager() class Meta: verbose_name = _('User Profile') def __str__(self): return self.email Managers.py class UserProfileManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def _create_user(self, email, password, **extra_fields): """ Create and save a user with the given email, and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user … -
how to filter model by foreignkey in django's admin forms?
I'm using django 3.2 I have those models. When adding an item to database through django's admin I'd like to be able to after choose the Disciplina (discipline) item, when I'd choose the assunto(subject) the assunto would be filtered by the subjects of the Discipline chosen above. How to do it in pure django (without javascript)? from django.db import models # Create your models here. class Base(models.Model): criacao = models.DateTimeField(auto_now_add=True) atualizacao = models.DateTimeField(auto_now=True) ativo = models.BooleanField(default=True) class Meta: abstract = True class Disciplina(Base): ORIGEM_CHOICES = [ ('PT', 'Exame Nacional Português'), ('BR', 'ENEM Brasil'), ('SUPERIOR', 'Nível Superior'), ] nome = models.CharField(max_length=100, unique=True) origem = models.CharField(max_length=8, choices=ORIGEM_CHOICES) def __str__(self): return f"{self.nome} ({self.get_origem_display()})" class Assunto(Base): nome = models.CharField(max_length=100) disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE, related_name='assuntos') def __str__(self): return f"{self.nome} ({self.disciplina.nome})" class Questao(Base): disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE) assunto = models.ForeignKey(Assunto, on_delete=models.CASCADE) latex_text = models.TextField(blank = True, null=True) # Novo campo para texto em LaTeX math_jax = models.TextField(blank = True, null = True) gabarito = models.CharField(max_length = 200) dificuldade = models.CharField(max_length = 10, choices=[ ('FACIL', 'Fácil'), ('MEDIO', 'Médio'), ('DIFICIL', 'Difícil'), ]) imagem = models.BooleanField(default = False) link_imagem = models.URLField(blank =True, null=True) link_bucket = models.URLField(blank = True, null=True) def __str__(self): return self.latex_text admin.py from django.contrib import admin from … -
Mailgun in Django Projekt einbinden
Ich versuche die Mailgun Api in mein Django React Projekt einzubinden. enter image description here Dies ist meine Api view: enter image description here und das meine url: enter image description here Wenn ich in dem Browser die url öffne und die email als parameter eingebe kommt dieser fehler: enter image description here Kann mir dabei jemand helfen, die Fehlermeldung wegzubringen. Vielen Dank im Voraus. -
Set admin field short_description dynamically in Django, without trigerring APPS_NOT_READY_WARNING_MSG
I'm encountering the APPS_NOT_READY_WARNING_MSG after updating to Django 5.0. The warning appears in the admin when using a custom field description set via @admin.display(). I need to include these custom columns in my list_display, where they are dynamically calculated based on the current_year retrieved from the database. Here’s an example from my admin mixin: from app.models import FiscalYear class MyAdmin(admin.Modeladmin): current_fiscal_year = FiscalYear().get_current_fiscal_year() @admin.display(description=f"FY{current_fiscal_year}") def total_exercice_courant(self, obj): total_exercice_n = obj.get_montant_exercice_n(year_n=0) return format_number_euro(total_exercice_n) if total_exercice_n else "-" To determine whether the column should be labeled FY24, FY25, etc., I currently make a database call (current_fiscal_year = FiscalYear().get_current_fiscal_fiscal_year()). However, this call during initialization is causing the issue. How can i update my admin field short_description later than at import ? -
Adding percentage of student marks in display table in a crud program in Django
<table> {% for data in result %} <tr> <td>{{ data.id }}</td> <td>{{ data.name }}</td> <td>{{ data.marks1 }}</td> <td>{{ data.marks2 }}</td> <td>{{ data.marks3 }}</td> <td>{{ data.marks4 }}</td> <td> {% with data.marks1|add:data.marks2|add:data.marks3|add:data.marks4 as total %} {{ total }} {% endwith %} </td> </tr> {% endfor %} </table> //show.html(above code) - This is without the math-filters function //views.py from django.http import HttpResponse from django import template from django.shortcuts import render from .models import Student def add(request): if request.method == 'POST': if request.POST.get('name') and request.POST.get('marks1'): stud = Student() stud.name = request.POST.get('name') stud.marks1 = request.POST.get('marks1') stud.marks2 = request.POST.get('marks2') stud.marks3 = request.POST.get('marks3') stud.marks4 = request.POST.get('marks4') stud.save() return render(request, 'add.html') else: return render(request, 'add.html') def show(request): data = Student.objects.all() return render(request, 'show.html', {'result': data}) register = template.Library() @register.filter def div(value, arg): try: return float(value) / float(arg) except (ValueError, ZeroDivisionError): return None I tried adding this after the td tag which has the total function hoping it would work but it ends up displaying an error. {% load math_filters %} <td> {% with total=data.marks1|add:data.marks2|add:data.marks3|add:data.marks4 %} {{ total|div:"4"|floatformat:2 }} {% endwith %} </td> enter image description here Image of the error that occurs. -
Superadmin login is asking for staff account
I am trying to create a custom user model in my Django project. Here are my code: models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager ############# Handles the creation of regular users and # superusers (admin users) with custom logic. ############ class MyAccountManager(BaseUserManager): # Creates a regular user with the necessary fields def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have a username') user = self.model( email = self.normalize_email(email), # This line normalizes the email address #that means it converts the domain part of the email address to lowercase. username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user # Creates a superuser with the necessary fields def create_superuser(self, first_name, last_name, username, email, password=None): user = self.create_user( # This line calls the create_user method to create a regular user. email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superadmin = True user.save(using=self._db) return user ######################## This is a custom user model that represents a user # with fields that go beyond the default Django user model.################# … -
Django User as foreignKey has strange behaviour
I am building a restful API in Django and I have noticed something quite odd! This is my Topic Model: class Topic(models.Model): """ Topic base model""" owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150, blank=False, null=False) content = models.CharField(max_length=500, blank=False, null=False) date_added = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return self.title And this is my serializer: class TopicSerializer(serializers.ModelSerializer): """Serializer for the Topic model""" user = serializers.ReadOnlyField(source='owner.username') class Meta: model = Topic exclude = ['owner'] extra_kwargs = {'pk': {'read_only': True}, 'owner': {'read_only': True}} As you can see owner is excluded, but when I make a get request /api/topics/1/ at my Topic ModelViewSet, I get: {"id":1,"user":"Javad","title":"a","content":"b","date_added":"2024-08-25T19:57:00.712475Z"} And when I include owner in my serializer I get: {"id":1,"user":"Javad","title":"a","content":"b","date_added":"2024-08-25T19:57:00.712475Z","owner":"90f8d3d9-08c2-4890-9ba6-3e6f912b10ee"} So why exactly does Django add a "user" field to my model? I guess this must be intentional and unique to user Model, right? Can I control this? -
Cannot resolve "missing" python package (it isn't missing!) when trying to run open source AI program
I'm rather new to python and AI. I want to use the popular package label-studio to build training data using images that I'll apply the AI labelling steps on. The problem is that after cloning the repo from github and following all the instructions, I'm getting the following error: Traceback (most recent call last): File "/Users/markalsip/label-studio/label_studio/manage.py", line 11, in from django.conf import settings ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/markalsip/label-studio/label_studio/manage.py", line 18, in raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The first problem is that django IS installed and my PYTHONPATH environment variable, by all means at my disposal, is correct: django-admin --version returns: 3.2.25 echo $PYTHONPATH returns: /Users/markalsip/label-studio/env/lib/python3.12/site-packages: I should point out the instructions for this program indicate I should run it in what I believe to be a virtual environment. I have done this (my current root folder is Marks-MBP:label-studio, thus the text shown in the prompt): Marks-MBP:label-studio markalsip$ source /Users/markalsip/label-studio/env/bin/activate (env) Marks-MBP:label-studio markalsip$ python --version returns: Python 3.12.0 To run the python … -
"detail": "Authentication credentials were not provided." drf
I'm doing a pet project. And I need to make that only authorized users can make POST/PATCH requests, and that only the owners of items can change/delete them. views.py(item_app) class CreateItemView(APIView): serializer_class = CreateItemSerializer authentication_classes=[OwnAuthentication] permission_classes=[IsAuthenticatedOrReadOnly, IsOnwerOrReadOnly] ... code ... permissions.py(item_app) from rest_framework import permissions class IsOnwerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user authentication.py(auth_app) from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class OwnAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('username') if not username: return None try: user= User.object.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) settings.py AUTH_USER_MODEL = "auth_app.Users" REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } [Authorization is done via JWT tokens, at login I get access token and copy it and paste it into header “Authorization” in postman, and when I enable this header there is still an errorenter image description here]1 -
How to handle custom error message for Django Admin panel save_model method?
I've overwritten a save_model method for ModelAdmin. Let's say like below: def save_model( self, request, obj, form, change, ): if not change: try: if True: raise exceptions.ValidationError( _(f"Oh no, record can't be created for serious reason!") ) except exceptions.ValidationError as err: messages.set_level(request, messages.ERROR) self.message_user(request, err.message, level=messages.ERROR) return super().save_model(request, obj, form, change) I can't use Form, since I need database access to validate business logic. This almost worked, nevertheless I get redirect to main admin panel screen with I don't really like. Moreover, there is ADDITIONAL message displayed, that object does not exist (of course it doesn't exist, since it wasn't created). I will appreciate any tips how to stay on current screen and display just a custom message or at least be redirect to main admin panel screen, but without displaying additional message (just my custom one). -
Trying to run django for the first time
I can't access files in my app hello in my template, rendering them does not work. Here is my github repo to understand the issue https://github.com/Firiceee/Bug_django . I tryed to understand where does the problem come from as u can see with the exept, and effectively it triggers the except, furthermore, the last render, simpler does already not work, it's like , I can't access my directory "templates"... -
Session ID Returns None After Setting Session Data in Django with React Frontend
I'm working on a Django backend with a React frontend and using sessions to manage user authentication. After successfully logging in a user, I'm setting session data (e.g., user_id, name, email, etc.), but the session ID is returning as None despite the session data being correctly stored. I've configured SESSION_ENGINE to use the database and set SESSION_SAVE_EVERY_REQUEST = True. CORS headers are properly configured with CORS_ALLOW_CREDENTIALS = True. Despite these settings, the session ID isn't being generated or returned correctly, which is causing issues with session management on the client side. How can I resolve this issue and ensure the session ID is properly generated and accessible after login?(https://i.sstatic.net/EawnCfZP.png) I configured Django's session settings to use database-backed sessions, set SESSION_SAVE_EVERY_REQUEST = True, and enabled CORS with credentials. I expected the session ID to be generated and returned after a user logs in, allowing for proper session management. However, the session ID is returning as None, even though the session data is correctly stored and accessible. I’ve also verified that CORS and session settings are properly configured but still face the issue.enter image description here -
Integrating Strapi with existing backend and database
I’m working on a website that uses a Django backend with NextJS frontend. The database used is PostgreSQL. The website can be considered as an affiliate marketing platform. So a lot of features involving brands and products are present. Now a new Strapi CMS was decided to be added to the website for handling brand and products. So the django backend will be used for all the other functions while the direct CRUD of the brands and products will be handled by Strapi. But strapi flushes the entire connected database and I don’t want to set the entire database schema in strapi since it uses only brands and products - two tables. While the current backend has about 50 tables. So this means that Strapi would require a new database instance. Now, product and brand data is also needed by the existing django backend for some functions. So is there a way that I can just use Strapi for its frontend and further plugins while I can continue to use Django as the backend. -
the runserver command don't show url
I wanted to execute the runserver command, but it show lot's of non useful texts/codes I expected the url to adminstration site, but it just showed this: Watching for file changes with StatReloader Exception in thread django-main-thread: -
What libraries do programmers often use? And is it necessary to learn PyGame and Tkinter?
I am a beginner programmer and I want to understand what to do after learning the basics of Python. What libraries to learn and where to go?I want experienced python developers to answer. Thanks for your attention. I tried to learn tkinter but then I thought why do I need it and do programmers use the tkinter library -
How can I send an image inside a form in a state variable in react to a django backend
I am trying to send an image to be stored in the backend. The image is stored in a react useState that is updated when the user changes the the input form and is sent to its django backend api. The api accepts other inputs, not just the image, that are strings. So to send the request I store everything in an useState and make the request in an async function. The api has been tested to work on postman, the problem is I don't know too well how to make the request. The image is an optional parameter and therefore it works perfect just with the other inputs, without the image. Previously, I ignored the image and went along with the other inputs to make the request, which worked perfectly. I did this by putting everything in an object. Although when I put the image in the same object it stops working. I looked around and I found out to send images I need to use the FormData constructor and so I did, but I encountered a few problems. This is how my form component looks like: export default function Component() { const [ image, setImage ] = useState<File>(); … -
about useing photo in django
enter image description here from django.db import models # Create your models here. class Food (models.Model): name=models.CharField(max_length=100) tozih=models.CharField(("tozih"), max_length= 50) rate=models.IntegerField(("score")) price=models.IntegerField() pub=models.DateField(("when"), auto_now= False , auto_now_add= True) p2hoto=models.ImageField(upload_to='foods/' , max_length= 20000 ) i want to in my admin page upload a image but is giving me this -
Is there a ModelAdmin method that runs after Model.clean()?
I'm raising ValidationError in my model's clean() method from django.core.exceptions import ValidationError class PosDetail(models.Model, PosDetailChecksMixin): self._errors = set() ... def clean(self, *args, **kwargs): if PosDetail.objects.filter(username=self.username).exists(): # example ValidationError self._errors.add('check_duplicates') raise ValidationError("This username is already in use.", code="invalid") return super().clean(*args, **kwargs) the ValidationError then is shown in the admin change view form after a POST request. i want to show a button in the admin change view after form submission i tried the save_model method but i dose not execute if a ValidationError is raised. i also tried to override the change_view method of the ModelAdmin but it executes before the Model clean method so it misses the validations. @admin.register(PosDetail) class BddDetailAdmin(admin.ModelAdmin): ... def change_view(self, request, object_id, form_url="", extra_context=None): extra_context = extra_context or {} pos_detail = self.get_object(request, object_id) if request.POST: if pos_detail and 'check_duplicates' in pos_detail._errors: extra_context['show_save_anyway'] = True else: extra_context['show_save_anyway'] = False return super().change_view(request, object_id, form_url, extra_context) Is there a ModelAdmin method that runs after Model.clean() ? so i can catch the ValidationError that accur in the Model.clean method. -
Django makemigrations not making migrations for my app
Full disclosure. This is for my github project warehauser which can be found at: https://github.com/warehauser/warehauser If you download it and follow the INSTALL file instructions it says to python manage.py makemigrations But when that is done it does not make the migrations for the core app. 'core' is included in the warehauser/settings.oy INSTALLED_APPS setting. The 'core' app/directory is in the project base directory. If I go: python manage.py makemigrations core It picks up the core app and makes the migrations. But I want to know why it is not working without specifying the core app explicitly. I attempted: (venv) D:\project\warehauser\>python manage.py makemigrations And expected that to include making migrations for core app. I attempted: (venv) D:\project\warehauser\>python manage.py makemigrations core And that worked. But I need the first command to work for the core app. -
What are the steps involved in Django API creation? [closed]
I'm currently learning Django. All the online resources have been teaching the concepts or uploaded their own created apps or API? What are the steps involved in creating an API in Django? From Scratch, How an individual can create an API using Django? The prerequisites, basic steps or How to partition the project for creating an API and proceed with that?