Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable perfomance measures for some transactions in Sentry
Our application written on stack Django\Postgres\Redis\Celery + Vue. As one of the monitoring tool we are using Sentry. Sentry measures performance for transactions. It's possible to control how many transaction will be covered by Sentry with set up sample rate. Also we can control which transaction could be covered with filtering them by (for example) path. How can i exclude transactions from performance monitoring (but still watch them for issues)? -
How to create *working* data migration using relation ot custom User in Django?
I've just started a new project and I'm using custom User model (from django-authtools). Everything works perfect until I got tired of constantly creating example data after wiping the db and decided to add a data migration for development purposes. Mind you, I specifically don't want to use fixtures for this. I have a ContactPerson model that references settings.AUTH_USER_MODEL and I'm using apps.get_model() calls in the migration. Everything by the books (or so it seems): # clients/models.py ... class Client(models.Model): name = models.CharField(max_length=128) class ContactPerson(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="as_contact_person", ) # migration from django.contrib.auth import get_user_model from django.db import migrations def create_example_data(apps, schema_editor): Client = apps.get_model("clients", "Client") ContactPerson = apps.get_model("clients", "ContactPerson") User = get_user_model() jim_user = User.objects.create_user( email="j.halpert@dundermifflin.com", password="*", name="Jim Halpert" ) dunder_mifflin = Client.objects.create( name="Dunder Mifflin, Inc.", ) ContactPerson.objects.create( client=dunder_mifflin, user=jim_user, ) class Migration(migrations.Migration): dependencies = [ ("clients", "0001_initial"), ] operations = [ migrations.RunPython(create_example_data) ] But trying to run the migration I get this error: ValueError: Cannot assign "<User: Jim Halpert j.halpert@dundermifflin.com>": "ContactPerson.user" must be a "User" instance. Other migrations are fresh and the built-in User model had never been used. I've also checked that the User model in the migration is of … -
how to connect service to django admin panel actions
I have the model Machine, that is inherited from models.Model: class Machine(models.Model): ... The model is registered in django admin panel using: admin.site.register(Machine) When I create new model using Add... button, I need to proceed some service code, along with creating new Machine. How can I connect my service code to default django admin panel? I've tried to connect code using re-defining methods in model class, based on information I found in Internet, but that didn't work. -
Full path is not saved to media when I implement django-tenants in my django project
I am implementing multitenant in a django project with PostgreSQL for this I implemented a library called django-tenants but I have a small problem what I wanted was to save the media files for each scheme in a folder with the same name of the scheme for it in the official documentation It told me that I had to put this configuration in my settings.py. DEFAULT_FILE_STORAGE = 'django_tenants.files.storage.TenantFileSystemStorage MULTITENANT_RELATIVE_MEDIA_ROOT = "" To be able to save a folder of the media of my models for each scheme, when I test my model class Product(models.Model): name = models.CharField(max_length=150, verbose_name='Name') image = models.ImageField(upload_to='product/%Y/%m/%d', null=True, blank=True, verbose_name='Image') Actually saving in the correct folder is called schema/product/2023/08/30/imagen.png but when I consult the path in the database it only saves me product/2023/08/30/imagen.png how do I get it to be save the schematic also in the path? I tried to find a solution by all means but none worked. -
I get some error when create new model in Django
I created 2 model for one to one in Django model So model codes is very simple enter image description here I executed CMD after put the above code python manage.py migrate But I get this error message enter image description here` -
Django-admin on react page
I'm trying to put the django-admin page in a react component so that it appears to the user on the frontend. it's a project just for programmers so everyone is authorized. However, I'm having difficulties using the iframe to display the page, how can I do this without harming the application's security? I'm currently trying to use the iframe for this, but some security problems are appearing, mainly those related to crsf. -
Can't serve files located in static root with whitenoise
I am trying to serve my static files in my testing environment that's suppose to mirror my production environment that uses Whitenoise. In setting.py, I believe these are the relevant parts of the issue: DEBUG = True INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', # the rest of the apps ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' if not DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' else: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") # STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')] WHITENOISE_USE_FINDERS = False I set WHITENOISE_USE_FINDERS = False to ensure that my development environment is serving files the way Whitenoise would. Regardless, none of the static assets are being served. The only time things seem to work is when I uncomment STATICFILES_DIRS and set STATIC_ROOT = 'static/, but I can't have that for my production environment. This problem has been troubling me for a long while now and if anyone can offer some insight, I'd appreciate it a lot. -
django-avatar // not enough values to unpack (expected 2, got 1)
https://django-avatar.readthedocs.io/en/latest/ Django returns "not enough values to unpack (Expected 2, got 1) when trying to open this html template: {% extends 'base.html' %} {% load account %} {% load avatar_tags %} {% block content %} <div style="border: 2px solid #ffffff; text-align:center"> <h1>Dashboard</h1> <div> {% avatar user %} <a href="{% url 'avatar_change' %}">Change your avatar</a> </div> <div> <p>Welcome back, {% user_display user %}</p> </div> </div> {% endblock content %} and highlights "{% avatar user %}" Here's the traceback: https://dpaste.com/B7EX28LNB Environment: Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/ Django Version: 4.2.4 Python Version: 3.11.5 Installed Applications: ['yt2b2', 'home', 'dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'embed_video', 'avatar', 'allauth', 'allauth.account', 'allauth.socialaccount'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Pedro\Documents\GITHUB\YT2B2-new-dev\YT2B2\youtube2blog2\dashboard\templates\dashboard\dashboard.html, error at line 10 not enough values to unpack (expected 2, got 1) 1 : {% extends 'base.html' %} 2 : {% load account %} {% load avatar_tags %} 3 : 4 : {% block content %} 5 : 6 : <div style="border: 2px solid #ffffff; text-align:center"> 7 : <h1>Dashboard</h1> 8 : <div> 9 : 10 : {% avatar user %} 11 : 12 : <a href="{% url 'avatar_change' %}">Change your avatar</a> 13 : 14 : </div> 15 … -
How to send emails in the same thread in Django?
I am wondering how can I send email in the same email thread using django.core.mail. I have an APIView that handles post requests from my contact form. It receives the contact form input and sends it to my email. In case when the email address from form input was already used (e.g. first form was submitted with mistakes), I would like such forms to be sent in the same email thread, rather than in separate emails. So basically every thread should contain submitted forms with the same email address as replies to the original email. views.py from rest_framework.views import APIView from rest_framework.response import Response from .serializers import ContactFormSerializer from rest_framework import status from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags class ContactFormAPIView(APIView): def post(self, request): serializer = ContactFormSerializer(data=request.data) if serializer.is_valid(): contact_form = serializer.save() subject = 'New Contact Form Submitted' context = { 'name': contact_form.name, 'email': contact_form.email, 'subject': contact_form.subject, 'message': contact_form.message, 'submitted_at': contact_form.submitted_at, } html_content = render_to_string('api/contact_form.html', context) text_content = strip_tags(html_content) email = EmailMultiAlternatives( subject, text_content, from_email=settings.EMAIL_HOST_USER, to=[settings.EMAIL_HOST_USER] ) email.attach_alternative(html_content, 'text/html') try: email.send() except Exception as e: return Response({'detail': f'Failed to submit the contact form: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({'detail': 'Contact form submitted successfully.'}, … -
Authorization button not appearing in Django Ninja API docs
I am using Django Ninja to build an API, and I am having trouble getting the authorization button to appear in the API docs. I have already added the rest_auth app to my INSTALLED_APPS and add this REST_AUTH_DEFAULT_AUTHENTICATION_CLASS = 'rest_auth.authentication.TokenAuthentication' to my Django settings file, but the button is still not appearing.and this is my api docs and as you see the authorization button don't appear I expected the authorization button to appear in the API docs, so that I could use it to authenticate with my API. However, the button is not appearing. -
Django Allauth - ModuleNotFoundError: No module named 'allauth.account.middleware' even when django-allauth is properly installed
"ModuleNotFoundError: No module named 'allauth.account.middleware'" I keep getting this error in my django project even when django-allauth is all installed and setup??? I tried even reinstalling and changing my python to python3 but didn't change anything, can't figure out why all other imports are working but the MIDDLEWARE one... Help pls? settings.py: """ Django settings for youtube2blog2 project. Generated by 'django-admin startproject' using Django 4.2.4. For more information on this file, see For the full list of settings and their values, see """ from pathlib import Path import django import os import logging import pyfiglet import allauth # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-l_pc%*s54c__=3ub&@d)s&@zp*46*=@)y*uv@v&(b6+hwq1&u5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # CUSTOM CODE # os.environ['FFMPEG_PATH'] = '/third-party/ffmpeg.exe' # os.environ['FFPROBE_PATH'] = '/third-party/ffplay.exe' OFFLINE_VERSION = False def offline_version_setup(databases): if (OFFLINE_VERSION): # WRITE CODE TO REPLACE DATABASES DICT DATA FOR OFFLINE SETUP HERE return True return banner_ascii_art = pyfiglet.figlet_format("CHRIST IS KING ENTERPRISES") logger = logging.getLogger() logger.setLevel(logging.DEBUG) print("\n - CURRENT DJANGO VERSION: " + … -
How to update django user profile information from a form?
I'm creating a web application to track my friends personal bets amongst eachother.. I have added a UserBalance value to the user model, but now I want superuser/admins to be able to update that upon submitting a form. List of all bets Leaderboard with user balances How would I go about making it so the form in last column of first screenshot will update both bettor's balances? accounts models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class UserBalance(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_user_balance(sender, instance, created, **kwargs): if created: UserBalance.objects.create(user=instance) I assume I need to add a method somewhere to take the winner/loser form info and then change the corresponding user's balances but I'm not sure where to do that or how -
not being able to access a variable in python flask
Let me briefly explain to you what I want to do: I want to get the username of the commenter to comment on an article. for this I perform a query from the articles table (sorgu2). Finally, I find the username of the person who made the comment, but I get an error. mistake:UnboundLocalError: cannot access local variable 'cevaplanan' where it is not associated with a value how do i solve this please help `@app.route('/yorum/string:article_title/', methods=["GET","POST"]) def yorum_ekle(article_title): cevap = CevapVer(request.form) form = ArticleForm(request.form) if request.method=="POST" and cevap.validate(): icerik = cevap.icerik.data cursor2 = mysql.connection.cursor() cnt = form.content.data tit = form.title.data sorgu2 = "SELECT author FROM articles WHERE title = %s AND content = %s " cursor2.execute(sorgu2,(cnt,tit)) sonuclar = cursor2.fetchall() cevaplanan = None cursor = mysql.connection.cursor() sorgu = "insert into yorum(icerik,cevaplayan,cevaplanan) values(%s,%s,%s)" cursor.execute(sorgu,(icerik,session["username"],cevaplanan)) mysql.connection.commit() cursor.close() flash("Yorum eklendi","success") return render_template('cevapla.html', article_title=article_title, cevap=cevap) ` I was trying to get a username with sql but couldn't get it -
Order tracking in django
I am a beginner in django and I want to create a web app where a user can enter an order ID and the status of that order will be displayed(eg pending) , and If I change the status it will also change for the user(Ie from pending to processed) how do I go about it Just started out haven’t tried anything yet -
Getting csrf token and sessionid from response headers in react app
We are creating some site. We have react + django rest framework.We use SessionAuthentication in django. So, we have issues with authentication. When frontend is trying to login, he get's status 200, but he can't get csrf token and sessionid from response headers, that backend hash sent. We can see them(csrf token and sessionid) in browser Network as Set-cookie values, also we see them in Postman, but not in js. Why? How can we get them? There is part of my settings.py: MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ] } CORS_ALLOWED_ORIGINS = [ 'http://localhost:5173', ] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://localhost:5173', ] SESSION_COOKIE_HTTPONLY = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' I've tried many of settings, have tried to combine them in separate ways, but it didn't help There is react code: import axios from "axios"; axios.defaults.withCredentials = true; export default async function login(data){ axios.post( 'http://127.0.0.1:8000/user/session/', data ) .then( (response) => { console.log(response) // const headerKeys = Object.keys(response.headers); // console.log(headerKeys); // console.log('Set-Cookie:', response.headers['set-cookie']) }) } This is screenshot of what we get in jsresponse js This is what … -
How to create a copy to clickboard for dynamic buttons
Hi guys I'm working currently on a little project with django and Js, I want to add a button to copy information to clickboard, the buttons are dynamic and the site where I'm working is not https so i can't use "navigator.clipboard.writeText" at this point i can get the information trough the attributes specified in my button, but I'm a litle bit stuck since i don't really know how to copy the information from the variables to the clickboard, I'm newbie so if someone can help me with this it would be really nice :) This is basically the main piece of code {% for item in object_list %} <tr> <td class="th-width">{{ item.user.company.name }}</td> <td class="th-width">{{ item.user.user_name }}</td> <td class="th-width">{{ item.user.full_name }}</td> <td class="th-width email-column">{{ item.user.email }}</td> <td class="th-width">{{ item.expire_date }}</td> <td class="th-width">{{ item.avt_version}}</td> <td class="th-width">{{ item.license_avt }}</td> <td class="th-width">{{ item.generated_user.username }}</td> <td class="th-width"> <button class="control button copy-btn btn" company-name="{{item.user.company.name}}" user-name="{{item.user.user_name}}" full-name="{{item.user.full_name}}" email="{{item.user.email}}" expire-date="{{item.expire_date}}">Copy information</button> </td> </tr> {% endfor %} </tbody> </table> <script> const copyBtns = [...document.getElementsByClassName("copy-btn")] copyBtns.forEach(btn => btn.addEventListener('click', () => { const companyName = btn.getAttribute("company-name") const userName = btn.getAttribute("user-name") const fullName = btn.getAttribute("full-name") const email = btn.getAttribute("email") const expireDate = btn.getAttribute("expire-date") console.log(companyName) console.log(userName) console.log(fullName) console.log(email) console.log(expireDate) btn.textContent = … -
How do I conditionally exclude/ include field in fomset on Django admin site TabularInline?
Point System QA model with Point System QA details model rendered as tabular inline form. How can I conditionally exclude/include a field from the Point System QA details formset? Any help would be much appreciated. Model class PointSystemQADetails(models.Model): point_name = models.ForeignKey('PointSystemQA', blank=True, null=True, on_delete=models.SET_NULL) brand = models.IntegerField(blank=True, null=True) model = models.IntegerField(blank=True, null=True) amount = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) ... more filed Admin page: # Point System QA Details Formset # class PointSystemQADetailsFormSet(BaseInlineFormSet): def get_form_kwargs(self, index): kwargs = super().get_form_kwargs(index) kwargs['parent_object'] = self.instance return kwargs class PointSystemQADetailsForm(forms.ModelForm): brand = forms.ChoiceField(choices = []) model = forms.ChoiceField(choices = []) def __init__(self, *args, parent_object, **kwargs): self.parent_object = parent_object super(PointSystemQADetailsForm, self).__init__(*args, **kwargs) if self.parent_object.device_type.id == 19: del self.fields['model'] # not working.. self.fields['brand'].choices = [('', '------'),] + [(x.pk, x.manufacturer_name) for x in Manufacturer.objects.all()] else: self.fields['brand'].choices = [('', '------'),] + [(x.pk, x.manufacturer_name) for x in Manufacturer.objects.all()] self.fields['model'].choices = [('', '------'),] + [(x.pk, x.series) for x in WatchSeries.objects.all()] class PointSystemQADetailsAdmin(admin.TabularInline): model = PointSystemQADetails formset = PointSystemQADetailsFormSet form = PointSystemQADetailsForm extra = 1 # End Point System # class PointSystemQAAdminForm(forms.ModelForm): class Meta: model = PointSystemQA exclude = ['created_at', 'updated_at', 'created_by', 'updated_by'] class PointSystemQAAdmin(admin.ModelAdmin): model = PointSystemQA inlines = [PointSystemQADetailsAdmin] form = PointSystemQAAdminForm save_on_top = True list_display_links = ('point_name', ) search_fields … -
why django page not found/ URL patterns didn't match?
why page not found what is incrorrect on my code ? and there the dealerships code if there any mistake let me know dealships-home- ` <body> <nav class="navbar navbar-light bg-light"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Dealership Review</a> </div> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <div class="rightalign"> <div class="dropdown"> <button class="dropbtn">{{user.first_name}}</button> <div class="dropdown-content"> <a href="{% url 'djangoapp:logout' %}">Logout</a> </div> </div> </div> {% else %} <div class="rightalign"> <div class="dropdown"> <form action="{% url 'djangoapp:registration' %}" method="get"> <input class="dropbtn" type="submit" value="Visitor" /> <div class="dropdown-content"> <a href="{% url 'djangoapp:registration' %}">Signup</a> <a href="{% url 'djangoapp:login' %}">Login</a> </div> </form> </div> </div> {% endif %} </ul> </div> </nav>` and there the url code if there any mistake let me know url: `app_name = 'djangoapp' urlpatterns = [ # path for dealerships/index path(route='dealerships/', view=views.get_dealerships, name='dealerships'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ` and there the views code if there any mistake let me know Views: ` def get_dealerships(request): context = {} if request.method == "GET": return render(request, 'djangoapp/dealerships.html', context)` Any suggestions -
Unable to use MySql with Django
I am trying to get Django running with MySql, I am following this guide: https://docs.djangoproject.com/en/4.2/intro/tutorial02/ Everything works up until this command: python manage.py migrate I will include the entire error, the punchline is: Traceback (most recent call last): File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: dlopen(/Users/timo/opt/anaconda3/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/timo/Documents/coding/plegeus/musicians/backend/manage.py", line 22, in <module> main() File "/Users/timo/Documents/coding/plegeus/musicians/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Users/timo/opt/anaconda3/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 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/timo/opt/anaconda3/lib/python3.9/site-packages/django/contrib/auth/base_user.py", … -
How to redirect the login to an app, model specific
I need that when I log in, it shows me directly an admin model.. Example, I have the app nameapp, and within the models nodel_one, model_two that are different tables, I need it to show me the records of one of those tables when entering after login. How do I set the urls? I have: # file: intrados/intrados/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('daytona/', include("daytona.urls")), path('', admin.site.urls), # home also goes to admin ] And I need to go to # file: intrados/daytona/admin.py is in URL http://localhost:8000/admin/daytona/domain/ class DomainAdmin(SetReadOnlyModel, admin.ModelAdmin): #xxxxxxxxx te redirect specific table to see records -
changing the project name and environment doesn't work
After my project name was changed, when I activate my environment in my project, it shows activated but doesn't work in wsl2 -
How do I change my whole form based on a user selection? Using Django/Python
I need to build a registration form for industrial equipments. But I want that form to change based on a user selection. For example, some type of equipments require a different types of values and what I need is when the user select a type of equipment the form adapting automatically to what the user needs and later on, save that data in a database. I already tried the Dynamically Change Form Action Based on Selection using jquery, but (as far as I know) this only works for dropdowns menus changing data for another dropdown menu, like when you are on a site that asks for your country in a dropdown menu and in another dropdown right under is a dropdown to select the cities from the country that you selected. Unfortunelly this doesn't help me. What I need is to change the whole form. I'm picturing like a button or checkbox, or even a dropdown menu above the form that asks for the user to choose what type of equipment they want to register and then the form changes. -
Can you tell why here create two objects instead of one object of Notification?
Here I would like to create a notification after creating a blog. It's working fine, but the issue is here creating two objects of Notification instead of one object. Can you tell me where is the problem in my code? models.py: class blog(models.Model): title = models.CharField(max_length=250) img = models.ImageField(upload_to="img_file/", blank=True, null=True) def __str__(self): return f"{self.pk}.{self.title}" class Notification(models.Model): title = models.CharField(max_length=250) details = models.TextField() is_seen = models.BooleanField(default=False) def __str__(self): return f"{self.pk}.{self.title}" signal.py: from django.db.models.signals import post_save from django.dispatch import receiver from .models import blog, Notification @receiver(post_save, sender=blog) def call_notification(sender, instance, **kwargs): Notification.objects.create( title="New Blog Post uploaded", details=f"{instance.id} number Blog" ) -
Django-Rest MultiPartParser vs JsonParser
Imagin in javscript have a object like below : {is_active:false,date:null} it is the data that i get from a form and then i POST this data to the django server when i send data with header: 'Content-Type': 'application/json' , in server i receive this: is_active:False date:None but when i send data with header: 'Content-Type': 'multipart/form-data' , in server i receive this: is_active:'false' date:'null' is there any way to when sending data with 'multipart/form-data' header , and geting python object insted of get an strings -
I am working on a django project and for payment integration we need SSLCOMMERZ python . While installing this problem arises
I am working on a Django project and attempting to install the sslcommerz-python\ package for payment integration. However, I encountered an error during the installation process. Here's the error message: pip install sslcommerz-python Collecting sslcommerz-python ... Building wheels for collected packages: typed-ast Building wheel for typed-ast (setup.py) ... error ... Failed to build typed-ast ERROR: Could not build wheels for typed-ast, which is required to install pyproject.toml-based projects This is the error I get while installing sslcommerz python Thanks in advance for your help.