Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Python suddenly goes Internal error in Azure
I'm pretty new in Python I only worked with it 3 months and I must take care with this implantation in my current job. The thing is the Django Web App inside Azure suddenly throws Internal Error Monday the Web App was working without problem, yesterday suddenly stopped working and throws Internal Error . The log is the next one. 2023-12-13T10:00:49.303444248Z: [ERROR] [2023-12-13 10:00:49 +0000] [108] [ERROR] Error handling request / 2023-12-13T10:00:49.303502748Z: [ERROR] Traceback (most recent call last): 2023-12-13T10:00:49.303508848Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 135, in handle 2023-12-13T10:00:49.303512948Z: [ERROR] self.handle_request(listener, req, client, addr) 2023-12-13T10:00:49.303516548Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 178, in handle_request 2023-12-13T10:00:49.303520448Z: [ERROR] respiter = self.wsgi(environ, resp.start_response) 2023-12-13T10:00:49.303523948Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ 2023-12-13T10:00:49.303527548Z: [ERROR] response = self.get_response(request) 2023-12-13T10:00:49.303530848Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 139, in get_response 2023-12-13T10:00:49.303534548Z: [ERROR] set_urlconf(settings.ROOT_URLCONF) 2023-12-13T10:00:49.303537748Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/conf/__init__.py", line 104, in __getattr__ 2023-12-13T10:00:49.303541248Z: [ERROR] val = getattr(_wrapped, name) 2023-12-13T10:00:49.303544547Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/conf/__init__.py", line 331, in __getattr__ 2023-12-13T10:00:49.303548047Z: [ERROR] return getattr(self.default_settings, name) 2023-12-13T10:00:49.303551347Z: [ERROR] AttributeError: module 'django.conf.global_settings' has no attribute 'ROOT_URLCONF' I know what it seems... but I double checked all configurations, maybe is something that I'm missing... This is a snippet from settings.py I can't share publicly the entire file but the folder hierarchy … -
Problem with Error 502 when run app on server
I am beginner in Python and Django. I have his code: def force_resend(self): # without this code app run ok url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.secretkey+ "/" + settings.PAYMENT_POS_ID + "/resend/" req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.urlopen(req,context=ctx) contents = data.read().decode('utf-8') contents = '{"status": "OK", "payments_accepted": 1, "payments_count": 1, "payments_declined": 0}' data = json.loads(contents) return data I try this code too: def force_resend_transaction(self): h = httplib2.Http(disable_ssl_certificate_validation=True) resp, content = h.request(settings.PAYMENT_GATEWAY_URL + "payments/" + self.secretkey+ "/" + settings.PAYMENT_POS_ID + "/resend/") # # content = '{"status": "OK", "payments_accepted": 1, "payments_count": 1, "payments_declined": 0}' c = json.loads(content) return data When I run this code on my local PC - it's work without any problems. When i try run this in my Kubernetes, i have Error 500. Other functions in my app work correctly. Problem is only with this method. How can i fix them? I use Python 3.8 Please help me :) -
Creating an object of a class whose field is a set of objects of another class
In the Django model lets create a class, eg Ingredients: class IngredientsClass(models.Model): name = models.CharField('Name', max_length=50, default='') package_price = models.FloatField() package_amount = models.FloatField() supplier = models.ForeignKey(SupplierClass) price = models.FloatField() Now lets make some product from the ingredients class DishClass(models.Model): name = models.CharField('Name', max_length=50, default='') price = models.FloatField() ingredients = models.***???*** And here is a problem... In the field ingredients of an DishClass object can be different amount of ingredients from one to thousand. How do I need to set up the field ingredients? -
Deleting items autometically after 15 days of creation from database in django
To achieve this functionality i have used Django Signals, but that is not working in my case, Please let me know if i have done this right, You can also suggest me any other way to achieve this functionality signals.py from django.db.models.signals import pre_delete from django.dispatch import receiver from django.utils import timezone from smart_search.models import UserHitCount @receiver(pre_delete, sender=UserHitCount) def delete_user_hit_count(sender, instance, **kwargs): print("signal handler triggered!") if timezone.now() - instance.created_at > timezone.timedelta(minutes=1): instance.user.delete() app.py from django.apps import AppConfig class SmartSearchConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'smart_search' def ready(self): from . import signals init.py default_app_config = 'smart_app.apps.SmartAppConfig' model.py from django.db import models from user_application.models import Registered_user class UserHitCount(models.Model): user = models.OneToOneField(Registered_user, on_delete=models.CASCADE) search_count = models.IntegerField(default=0) question_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, null=True) My main objective is to delete the things once created date is less then today and this should be done automatically -
i am trying to install django but getting error in path
The script django-admin.exe is installed in 'C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. after running this command :- pip install django how can i fix it -
Automatic field filling based on user information
I want the name field to be filled automatically based on the user's information and the user cannot change it while filling the form. But nothing can be written in the field, nor is it automatically filled, and the form is not sent. It should be noted that without this option, the form works perfectly. models: class Product(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=20) category = models.CharField(max_length=20) seller_price = models.DecimalField(max_digits=10, decimal_places=2) desc = models.TextField() status = models.CharField(max_length=1, choices=choice) image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) active_bool=models.BooleanField(default=False) forms: class ProductForm(forms.ModelForm): user = forms.CharField(disabled=True) class Meta: model = Product fields = ['title', 'category', 'seller_price', 'desc', 'status', 'image', 'image_url'] def __init__(self, args, kwargs): super(ProductForm, self).__init__(args, **kwargs) self.fields['user'].initial = kwargs['initial']['user'] views: def create_product(request): form = ProductForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return redirect('index') else: form = ProductForm() return render(request, 'auctions/create_product.html', {'form': form}) html: {% block body %} <h2>Create New Product</h2> {% if user.is_authenticated %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% else %} Not signed in. {% endif %} {% endblock %} -
Django REST framework and Vue.js "CSRF cookie not set" is occurred
I'm trying to implement the login feature using django and vue.js. But I got an error "CSRF cookie not set" when sending the post request. I checked that I could get the csrftoken correctly by seeing the developer tools. Below is the code of login.vue <template> <div class="hello"> <div class="title-color">This is a Login page.</div> <div class="form-container"> <form v-on:submit.prevent="getCSRF"> <h2>Add User</h2> <div class="form-group"> <label class="label">username</label> <input class="input" type="text" v-model="username" /><br> </div> <div class="form-group"> <label class="label">password</label> <input class="input" type="text" v-model="password" /><br> </div> <button class="button" type="submit">Submit</button> </form> </div> </div> </template> <script> import axios from "axios"; axios.defaults.xsrfHeaderName = 'x-csrftoken' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.withCredentials = true; export default { name: "LoginView", props: { msg: String, }, data() { return { username: "", password: "", csrftoken: "", }; }, mounted() { }, methods: { getCSRF() { axios({ method: "get", url: "http://127.0.0.1:8000/csrf/", auth: { username: "cannot show", password: "cannot show", }, }).then((response) => { this.csrftoken = response.headers['x-csrftoken']; console.log("token is ", this.csrftoken); axios({ method: "post", url: "http://127.0.0.1:8000/login/", data: { username: this.username, password: this.password, }, headers: { 'X-Csrftoken': this.csrftoken, }, auth: { username: "Cannot show", password: "Cannnot show", }, }).then((response) => { console.log(response); }) }) }, } }; </script> Below is the views.py def loginView(request): username = request.POST['username'] password … -
is ConnectionClosedByClient exception from pika a problem
I recently upgraded to a newer version of pika and these logs started showing up where they have not been there before: User-initiated close: result=BlockingConnection__OnClosedArgs(connection=<SelectConnection CLOSED transport=None params=<URLParameters host=rabbitmq port=xxxxx virtual_host=xxxxx ssl=False>>, error=ConnectionClosedByClient: (200) 'Normal shutdown') AMQP stack terminated, failed to connect, or aborted: opened=True, error-arg=None; pending-error=ConnectionClosedByClient: (200) 'Normal shutdown' Stack terminated due to ConnectionClosedByClient: (200) 'Normal shutdown' I have looked over my changes but all I was doing before these logs showed up was to upgrade my django project libraries No changes in logic have taken place It is confusing because according to documentation this exception, ConnectionClosedByClient, is raised when "Connection was closed at request of Pika client." which is the normal behaviour? Also it says Normal Shutdown So am i safe to assume this is just a new log that is cluttering my logs and isn't an actual error because all my rabbitMQ and logs are all good and they are behaving properly as well If it is the case that it is just new logs and this exception needs to be handled for it to not appear in logs, any tips on how to do that safely as well -
Django: Track and save to db user login/logout activities
I want to log users into the database with their time when they log in or log out. I can do this if these operations are done using the login and logout functions, but I need to detect and record the logout operation when they log out by closing the browser. I used websocket for this, but websocket disconnects and reconnects when users switch pages in the project, so it is detected as logout. Is there a way to do this? I added this websocket codes to my base.html let wsProtocol = window.location.protocol === "https:" ? "wss" : "ws"; let url = `${wsProtocol}://${window.location.host}/ws/socket-server/` const markSocket = new WebSocket(url) markSocket.onopen = function(e){ markSocket.send(JSON.stringify({ 'message':'CONNECTED' })) } markSocket.onclose = function(event) { console.error("WebSocket closed:", event); }; and here is my consumer.py that connected to websocket class OnlineStatusConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() user = self.scope['user'] status = True print("CONNECTED",user) await self.change_online_status(user, status) async def disconnect(self, close_code): user = self.scope['user'] status = False print("DISCONNECTED", user,close_code) await self.change_online_status(user, status) @database_sync_to_async def change_online_status(self, user, status): if status: active_user = ActiveUsers.objects.get_or_create()[0] if not active_user.active_users.filter(id=user.id).exists(): active_user.active_users.add(user) active_user.active_user_count += 1 active_user.save() # Kullanıcının en son oturum açma girişimini al last_login_attempt = SpecificUserLoginDiary.objects.filter(user=user).last() # Eğer kullanıcı daha önce oturum açma … -
Django logging not happening in real-time
I have a log configuration setting like the following: LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '[{levelname}] {asctime} {module}.{funcName}.{lineno} {process:d} {thread:d} {message}', 'style': '{' } }, 'filters': { 'filter_for_generic': { '()': 'service.logging.filters.FilterLevels', 'filter_levels': [ "INFO", "DEBUG" ] }, 'filter_for_mail': { '()': 'service.logging.filters.FilterLevels', 'filter_levels': [ "WARNING", "ERROR", "CRITICAL" ] }, }, 'handlers': { 'file_generic': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': path.join(BASE_DIR, 'logs', 'generic.log'), 'when': 'midnight', 'backupCount': 30, 'formatter': 'verbose', 'filters': ['filter_for_generic'] }, 'file_diagnostic': { 'level': 'WARNING', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': path.join(BASE_DIR, 'logs', 'diagnostic.log'), 'when': 'midnight', 'backupCount': 30, 'formatter': 'verbose' }, 'mail_admins': { 'level': 'WARNING', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['filter_for_mail'] } }, 'loggers': { 'app': { 'handlers': ['file_generic', 'file_diagnostic', 'mail_admins'], 'level': 'DEBUG' }, 'jwt_validator_middleware': { 'handlers': ['file_generic', 'file_diagnostic'], 'level': 'DEBUG' }, 'django': { 'handlers': ['file_generic', 'file_diagnostic', 'mail_admins'], 'level': 'DEBUG' } }, } Let's say I am something in my code as follows: LOGGER = logging.getLogger(__name__) LOGGER.info("Hello") The generic log file gets created, but I can't see the Hello in the file. After hours (and most possibly the next day I get to see the Hello in the log file. I tried to look for a bit and I came across something called Buffered output. Something like the logs are buffered before … -
Django DB backup and restore
I am using Postgres in my Django project. My concern is regarding database backup and restore. Let's say I have a Django model named TestModel with name as a char field in that TestModel. I have ran Django's migrations and have inserted the data into model from Frontend. Then I take backup of database using django's dumpdata command and store it into backup.json. At some point after backup, I had to delete my database, change the field name 'name' to 'machine_name' of TestModel and then I ran migrations. Now when I try to insert data by loaddata command using my earlier backup file named backup.json, it gives me error for that name field that I had changed. I tried: Django's built-in commands like dumpdata and loaddata. Third-party library django-dbbackup I need to know how this database backup and restore is carried out in production when there are changes in database schema. How can I know the changes in database schema from one backup to another and if there are changes in schema I still be able to restore my old data into new database. -
While Scheduling Task with Celery in Djano Backend is good RabbitMQTT or django-celery-result?
here is my task.py: @shared_task def schedule_task(subscription_id): subscription = Subscriptions.objects.get(id=subscription_id) # Perform the task for the subscription # ... pass @shared_task def remove_task(subscription_id): # Task to remove the subscription-related task # ... pass here is my model.py with signals in it: def generate_dispatch_uid(): timestamp = timezone.now().isoformat() unique_id = str(uuid.uuid4()) dispatch_uid = f"{unique_id}_{timestamp}" return dispatch_uid def default_billing_date(): return date.today() + timedelta(days=7) class Subscriptions(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.ForeignKey(Group, on_delete=models.CASCADE) subscription_token = models.CharField(max_length=100) is_yearly = models.BooleanField(default=False) billing_date = models.DateField(default=default_billing_date) @staticmethod def schedule_subscription_task(subscription): if subscription.is_yearly: # Schedule task to run after 12 months and +6 days schedule_date = subscription.billing_date + timedelta(days=372) schedule_task.apply_async(args=[subscription.id], eta=schedule_date) else: # Schedule task to run monthly, billing_date + 6 days schedule_date = subscription.billing_date + timedelta(days=6) schedule_task.apply_async(args=[subscription.id], eta=schedule_date) @staticmethod def remove_subscription_task(subscription): remove_task.apply_async(args=[subscription.id]) @receiver(post_save, sender=Subscriptions, dispatch_uid=generate_dispatch_uid()) def create_subscription_task(sender, instance, created, **kwargs): if created: Subscriptions.schedule_subscription_task(instance) @receiver(post_delete, sender=Subscriptions,dispatch_uid=generate_dispatch_uid()) def delete_subscription_task(sender, instance, **kwargs): Subscriptions.remove_subscription_task(instance) Here is my celery.py import os from celery import Celery from MyProject.config import RabbitMQTT_Broker, RabbitMQTT_Result_backend os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings') # Create a new Celery app. app = Celery('MyProject') # Configure Celery to use Redis. app.conf.broker_url = RabbitMQTT_Broker app.conf.result_backend = RabbitMQTT_Result_backend # Load configuration from Django settings. app.config_from_object('django.conf:settings', namespace='CELERY') # Discover tasks modules in your apps. app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): … -
My Django url system isn't working, what should I do? [closed]
The urls of django is not working I started learning Django this year, and writing my first code, the urls weren't working, I watched several tutorials and still nothing, I followed Vs Code's guide "https://code.visualstudio.com/docs/python/tutorial-django", I ran it and instead of seeing "Hello, Django!" it just shows that successful installation screen -
django.core.serializers.base.DeserializationError: ['“F(version) + Value(1)” value must be an integer.'] while using reversions
I am trying to use reversions to get keep the revisions of my model, but my model has a field that is updated like this self.version = F("version") + 1. Now if I use the below code, I am getting this error django.core.serializers.base.DeserializationError: ['“F(version) + Value(1)” value must be an integer.'] with transaction.atomic(), reversion.create_revision(): self.save() reversion.set_user(user) but if I use this code, the revision is working fine, but I think this is quite inefficient, is there any other way to do this?? self.save() with transaction.atomic(), reversion.create_revision(): self.refresh_from_db() self.save() reversion.set_user(user) -
Django DB connection error when connecting to MariaDB: SSL connection error: The message received was unexpected or badly formatted
I am trying to set up Django, but whenever Django tries to connect to my remote Database (MariaDB) with these Django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'xx', 'HOST': 'xx', 'PASSWORD': 'xx', 'NAME': 'xx', 'PORT': '', 'OPTIONS': {'ssl': True}, } } I get this error: django.db.utils.OperationalError: (2026, 'SSL connection error: The message received was unexpected or badly formatted') The status of my MariaDB is MariaDB [(none)]> status -------------- C:\Program Files\MariaDB 11.2\bin\mysql.exe from 11.2.2-MariaDB, client 15.2 for Win64 (AMD64), source revision 929532a9426d085111c24c63de9c23cc54382259 Connection id: 98 Current database: Current user: mads@85.81.43.174 SSL: Cipher in use is ECDHE-RSA-AES256-GCM-SHA384 Current pager: stdout Using outfile: '' Using delimiter: ; Server: MariaDB Server version: 10.5.22-MariaDB MariaDB Server Protocol version: 10 Connection: eccentric.dk via TCP/IP Server characterset: latin1 Db characterset: latin1 Client characterset: utf8mb4 Conn. characterset: utf8mb4 TCP port: 3306 Uptime: 2 hours 24 min 5 sec and the SSL settings for the database: MariaDB [(none)]> SHOW VARIABLES LIKE '%ssl%'; +---------------------+----------------------------------+ | Variable_name | Value | +---------------------+----------------------------------+ | have_openssl | YES | | have_ssl | YES | | ssl_ca | /etc/mariadb/chain.pem | | ssl_capath | | | ssl_cert | /etc/mariadb/fullchain.pem | | ssl_cipher | | | ssl_crl | | | ssl_crlpath | | | … -
How to change the default "non_field_errors" message with Django Rest Framework
I'm trying to change the default error message value of a "non field error" in a serializer. Here's what I've got so far: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = "__all__" extra_kwargs = { "non_field_errors": { "error_messages": { "unique": "There exists an item with this name already!" } } } ItemSerializer behaves as expected, but the code above has no effect on the output. -
The django-bootstrap-datepicker-plus is not working properly when the date format option is used to set up a custom date format
I'm using this django model using a DateField with a default: from django.db import models from django.utils import timezone class MyModel(models.Model): submitted_by = models.ForeignKey( User, null=True, on_delete=models.SET_NULL, verbose_name=_("Submitted by"), related_name="submitted_by", ) submitted_at = models.DateField( default=timezone.now, verbose_name=_("Submission date"), ) along with this form: from bootstrap_datepicker_plus.widgets import DatePickerInput from django import forms from .app.models import MyModel class MyForm(forms.ModelForm): class Meta: model = MyModel fields = [ "submitted_by", "submitted_at", ] widgets = { "submitted_at": DatePickerInput( options={ #"format": "DD-MM-YYYY", # <---- line to uncomment "locale": "fr-FR", "useCurrent": False, } ), } def clean(self): cleaned_data = super().clean() for i, (k,v) in enumerate(cleaned_data.items()): print(f"{i}) {k}: {v} type {type(v)}") return cleaned_data Everything is fine, except that the date in my form widget is in the American style: MM/DD/YYYY which I do not want. That's why I've added the "format" option, but once this option is set up (line to be uncommented in the above code), my form is no more valid: the date field becomes red when I submit the form data, but no error message is raised on the server side. The data is simply not submitted to the database. And the print you can see in the clean() function no longer returns anything related to … -
Could not build wheels for libsass
Hey guys i'm trying to start a project in wagtail using docker and I have the following requeirements Django>=4.2,<5.1 wagtail>=5.2,<5.3 psycopg2-binary==2.9.9 libsass==0.22.0 django-libsass==0.9.0 django-compressor==4.4 wagtail-metadata==5.0.0 wagtail-modeltranslation==0.14 wagtail-orderable==1.2.0 and here is my Dockerfile # /app/Dockerfile # Pull the base image FROM python:3.11.4-alpine3.17 AS builder # Set workdirectory WORKDIR /src/ # Enviroment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Install server packages RUN apk update \ && apk add --no-cache postgresql-dev gcc python3-dev musl-dev libffi-dev openssl-dev \ && apk add --no-cache jpeg-dev libwebp-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev libxml2-dev libxslt-dev libxml2 \ && rm -rf /var/cache/apk/* /tmp/* # Install python packages COPY requirements.txt . RUN pip install --upgrade pip \ && pip install --upgrade pip setuptools \ && pip install --no-cache-dir -r requirements.txt # Postgres Entrypoint COPY src/entrypoint.sh . ENTRYPOINT ["sh","/src/entrypoint.sh"] # Copy needed files COPY src . and the docker docker-compose.yml version: "3.7" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./src/:/src/ ports: - 8000:8000 environment: - DJANGO_SETTINGS_MODULE=app.settings.dev env_file: - infra/dev/env_files/.env.dev depends_on: - db db: image: postgres:12.2-alpine restart: always ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - infra/dev/env_files/.env.dev.db volumes: postgres_data: Here is my project file system if it helps enter image description here Everytime i … -
HTML CSS background image not loading
I have a background image url('home1400.jpg') from the style.css file. I have saved the image in the same folder as the style.css for debugging. /* ===== Home ====== */ .sectionHome{ width: 100%; min-height: 90vh; background-image: linear-gradient(0deg, rgba(0,0,0,0.3), rgba(0,0,0,0.3)), url('home1400.jpg'); background-position: center; background-size: cover; position: relative; display: flex; justify-content: center; flex-direction:column ; } /* ===== end food Home ====== */ I checked that the home.html reads the style.css because if I change the home1400.jpg for any url with a picture in the internet, it loads the picture in the internet. So I cannot see the image and I dont know why. I see in Chrome inspection that the image points to an static url. Is this the reason? Maybe my Django statics are wrongly set? Any idea what may be going on? I have checked other SO questions but still not working. -
how to fix a string represented form validation in django forms?
#models class PartyTheme(models.Model): franchise = models.ForeignKey(Franchise, on_delete=models.CASCADE) theme_name = models.CharField(max_length=50) theme_price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return f"{self.franchise.name}: {self.theme_name}: {self.theme_price}" #forms class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['party_theme'] def __init__(self, *args, franchise_id=None, **kwargs): super().__init__(*args, **kwargs) self.franchise_id = franchise_id party_theme_choices = [(theme.id, f'{theme.theme_name} - {theme.theme_price}') for theme in PartyTheme.objects.filter(franchise_id=self.franchise_id)] self.fields['party_theme'] = forms.ChoiceField(choices=party_theme_choices, widget=forms.RadioSelect(), required=True) #views def booking_form(request, id): franchise_id = id form = BookingForm(franchise_id=franchise_id) if request.method == 'POST': form = BookingForm(request.POST, franchise_id=franchise_id) if 'paylaterbtn' in request.POST: if form.is_valid(): instance = form.save(commit=False) instance.franchise_id = franchise_id instance.save() print(request.POST) #templatetags from django import template register = template.Library() @register.filter def split_label_price(value): return value.split(' - ') #templates <form method="POST" action="{% url 'booking:booking_form' id=franchise_id %}"> {% csrf_token %} {% if form.errors %} {{ form.errors }} {% endif %} {% for radio in form.party_theme %} <input type="radio" id="{{ radio.id_for_label }}" name="party_theme" value="{{ radio.choice_label|split_label_price|first }}" {% if radio.is_checked %}checked{% endif %}> <label for="{{ radio.id_for_label }}"> {{ radio.choice_label|split_label_price|first }} <span class="hidden"> - {{ radio.choice_label|split_label_price|last }} </span> </label> {% endfor %} </form> Print Statement: "<QueryDict: {'csrfmiddlewaretoken': ['somevalue'], party_theme': ['Space'], 'paylaterbtn': ['paylater']}>" form.errors: "party_theme: Select a valid choice. Space is not one of the available choices." I've tried changing the model string representation to match the template form value="{{ … -
Django: How to prevent duplicate data from being entered into a form
Hi I am new to Django and due to time constraints i am making a personal_project on the go.I have been able to set upa login page and some forms to fetch the data going through videos and tutorial. The issue i am facing now is that for a location model.If i insert same data multiple times it is creating a new row in My DB. What would be the correct way to prevent it should i update my Db model logic or Is there a view level validation that i can implement for same? My Current Model includes User(Default User Model), Agency and Lcoation Models And Each user can create multiple agencies but each agency can have one or more location but not at the same place.Below is how i have set it up is there any to identify if the string is same? One way i though was that i Should query and concat all the fields to lower from Location model before saving it and compare it with the new data and only if its different i should update it .Is it a efficient/valid way to do it? Here is the model i am using Any Advice … -
Django Bootstrap modal forms missing csrf token
I'm using django bootstrap modal forms for login and signup popups but they're missing csrf tokens, i get "CSRF token from POST incorrect." error when signing up or logging in. I have {% csrf token %} in my html templates so that's not the problem. I've seen lots of answers to this problem with views reconfigurations (adding method decorators and form to render context) but since i'm using class-based view from bootstap modal forms documentation example I can't repeat such solutions. My views look like this: class CustomLoginView(BSModalLoginView): authentication_form = CustomAuthenticationForm template_name = 'login.html' success_message = 'Success: You were successfully logged in.' extra_context = dict(success_url=reverse_lazy('home')) class SignUpView(BSModalCreateView): form_class = CustomUserCreationForm template_name = 'signup.html' success_message = 'Success: Sign up succeeded. You can now Log in.' success_url = reverse_lazy('home') I've tried rewriting them with methods like this: class SignUpView(BSModalCreateView): def signup_view(request): form = CustomUserCreationForm() if request.method == "GET": return render(request, 'signup.html', context={'form':form}) if request.method == "POST": data = request.POST if form.is_valid(): user = form.save(False) user.set_password(user.password) user.save() return redirect('home') but then forms stop working. Also, I've tried adding CsrfExemptMixin from django-braces but that didn't work either. The only solution that worked is disabling csrf checks completely but I really want to keep them … -
Django - fill in a field based on what the user enters for another field
I am trying to have a field fill in automatically based on what the user enters for another field. You will see below that there is a Choice field called 'typeofacct' and there is another field called 'mintoopen'. One of the options for 'typeofacct' is Everyday Business and there are 4 other options as well. For example, if the user selects Everyday Business as the option for the 'typeofacct' field, I would like to have the 'mintoopen' field filled in with '$100' (a string). Below are my files: forms.py class WaiveForm(forms.Form): header = forms.CharField( widget=HeaderWidget(attrs={'class': 'my-css-class'}), initial='Fee Waive Worksheet', required=False, label='' ) businessname = forms.CharField(max_length=50, label='Business Name') acctnum = forms.IntegerField(label='Business Account Number') annualreviewdt = forms.DateField(label='Annual Review Date', initial=(today + relativedelta(years=1)).strftime('%m/%d/%Y'), disabled=True, required=False) effectivemonth = forms.ChoiceField(choices=effectiveMonthChoice, label='Effective Month') typeofacct = forms.ChoiceField(choices=typeOfAcctChoice, label='Type of Account') # Table mintoopen = forms.ChoiceField(required=False, choices=minToOpenOptions) class SnippetForm(forms.ModelForm): class Meta: model = Snippet fields = ('businessname', 'acctnum', 'annualreviewdt', 'effectivemonth', 'typeofacct', 'mintoopen') models.py class Snippet(models.Model): businessname = models.CharField(max_length=50) #acctNum = models.IntegerField(max_length=17) acctnum = models.PositiveIntegerField(primary_key=True, validators=[MaxValueValidator(99999999999999999)]) annualreviewdt = models.DateTimeField(default=today) effectivemonth = models.CharField(choices=effectiveMonthChoice, max_length=2) typeofacct = models.CharField(choices=typeOfAcctChoice, max_length=1) # Table mintoopen = models.CharField(max_length=20, blank=True, choices=minToOpenOptions, default=typeofacct.formfield()) def __str__(self): return self.businessname, self.acctnum, self.annualreviewdt, self.effectivemonth, self.typeofacct, self.mintoopen def mintoopen_func(self): return minToOpenArray[int(self.typeofacct)] def … -
cannot import name 'Celery' from partially initialized module 'celery' (most likely due to a circular import)
whatever i do it shows me this error "cannot import name 'Celery' from partially initialized module 'celery' (most likely due to a circular import)" this is my structure in django SB is the project and main is the app that has all the models . └── SB/ ├── main / │ └── tasks.py ├── SB ├── celery.py └── manage.py I tried every structure possible this is my code for celery.p: from celery import Celery from main.tasks import send_subscription_ending_email app = Celery('SB') # Configure broker and backend connections app.config_from_object('django.conf.settings') # Optional: Configure additional worker settings app.conf.beat_schedule = { "send_subscription_ending_emails": { "task": "main.tasks.send_subscription_ending_email", "schedule": crontab(hour="*", minute="0", day_of_month="*"), "args": ([specific_subscription_id]), # Replace with actual ID }, } from main.tasks import send_subscription_ending_email tasks.py: from celery import shared_task from django.core.mail import send_mail from .models import Subscription # Import your Subscription model here @shared_task def send_subscription_ending_email(sub_id): # Fetch the subscription object sub = Subscription.objects.get(pk=sub_id) # Check remaining days remaining_days = sub.remain if remaining_days <= 3: # Get user email and format message user_email = sub.author.email message = f"Hi {sub.author.username},\nYour subscription for {sub.provider} - {sub.tier} will end in {remaining_days} days. Please renew to continue enjoying your subscription benefits." # Send email using your preferred email sending library … -
Swagger wont allow post method to send data to django restAPI
Trying to send data using swagger but POST method is not showing any data input option to send data. why? here are my views : from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from .models import Blog from .serializer import BlogSerializer @api_view(['GET']) def get_blogs(request): blogs = Blog.objects.all() serializer = BlogSerializer(blogs, many=True) return Response({ 'Blogs':serializer.data }, status.HTTP_200_OK) @api_view(['POST']) def create_blog(request): data = request.data serializer = BlogSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({ 'data':serializer.data }, status.HTTP_201_CREATED) return Response(serializer.errors) Here are my urls : schema_view = get_schema_view( openapi.Info( title="Blog API", default_version='v1', description="Test description", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path("admin/", admin.site.urls), path("api/", include('app.urls')), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] How to send data through post method in swagger? How to send input data through post method.