Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get the label from the value models.IntegerChoices
please help out. I have the class that inherits from models.IntegerChoices, however, I know getting the value can be retried for instance if i want to retrieve the value for Daily, I can run RecurringType.DAILY, and I can get the value using RecurringType.DAILY.value and label by RecurringType.DAILY.label. But now, what if I have the value and want to get the label, how can I do that, I have tried so many things on here but nothing seems to work. Below is the code from django.db import models class RecurringType(models.IntegerChoices): DAILY = 1, ("Daily") WEEKLY = 2, ("Weekly") MONTHLY = 3, ("Monthly") -
PostgreSQL data not showing in Docker Container
I need some help, I'm stuck in Docker and can't find it out. I'm using Windows for a Django APP and Docker I'm using PgAdmin4 with PostgreSQL 16 and created a new server for docker The log for the Postgres Image: PostgreSQL Database directory appears to contain a database; Skipping initialization 2023-11-23 20:17:38.008 UTC [1] LOG: starting PostgreSQL 16.1 (Debian 16.1-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit 2023-11-23 20:17:38.008 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2023-11-23 20:17:38.008 UTC [1] LOG: listening on IPv6 address "::", port 5432 2023-11-23 20:17:38.027 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2023-11-23 20:17:38.086 UTC [30] LOG: database system was shut down at 2023-11-23 20:17:11 UTC 2023-11-23 20:17:39.317 UTC [1] LOG: database system is ready to accept connections Logs from my web: No changes detected Operations to perform: Apply all migrations: admin, auth, base, contenttypes, sessions Running migrations: No migrations to apply. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 23, 2023 - 20:17:44 Django version 4.2.2, using settings 'cutler.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. My docker-compose file: version: '3.9' services: db: image: postgres … -
My django form is not sending the values correctly to my responses page
Im invested on solving the code, theres still some things missing, i took a print the visual part of the pages seem fine, but theres something wrong with how im sending the values and I cant find what, im very distracted though and just started to learn Django, id be glad if someone could help me. views.py imports def form_view(request): if request.method == 'POST': form = ParticipantResponseForm(request.POST) if form.is_valid(): response = form.save(commit=False) # Check if absences_count is not empty before saving absences_count_value = form.cleaned_data['absences_count'] response.absences_count = int(absences_count_value) if absences_count_value else 0 response.save() # Add a success message messages.success(request, 'Form submitted successfully!') # Print form data for debugging print(form.cleaned_data) # Redirect to responses page return redirect('show_responses') else: form = ParticipantResponseForm() return render(request, ' form.html', {'form': form}) def show_responses(request): responses = ParticipantResponse.objects.all() print(responses) return render(request, 'responses.html', {'responses': responses}) models.py from django.db import models from .choices import PARTICIPANT_DISABILITY_CHOICES class Disability(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class ParticipantResponse(models.Model): participant_name = models.CharField(max_length=255) birth_date = models.DateField() gender_choices = [ ('male', 'Masculino'), ('female', 'Feminino'), ] PARTICIPANT_DISABILITY_CHOICES = [ #choices ] gender = models.CharField(max_length=6, choices=gender_choices) participant_disability = models.CharField(max_length=255, choices=PARTICIPANT_DISABILITY_CHOICES, default='') clinical_diagnosis = models.TextField() functional_profile = models.TextField() participation_modalities = models.TextField() participation_observations = models.TextField() attendance_frequency = models.IntegerField() attended_dates … -
Django Heroku pipfile lock out of date
So I recently moved from pipenv to venv, now that I try to push my changes to Heroku, I'm getting: -----> Installing pip 23.3.1, setuptools 68.0.0 and wheel 0.41.3 -----> Installing dependencies with Pipenv 2023.7.23 Your Pipfile.lock (old_hash[-6:]) is out of date. Expected: ({new_hash[-6:]}). Usage: pipenv install [OPTIONS] [PACKAGES]... How can I migrate to venv and not use pipenv anymore in Heroku? should I delete my pipfilelock? -
I have problem with receieving POST type http requests
So... My issue is very simple. I send request from my roblox game using http request (POST method). Now... I've tested with php already, the request is sent successfully and is receieved. However, we talk about Django here. I really want to do that on Django, because I am more familliar with python + I want to do a lot of complicated things, and I highly believe Django is simply what I need With my problem, I suspect simple problem, such as not adding few lines, or simply wrong instalation of django or something else (even tho am very sure I did that correctly) Anyways, if that isn't clear, I send a POST request into the .py file which is placed on my website. The website does not run on my PC, but on my paid VPS which runs on linux ubuntu. After the request is sent, the script is supposed to get the request, and at least tell me it's receieved in my logs, which works perfectly fine. Script: `import logging from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json import time logging.basicConfig(level=logging.DEBUG, filename="testfile", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s") @csrf_exempt def home(request): if request.method == 'POST': post_data … -
Django downloads the result after successful validation and processing of the form
I have such a form for pdf files: class PDFFileUploadForm(forms.Form): file = forms.FileField(widget=forms.FileInput(attrs={'accept': 'application/pdf'})) And this is the view: class PdfTextExtractView(FormView): form_class = PDFFileUploadForm template_name = 'pdf_processing/pdf_processing.html' def form_valid(self, form): text = services.extract_text_from_pdf(form.cleaned_data['file']) In form_valid, I need to redirect the user to a page where he can download a txt file. I know that it is possible to save the file in the database and then redirect the user to the appropriate page with the file id passed for download. But I don't know if this is the best way to do it. Maybe there are some better options? Thank you! -
I'm having problems when sending User's Id's on a django model
I'm tryng to do a post method on projetos on my Vue Front-end but i keep getting the error message of "null value in column "professor_id" of relation "fabrica_projeto" violates not-null constraint" even though the request body is the same when i try to post on django-admin and it works there I'm kinda new to this whole coding world so sorry if my vocabulary is lacking On Vue/ my front-end enter image description here On Django-Admin(works) enter image description here enter image description here This is the model for Projeto enter image description here from django.db import models from usuario.models import Usuario from uploader.models import Image class Projeto(models.Model): nome = models.CharField(max_length=200) descricao = models.CharField(max_length=2500) data = models.DateTimeField(auto_now_add=True) professor = models.ForeignKey(Usuario, related_name='professor', on_delete=models.PROTECT) alunos = models.ManyToManyField(Usuario, related_name='alunos') capa = models.ForeignKey( Image, related_name="+", on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return self.nome My Vue page is looking like this: (the professor part of the request is getting directly from the current user id): import api from '../plugins/api' import {useAuthStore} from '../stores/auth' class WorkspaceService { async getAllWorkspaces() { const response = await api.get('/projetos/') return response.data } async saveWorkspace(workspace) { const authStore = useAuthStore() workspace.professor = authStore.user_id let response if (workspace.id) { response = await … -
Set variable session out of a view in Django
I’m trying to set a variable session out of a view in Django. I’m aware of django’s documentation on Using sessions out of views. But in my case, I try to set a session variable in a custom management command. Here’s what I tried : from django.contrib.sessions.models import Session class Command(BaseCommand): help = "My custom command." def handle(self, *args, **options): for s in Session.objects.all(): s['my_variable'] = None What I get is this error: TypeError: 'Session' object does not support item assignment How can I set my_variable to None ? -
pyODBC Conversion failed when converting date and/or time from character string
Hello I want to convert date stored on a server from string to datetime here the view: class SubscribersListAPIView(ListAPIView): serializer_class = AbonesSerializer def get_queryset(self): start_date_param = self.request.query_params.get("start_date", None) end_date_param = self.request.query_params.get("end_date", None) start_date = None end_date = None if start_date_param: try: start_date = datetime.strptime(start_date_param, "%d/%m/%Y").date() except ValueError: pass if end_date_param: try: end_date = datetime.strptime(end_date_param, "%d/%m/%Y").date() except ValueError: pass queryset = Abones.objects.all() queryset = Abones.objects.annotate( date_as_datetime=ExpressionWrapper(F('date'), output_field=DateTimeField() ) ) if start_date_param and end_date_param: queryset = queryset.filter(date_as_datetime__range=(start_date, end_date)) elif start_date_param: queryset = queryset.filter(date_as_datetime=start_date) elif end_date_param: queryset = queryset.filter(date_as_datetime=end_date) return queryset i tried many solutions using ExpressionWrapper, Cast to force the conversion, Func but it didn't work. I want to filter date using the date_as_datetime but there is this error that come "Conversion failed when converting date and/or time from character string" Here are the traceback : Traceback (most recent call last): File "/home/darcy/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/darcy/var/www/envs/onasoft/lib/python3.10/site-packages/mssql/base.py", line 621, in execute return self.cursor.execute(sql, params) pyodbc.DataError: ('22007', '[22007] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting date and/or time from character string. (241) (SQLExecDirectW)') -
Split Django ModelForm selection base on previous field
So Im making a booking form, I have my Booking Model : class Bookings(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, verbose_name="کاربر",) booker_name = models.CharField(max_length=100, null=True, verbose_name="نام",) booked_time = models.ForeignKey(AvailableHours, on_delete=models.CASCADE,related_name='booked_time', verbose_name="سانس",) booking_code = models.IntegerField(unique=True,default=random_string, verbose_name="کدپیگیری",) confirmed = models.CharField(max_length=100,choices=BOOKING_STATUS,default='در انتظار',null=True, verbose_name="وضعیت",) class Meta: verbose_name_plural = "رزرو ها" verbose_name = "رزرو" def __str__(self): return f'{str(self.booker_name)} - {self.booked_time} ** {self.confirmed}' and my booked_time is based on : class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,verbose_name="تاریخ فعال", null=True, blank=True,on_delete=models.CASCADE,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True, verbose_name="از ساعت",) free_hours_to = models.IntegerField(null=True, blank=True, verbose_name="الی ساعت",) status = models.BooleanField(null=True,default=True, verbose_name="آزاد است؟",) class Meta: verbose_name_plural = "سانس ها" verbose_name = "سانس" def __str__(self): return f'{str(self.free_date)} - {self.free_hours_from} الی {self.free_hours_to}' class AvailableDates(models.Model): free_date = jmodels.jDateField(null=True, verbose_name="تاریخ فعال",) status = models.BooleanField(choices=AVAILABLE_DATE_CHOICES,null=True,default=True, verbose_name="وضعیت",) class Meta: verbose_name_plural = "روزهای فعال" verbose_name = "روز فعال" def __str__(self): return f'{str(self.free_date)}' I cannot workout how to split my Dates and Hours fields in ModelForm. class BookingForm2(forms.ModelForm): class Meta: model = Bookings exclude = ('user','booking_code','confirmed',) def __init__(self,*args, **kwargs): super(BookingForm, self).__init__(*args, **kwargs) self.fields['booked_time'].queryset = AvailableHours.objects.filter(status=True) so in frontend user picks from a dropdown menu the AvailableDates then picks AvailableHours made in that model. Anyone can suggest a workaround ? -
djnago application cant see data from html
I have django application named emnosy (emergency notification system) when i try to use add_contact function from html i can see only that error IntegrityError at /addcontact/ ERROR: A null value in the "message" column violates the NOT NULL constraint DETAIL: The error line contains (2, booby, null, booby@gmail.com). Request Method: POST Request URL: http://127.0.0.1:8000/addcontact/ Django Version: 3.2.23 Exception Type: IntegrityError Exception Value: ERROR: A null value in the "message" column violates the NOT NULL constraint DETAIL: The error line contains (2, booby, null, booby@gmail.com). Exception Location: D:\projects\EmNoSy\venv\lib\site-packages\django\db\backends\utils.py, line 84, in _execute Python Executable: D:\projects\EmNoSy\venv\Scripts\python.exe Python Version: 3.7.9 Python Path: ['D:\\projects\\EmNoSy\\venv\\emnosys_wqrfl', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\python37.zip', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0', 'D:\\projects\\EmNoSy\\venv', 'D:\\projects\\EmNoSy\\venv\\lib\\site-packages'] Server time: Thu, 23 Nov 2023 15:50:47 +0000 i dont know how to fix that issue this is my addcontacts.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="../../static/emnosys/css/addcontacts.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="about"> <div class="label"> Add contact </div> <form action="" method="post"> {% csrf_token %} <div class="username"> <input name="about--username" id="about--username" placeholder=" " maxlength="40"></input> <label for="#about--username" id="username--label">Username for recipient (locally)</label> </div> <div class="textarea"> <textarea name="about--textarea" id="about--textarea" cols="30" rows="10" placeholder=" " maxlength="999"></textarea> <label for="#about--textarea" id="textarea--label">Message</label> </div> <div class="telegram" id="telegram--label"> <input name="about--email" id="about--email" placeholder=" … -
How Can I implement Dynamic Real Time Counter in Django
I have the following Django Models where I want to display real timer count down of the subscription (count down to the expiring Date) of every business account. I also have ajax code stored in my static/js folder where i referenced it on the base.html template. while in the index.html template I added a p tag with the countdown id but nothing is working. Someone should demonstrate the best way of achieving this in Django real time. Models: class BusinessAccount(models.Model): STATE_CHOICES = [ ('Benue', 'Benue'), ] LGA_CHOICES = [ ('Gboko', 'Gboko'), ] ACCOUNT_CHOICES = [ ('RICE MILL', 'RICE MILL'), ] name = models.CharField(max_length=100) account_type = models.CharField(max_length=100, choices=ACCOUNT_CHOICES, null=True) address = models.CharField(max_length=200, null=True) state = models.CharField(max_length=50, choices=STATE_CHOICES, null=True) lga = models.CharField(max_length=50, choices=LGA_CHOICES, null=True) subscription_plan = models.ForeignKey(Subscription, on_delete=models.CASCADE, null=True) is_active = models.BooleanField(default=False) created_date = models.DateField(auto_now_add=True) def subscription_countdown(self): if self.subscription_plan: expiration_date = self.subscription_plan.expiration_date remaining_time = expiration_date - timezone.now() return max(remaining_time, timedelta(0)) else: return timedelta(0) def __str__(self): return self.name class SubscriptionHistory(models.Model): business_account = models.ForeignKey(BusinessAccount, on_delete=models.CASCADE) plan = models.ForeignKey(SubscriptionPlan, on_delete=models.CASCADE) pin = models.UUIDField(default=uuid.uuid4, unique=True) start_date = models.DateField() expiration_date = models.DateField() def __str__(self): return f'Subscription for {self.business_account.name} \ ({self.plan.name})' My Ajax code in static/js folder: <script> // Fetch the updated countdown value from the server function … -
is there a relation cloud database and if there is can i use it as a backend database for my django projects?
is there a free relation cloud database and if there is can i use it as a backend database for my django projects and can you recommended one for free usage ..................................................................................................................................................................................................................................................................................................................................................................................................................... ? -
Django can't login after sign up using custom model
So i create a custom model with AbstractUser: class CustomUser(AbstractUser): email = models.EmailField(unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=False) # Validators should be a list is_shop = models.BooleanField(default=False) products = models.ManyToManyField('Product', blank=True) class Meta: db_table = "scrape_customuser" def save(self, *args, **kwargs): if not self.pk: self.set_password(self.password) super().save(*args, **kwargs) and a sign up form class UserForm(UserCreationForm): class Meta: model = CustomUser fields = ['username', 'email', 'phone', 'password1', 'password2'] my login logic: def shop_user_signup(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_shop = True user.save() login(request, user) referring_url = request.POST.get('next', None) if referring_url: return redirect(referring_url) else: return redirect('/') else: form = UserForm() return render(request, 'shop_user_signup.html', {'form': form}) The user got created in the database with password got hash to something like this pbkdf2_sha256$600000$TvRyCcSY6eMhnV1i1urh93$aKLqPBrcma5KsuS469crJtS93UI0h+7pduJXeW6ukAU=, is_active=1 and somehow the last login is 2023-11-23 15:49:22.581983 even though the redirect didn't show username when i have <li class="nav-item"> {% if user.is_authenticated %} <a class="nav-link" href="{% url 'logout' %}">{{user.username}} | Logout</a> {% else %} <a class="nav-link" href="{% url 'login' %}">Login</a> {% endif %} </li> When i try to login in the login page i got the … -
Authentication user from a different (external) Python program
I currently running a Django application and want to provide a completely different service using Python running on the same server. This won't be a web service. For this I also want to set up some level of authentication, and kind of want to use the credentials from the Users table in the Django application. Is there a function which I can call to verify the username and password? I'm very close to the solution, but not getting a clean response yet: import os, sys import Dashboard.settings from django.contrib.auth import authenticate os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Dashboard.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise 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?" ) from exc execute_from_command_line(sys.argv) user = authenticate(username="testuser", password="testpassword" ) if user is not None: print('Validated') else: # No backend authenticated the credentials print('wrong credentials') This does work, however, my output is the manage.py help menu followed by the output I want. Is there another command than execute_from_command_line(sys.argv) which I can use to mute the help menu? ... [sessions] clearsessions [staticfiles] collectstatic findstatic runserver Validated -
Filtering by distance without using postgis in django-filter
I've checked some answers related to my question but couldn't find solution. I have Foo and related FooAddress models. In django-filter I cannot filter Foo by distance, tried many options but no results. models.py class Foo(models.Model): pass class FooAddress(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name="address") longitude = models.DecimalField(max_digits=9, decimal_places=6) latitude = models.DecimalField(max_digits=9, decimal_places=6) filters.py from django_filters import rest_framework as filters from geopy.distance import distance class FooFilter(filters.FilterSet): point = filters.CharFilter(method="filter_by_distance") class Meta: model = Task fields = ["is_foo", "is_bar"] def filter_by_distance(self, queryset, name, value): point = value.split(",") if len(point) == 2: latitude = float(point[0]) longitude = float(point[1]) query_distance = self.data.get("distance") queryset = queryset.annotate( distance=distance( (latitude, longitude), (F("address_latitude"), F("address_longitude")) # accepts float or int ) ).filter(distance__lte=query_distance) return queryset In filters.py I tried to use geopy's distance method to calculate distance and it accepts float or real number but in my case I am giving F() type object that I cannot extract actual field value. Is there any way to figure out this without using postgis ? Or is it possible to do it with pure PostgreSQL query if yes how can it be done as I am not good at complex SQL queries. Thanks in advance. -
WINDOWS Could not build wheels for pyodbc, which is required to install pyproject.toml-based projects
Hello I having problems with this error: "Could not build wheels for pyodbc, which is required to install pyproject.toml-based projects" I don't know what to do! I searched and installed pyproject.toml and nothing! asgiref 3.7.2 attrs 23.1.0 Django 4.2.7 jsonschema 4.20.0 jsonschema-specifications 2023.11.1 mssql-django 1.3 pip 23.3.1 pyodbc 5.0.1 pyproject-toml 0.0.10 pytz 2023.3.post1 referencing 0.31.0 rpds-py 0.13.1 setuptools 69.0.2 sqlparse 0.4.4 toml 0.10.2 tzdata 2023.3 wheel 0.41.3 Python 3.12.0 -
Django server running on server instead running on local server when I hit on login
Django application is running on a server instead of the local server When I attempt to log in to Django application, it should normally run on your local development server (http://127.0.0.1:8000). However, if you notice that the login process redirects to a server, it might indicate an issue. url path('', auth_views.LoginView.as_view(template_name='frontend/auth-login.html'), name='login'), form <form class="form-horizontal" action="#" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for message in messages %} <div class="alert {{ message.tags }} mb-4 text-center" role="alert"> <strong>{{ message }}</strong> </div> {% endfor %} {{ form|crispy}} <div class="form-check text-start"> <input type="checkbox" class="form-check-input" id="auth-remember-check"> <label class="form-check-label" for="auth-remember-check">Remember me</label> </div> <div class="mt-3 text-end"> <button class="btn btn-primary w-sm waves-effect waves-light" type="submit">Log In</button> </div> <!---- <div class="mt-4 text-center"> <p class="mb-0">Don't have an account ? <a href="{% url 'register' %}" class="fw-medium text-primary"> Signup now </a> </p> </div>--> <div class="mt-2 text-center"> </div> </form> I have try to find view method in views and from in forms but their code not exist in that files -
Django nested formsets - 3 levels
I'm working on an app for construction company, and I want to create form for our daily schedule. For this I have 4 models: Date, DailySchedule, WorkersSchedule and MachinerySchedule. Each day we are working on several construction sites and we have 3-4 machines per CS and a few engaged workers on those sites. I'm trying to use inlineformset_factory with 3 levels of nesting, but without success: form (pick a date) formset0 (choose construction site) formset1 (choose employees) formset2 (choose machinery) date construction_site_1 employee_1 employee_2 machine_1 machine_2 machine_3 construction_site_2 employee_1 employee_2 machine_1 machine_2 machine_3 construction_site_3 employee_1 employee_2 employee_3 machine_1 machine_2 ... models.py class Date(models.Model): datum = models.DateField(blank=True, null=True) def __str__(self): return str(self.date) class DailySchedule(models.Model): date = models.ForeignKey(Date, on_delete=models.CASCADE, blank=True, null=True) construction_site = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.date) + ' --- ' + str(self.construction_site) class WorkersSchedule(models.Model): daily_schedule = models.ForeignKey(DailySchedule, on_delete=models.CASCADE, blank=True, null=True) employees = models.ForeignKey(Employees, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.daily_schedule) + ' --- ' + str(self.employees) class MachinerySchedule(models.Model): daily_schedule = models.ForeignKey(DailySchedule, on_delete=models.CASCADE, blank=True, null=True) machinery = models.ForeignKey(Machinery, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.daily_schedule) + ' --- ' + str(self.machinery) forms.py class DateForm(ModelForm): class Meta: model = Date fields = "__all__" views.py def daily_schedule_form(request): date = Date() … -
Format datefield in Django Report with reportlab
In my Django App I have an app to generate a reportlab report based on simpledoctemplates. To create the table inside the report I read the data with a value_list query to handover the queryset to the data variable for the table. teilnehmer_alle = Teilnehmer.objects.filter( teilnehmer_sprung__gt=0, teilnehmer_geburtsjahr__range=[riege.riege_ab, riege.riege_bis]).values_list('id', 'teilnehmer_name', 'teilnehmer_vorname', 'teilnehmer_verein__verein_name_kurz', 'teilnehmer_geburtsjahr', 'teilnehmer_sprung' ) and here is the handover to the table: headers = ['Start-Nr.', 'Nachname', 'Vorname', 'Verein', 'Jahrgang', 'Meldung', 'A-Note', 'B-Note', 'Summe'] table_data = [headers] + [list(row) + [''] * (len(headers) - len(row)) for row in teilnehmer_alle] if table_data: t = Table(table_data) content.append(t) everything works fine, but the value of the 'teilnehmer_geburtsjahr' isn't in the format I want to use. Currently it is 'YYYY-mm-dd' but I want only the year information in the report. Is there a way to change this inside the queryset? Or is there another solution? Any ideas? I'have tried to change the queryset without "values" or "value_list" but I didn't find a solution to change the format before I create the table. -
django asgi/channels not deployment failing
I currently have a Django ASGI project that runs well locally, but when I try to deploy it on Render or Railway, I encounter an error. Below are my build script (build.sh), Procfile, and relevant sections: My Asgi.py import django import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application django.setup() from chat.routing import websocket_urlpatterns from hometweet.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "root.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) **Build Script (`build.sh`):** #!/bin/bash # Upgrade pip and setuptools pip install --upgrade pip pip install --upgrade setuptools # Install Dependencies pip install -r requirements.txt # Run Migrations python manage.py makemigrations user python manage.py makemigrations hometweet python manage.py makemigrations profiles python manage.py makemigrations groupapp python manage.py migrate **Procfile** gunicorn root.asgi:application -k uvicorn.workers.UvicornWorker. I've tried various start commands, including: web: daphne -u /tmp/daphne.sock yourproject.asgi:application web: gunicorn root.wsgi:application gunicorn root.wsgi:application web: gunicorn root.asgi:application gunicorn root.asgi:application web: gunicorn root.asgi:application -k uvicorn.workers.UvicornWorker The last command is currently giving me a server error when attempting to access the page. is there something i need to change or add please. Please someone should help me out on how i can deploy it … -
random.choice() in form placeholder doesn't work how we expect
We used random.choice() to show random placeholders in an entry form. class EntryForm(forms.ModelForm): class Meta: my_placeholders = ['The fact that...', 'I am sure that...', 'It is awesome to...', 'I wish this was...', 'I always wanted to know how...', 'The reason I am writing this is...' ] my_placeholders_random = random.choice(my_placeholders) model = Entry fields = ['text'] labels = {'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': 80, 'placeholder': my_placeholders_random})} This works, but only if the local server is stopped using CTRL-C and restarted with python manage.py runserver or when we make changes in the file and save it. In those cases another placeholder is displayed. However, when the server is running, and we refresh the entry page a couple of times, the placeholder stays the same every time. In what way can we make sure the placeholder will be changed after every refresh? -
i cant show the image in detail page
views.py title = request.POST.get('Title') description = request.POST.get('Description') image = request.FILES.get('image') Course.objects.create(title=title, description=description, image=image) .html <form action="" class="form-control" method="post"> {% csrf_token %} <input class="form-control" name="Title" placeholder="Enter Title"> <input name="Description" class="form-control" placeholder="Enter Description"> <input name="image" class="form-control" type="file" formenctype="multipart/form-data" placeholder="Upload the image"> <button type="submit" class="btn btn-primary" style="margin-top: 10px">Submit</button> </form> detail page <img src="{{course.image.url }}" alt=""> I create the object but the image does not show in detail page how i can show the image of the object -
How to use a variable as character length parameter inside a regular expression [duplicate]
I have a regular expression pattern to find words longer than a certain amount of characters: pattern = r"\w{14,}" where i want the 14 to be dynamic. How can i insert a variable as a character length parameter inside a regular expression? I tried with no success: length = 14 pattern = re.compile(r"\w{" + str(length) + ",}") The pattern is then used as a query in a Django model as: module_list = Contentmodule.objects.filter( # Q(json__text__iregex = r"\w{14,}") Q(json__text__iregex = pattern) ) and i get the error: sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. -
why doesn't the clean method see field in forms?
I'm facing an issue with my forms in Django. I've created something like this: class EventForm(forms.ModelForm): class Meta: model = Event fields = [ "name", "start_date", "end_date" ] def clean(self): start_date = self.cleaned_data["start_date"] end_date = self.cleaned_data["end_date"] if start_date > end_date: raise ValidationError("Start Date cannot be great than End Date") elif start_date == end_date: raise ValidationError("The dates must be different.") def clean_start_date(self): start_date = self.cleaned_data["start_date"] if timezone.now() > start_date: raise ValidationError("The start date of the event must be after today.") return start_date When I tried to test it, something weird is happening. So, when I tried to input a start_date that is after today, I get the following message: start_date = self.cleaned_data["start_date"] KeyError: 'start_date' It looks like clean() doesn't see the start_date. But why?