Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get serializer data by foreign key
I need to pass data from EmployeeSerializer to VacationSerializer as nested json. This is my serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'first_name', 'surname', 'patronymic', 'birthday', 'email', 'position', 'phone_number') class VacationSerializer(serializers.ModelSerializer): class Meta: model = Vacation fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee') and my models.py: class Employee(models.Model): first_name = models.CharField("Name", max_length=50) surname = models.CharField("surname", max_length=50) patronymic = models.CharField("patronymic", max_length=50) birthday = models.DateField() email = models.EmailField() position = models.CharField("position", max_length=128) phone_number = models.CharField("phone", max_length=12, null=True) is_deleted = models.BooleanField(default=False) def __str__(self): return f'{self.surname} {self.first_name} {self.patronymic}' class Vacation(models.Model): start_date = models.DateField() end_date = models.DateField() employee_id = models.ForeignKey(Employee, related_name='employee', on_delete=models.PROTECT, default=-1) def __str__(self): return f'{self.start_date} - {self.end_date}' @property def date_diff(self): return (self.end_date - self.start_date).days in views.py I have this: @api_view(['GET', 'POST']) def vacations_list(request): if request.method == 'GET': data = Vacation.objects.all() serializer = VacationSerializer(data, context={'request': request}, many=True) return Response(serializer.data) I've tried this: class VacationSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(read_only=True, many=True) class Meta: model = Vacation fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee') but it doesn't show me even empty nested json, it shows me only VacationSerializer data. I easily can access VacationSerializer from EmployeeSerializer using PrimaryKeySerializer or any other serializer and get nested json where VacationSerializer data is nested in EmployeeSerializer data. … -
I am getting error on user login and registration in django
Hi, I have a project with django, database mysql, I'm getting an error in user login and registration process. Could it be from the database, do I need to code it differently because it's mysql? my codes and error message are attached ` `` ` ` def signupPage(request): if request.method == "POST": Formusername = 'username' in request.POST Formemail = 'email' in request.POST Formpassword = 'password' in request.POST Formrepassword = 'repassword' in request.POST if Formpassword == Formrepassword: if User.objects.filter(username=Formusername).exists(): return render(request,"signup.html",{"error":"username already taken","username":Formusername}) else: if User.objects.filter(email=Formemail).exists(): return render(request,"signup.html",{"error":"email already taken","email":Formemail}) else: user = User.objects.create_user(username=Formusername,email=Formemail,password=Formpassword) user.save() return redirect("signin") else: return render(request,"signup.html",{"error":"passwords do not match!"}) return render(request,"signup.html") def signinPage(request): if request.method == "POST": username = 'username' in request.POST password = 'password' in request.POST user = authenticate(request,username = username,password = password) if user is not None: login(request, user) return redirect("home") else: return render(request,"account/signin.html",{"error":"username or password wrong"}) return render(request,"signin.html") def logoutPage(request): return redirect("home") ` < `ValueError at /account/signup The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/account/signup Django Version: 4.1.3 Exception Type: ValueError Exception Value: The given username must be set Exception Location: C:\Users\merte\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\models.py, line 144, in _create_user Raised during: account.views.signUpUser Python Executable: C:\Users\merte\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Python Path: ['C:\\Users\\merte\\Desktop\\İş-Güç\\Orders\\order', 'C:\\Users\\merte\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\merte\\AppData\\Local\\Programs\\Python\\Python311\\Lib', … -
403 Forbidden media file django, nginx, aws
The images are not displayed in my project. If the static files. This is how my nginx configuration looks server{ listen 80; server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /var/www/html/static/; } location /media/ { autoindex on; alias /home/user/project/var/www/html/media; } location / { include proxy_params; proxy_pass http://ip:8000; } my settings.py DEBUG = False MEDIA_ROOT ='var/www/html/media' MEDIA_URL = '/media/' the permmission this path: /home/user/project/var/www/html/media drwxrwxr-x 3 www-data www-data I need the images to be displayed to the user or other solutions with other services with aws. -
Django Models Reverse Lookup
I am trying to normalize my models in Django. I have three models as below from django.db import models class Province(models.Model): province = models.CharField(max_length=20, blank=False, null=False) def __str__(self): return province class District(models.Model): district = models.CharField(max_length=20, blank=False, null=False) province = models.ForeignKey('Province', related_name='district_province', on_delete=models.CASCADE) def __str__(self): return district class School(models.Model): school = models.CharField(max_length=20, blank=False, null=False) district = models.ForeignKey('District', related_name='school_district', on_delete=models.CASCADE) def __str__(self): return self.school When I query the school model I can get the District, My question is, is it possible to also get the province without adding it as a foreign key in the School model? if yes, how do I achieve that? The Use cases are: Query a school with all its properties including district and province. With: School.objects.all or School.objects.get/filter I can get all schools and the district details but I do not know how to reach the province model. Get all schools in a District With: School.objects.filter(district=x) I can get schools in a district with no problem here. Get all schools in a Province Say I have province ID as 2, how do I get all schools in province 2? Thanks for any help given. -
I want to upload folder and subfolder with files in Django
HTML CODE <div class="input-group"> <input type="file" id="folder-upload-newtask" onchange="selectFolder(event)" webkitdirectory mozdirectory msdirectory odirectory directory multiple name="folder_name" tabindex="2"/> <label for="folder-upload-newtask">Choose Files</label> </div> Folder MainFolder --- FirstSubfolder -- (1.xlsx, 2.xlsx) SecondSubfolder -- (1.xlsx, 2.xlsx, 3.xlsx) ThirdSubfolder -- (1.xlsx, 2.xlsx, 3.xlsx, 4.xlsx) And inside subfolder excel file name same with different content. so I want to save all data in MEDIA_ROOT with correct format. -
Django forms useless div tag
I am getting one problem while using django forms. Actually When I am using RadioSelect widget it is giving unnecessary div tags. Means each radio button is separated with individual div tag. And I don't want that. Please help Image of Div tags for each label How can I get those label and input tag i.e Radio Buttons in single div tag not these many index.html forms.py -
How to send email on smtp server in django?
here is m settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAL_HOST_USER = 'test.mailed.login@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 Google used to have a less-secure apps settings now that it is removed, I am using this alternatively I obviously went on a google and created a new app and filled it on the EMAIL_HOST_PASSWORD I also enabled two step authentication Obviously i changed my app password on the above code so no one can see it I imported send_mail and run the function but it still sending me this error error details This is exactly what I have done nothing more or nothing less Every youtube video that I check it is working for all of them, Am I missing an earlier step -
Getting valueError : invalid literal for int() with base 10:''
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/store Django Version: 4.1.3 Python Version: 3.10.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store'] 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\acer\PycharmProjects\Eshop\store\templates\index.html, error at line 40 invalid literal for int() with base 10: '' 30 : <div class="card mx-auto mb-3" id={{product.id}} style="width: 18rem;"> 31 : <img class="card-img-top" src="{{product.image.url}}" alt="Card image cap"> 32 : <div class="card-body"> 33 : <p class="card-title">{{product.name}}</p> 34 : <p class="card-text"><b>{{product.price|currency}}</b></p> 35 : 36 : </div> 37 : 38 : <div class="card-footer p-0 no-gutters"> 39 : 40 : {% if product|is_in_cart:request.session.cart %} 41 : <div class="row no-gutters"> 42 : <form action="/#{{product.id}}" class="col-2 " method="post"> 43 : {% csrf_token %} 44 : <input hidden type="text" name='product' value='{{product.id}}'> 45 : <input hidden type="text" name='remove' value='True'> 46 : <input type="submit" value=" - " class="btn btn-block btn-success border-right"> 47 : </form> 48 : <div class="text-center col btn btn-success">{{product|cart_quantity:request.session.cart}} in Cart</div> 49 : <form action="/#{{product.id}}" class="col-2 " method="post"> 50 : {% csrf_token %} Traceback (most recent call last): File "C:\Users\acer\PycharmProjects\Eshop\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\acer\PycharmProjects\Eshop\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\acer\PycharmProjects\Eshop\store\views\home.py", line 57, in store return render(request, 'index.html', data) File … -
502 bad gateway error with django , gonicorn in ubuntu server
i got these error 502 bad gateway when cheched error.log i got when i checked goicorn the nginex services is run but after check i got this error this is my code in nginx/site-avalable upstream keepalive-upstream { server 127.0.0.1:8000; keepalive 64; } server { listen 80; listen [::]:80; server_name qhse-erp.com www.qhse-erp.com; location / { proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://keepalive-upstream; proxy_redirect off; } } -
Django: objects.raw() resulting query but not records
I'm django newbie, I have one fundamental and one technical questions. I'm using Postgres DB. I used psycopg2 connection/cursor for fetching the data, there was some delay while establishing a connection. I read that, ORM takes care of low level activities such as establishing a connection, etc. If I use django, ORM will takes care of connection challenge ? 1.1. Can I expect same (low level activities) with raw() as well? objects.raw(sql) returning Query but not records from the table. I defined Student Model as below class Student(models.Model): firstname = models.CharField(max_length=100) surname = models.CharField(max_length=100) def __str__(self): return self.firstname While creating the view, def studentList(request): #posts = Student.objects.all() --> 1. working as expected (fetching all records firstname) cursor = connection.cursor() sql = "select * from api_student" cursor.execute(sql) posts = cursor.fetchone() --> 2. returning entire record #posts = Student.objects.raw(sql) --> 3. RETURNING SQL QUERY NOT RECORD FROM TABLE ??? print(posts) return render(request, 'output.html', {'posts':posts}) output: <QuerySet [<Student: Anil>]> <RawQuerySet: select * from api_student> --> this is the challenge, did I miss any ('Anil', 'kumar') -
Chart.js automatic background color selector on Django app
I'm working on a Django app with chart.js charts and I'm trying to use a function to automatically change the colors of all the labels. Although when I run the app it only colors one label and makes the other transparent. I tried changing it from labels to data and was getting the same result. It's difficult to share the code as it is pulling data from the app so I'll share what I can. Here is the random color generator code: const labels = ['Category Types']; const backgroundcolor = []; const bordercolor = []; for (i = 0; i < labels.length; i++) { const r = Math.floor(Math.random() * 255); const g = Math.floor(Math.random() * 255); const b = Math.floor(Math.random() * 255); backgroundcolor.push("rgba(" + r + ", " + g + ", " + b + ", 1)"); bordercolor.push("rgba(" + r + ", " + g + ", " + b + ", 1)"); } Here is the chart code: var categoryTypes = JSON.parse(document.getElementById('category_types').textContent) var transactionAmountSum = JSON.parse(document.getElementById('transactionAmountSum').textContent) console.log('categoryTypes', categoryTypes) console.log('transactionAmountSum', transactionAmountSum) $(document).ready(function() { var ctx = document.getElementById('myChart1').getContext('2d'); var myCategory = new Chart(ctx, { type: 'pie', data: { labels: categoryTypes, datasets: [{ label: 'Category Types', data: transactionAmountSum, backgroundColor: [backgroundcolor], borderColor: … -
Download TikTok mp4 on client-side in Django App
I am working on an app and want to download a TikTok video given a URL on the client's machine. I have tried the following to no avail. I would like to do this in as lightweight a manner as possible and with libraries that are popular and maintained, if possible. The issues I have gotten for the attempts are provided therein. Using https://github.com/davidteather/TikTok-Api While this works locally, it does not work when I deploy the application, as I get issues with the threading. I copied over the code from this library and messed around with the threading, but it still did not work fully. I would like to avoid this option as it is not super maintainable. Using requests/wget I get the following issue when trying to use wget: Error downloading video: 'ascii' codec can't decode byte 0xe2 in position 248: ordinal not in range(128) [11/Dec/2022 05:10:13] "GET /downloader/https://www.tiktok.com/@patrickzeinali/video/7143758925349784874?is_copy_url=1&is_from_webapp=v1&item_id=7143758925349784874&lang=en HTTP/1.1" 200 24 This is what the current files look like: downloader/urls.py from django.urls import re_path, path from . import views urlpatterns = [ path('<path:video_url>', views.download_video, name='download_video'), ]` downloader/views.py from django.http import HttpResponse import ENV_VARS import requests import wget def download_video(request, video_url): print(f'Received request for video at URL: {video_url}') # … -
getting Keyerror on updating nested serializer in DRF
I have two serializer AccountSerializer UserProfileSerializer. user in UserProfileSerializer is Foreingkey to AccountSerializer. When I try to update UserProfileSerializer I get key error confirm_password. That is actually validation in AccountSerializer. How to prevent this. #Serializer class AccountSerializer(ModelSerializer): confirm_password = CharField(write_only=True) class Meta: model = Account fields = ["first_name", "last_name", "email", "password", "confirm_password"] extra_kwargs = { "password": {"write_only": True}, } def validate(self, data): if data['password'] != data.pop("confirm_password"): raise ValidationError({"error": "Passwords donot match"}) return data def create(self, validated_data): user = Account.objects.create_user(**validated_data) return user class UserprofileSerializer(ModelSerializer): user = AccountSerializer() class Meta: model = UserProfile fields = "__all__" def update(self, instance, validated_data): user_data = validated_data.pop('user', None) print('user_data', user_data) account = instance.user account.first_name = user_data.get('first_name', account.first_name) account.last_name = user_data.get('last_name', account.last_name) account.email = user_data.get('email', account.email) account.save() return super().update(instance, validated_data) #Error -
How to declare type for related object in django
In views.py I am creating products based on queryset and I don't know how to assign type to wz_product to get hints of appropriate variables. product_qs: List[Product] = product.orderproduct_set.all() for product in product_qs: product_serializer = ProductModelSerializer( data={"og_product": product.wz_product.og_product.id}) In VSC it looks like this: (in the question, I changed the names of the variables to make it easier to understand) -
Django Channels await database_to_async method not working
I'm trying to build a notification application by using Django Channels. The problem I'm having is the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. consumers.py class NotificationConsumer(AsyncJsonWebsocketConsumer): @database_sync_to_async def get_notifications(self, user): new_messages = NotificationSerializer(Notification.objects.filter(content=1, users_notified__in=[user]), many=True) notifs = { "new_messages": new_messages } return notifs async def connect(self): user = self.scope["user"] if user: self.channel_name = user.username self.room_group_name = 'notification_%s' % self.channel_name # Error happens in the following line notification = await self.get_notifications(self.scope["user"]) print("Notification", notification) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.disconnect(401) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def notify(self, event): await self.send_json(event["content"]) I have used the exact same approach when I developed a Django Channels chat application that saves messages to the database as well. When trying to convert my approach to the Notification system, it doesn't anymore. As soon as I don't await the self.get_notifications method anymore, it works but I only get back a <coroutine object SyncToAsync.__call__ at ...> -
Password field does not migrate to db
I have my user app with the following fields in its models.py file: from django.db import models from django import forms # Create your models here. class User (models.Model): name=models.CharField(max_length=50, verbose_name='Name') surname=models.CharField(max_length=50, verbose_name='Surname') username=models.CharField(max_length=50, unique=True, verbose_name='Username') password=forms.CharField(widget=forms.PasswordInput()) email=models.EmailField(unique=True, verbose_name='Email') When I do the migrations with python manage.py makemigrations does not migrate the password field, am I defining it wrong with form.CharField? -
Django - Get specific columns with get_object_or_404()
Is there a way to only get specific columns from the database using the get_object_or_404()? This is my query for getting the thesis information from my database. But I only want to return the title , author, and published date instead of all the columns from that specific thesis. details = get_object_or_404(thesisDB, slug=slug, published_status='Approved') -
scheduler library is not working with function-based view in django
`I am working on functional based view in django and I want to schedule a task for every few minutes. I am scheduling task using "schedule" library [pip install schedule]. when i am executing the task i am getting an error as : TypeError: home() missing 1 required positional argument: 'request'. If i try to pass some string in request parameter I get error as : AttributeError: 'bool' object has no attribute 'META' what shall i pass in "request" parameter ?` from django.shortcuts import render import requests import json import schedule import time def home(request): print("Scheduler working") res = requests.get("https://jsonplaceholder.typicode.com/posts").json() return render(request, "home.html", {'res':res}) schedule.every(5).seconds.do(home) #TypeError: home() missing 1 required positional argument: 'request' #schedule.every(5).seconds.do(home(request=True) #AttributeError: 'bool' object has no attribute 'META' (if try to pass some parameter such as string or bool or int) while True: schedule.run_pending() time.sleep(1) -
In django is there a way to access the selected ForeignKey field value in a ModelForm to filter another ForeignKey in the form?
In django 4.1.3 Trying to filter a ForeignKey field query using another selected ForeignKey field value in a ModelForm to limit the filter depending on the selected exhibitors corresponding id. from django import forms from .models import Entry, Exhibitor, Pen class EntryForm(forms.ModelForm): class Meta: fields = ('exhibitor', 'pen', 'class_id',) def __init__(self, *args, **kwargs): super(EntryForm, self).__init__(*args, **kwargs) # Can't figure out how to filter # Using the selected exhibitor field value self.fields['pen'].queryset = Pen.objects.filter(current_owner_id=1) # where 1 should be the exhibitor_id # using an int value for the current_owner_id works to filter the query # but don't know how to access selected field values, or would this work in a pre_save function? # tried self.fields['pen'].queryset = Pen.objects.filter(current_owner_id=self.fields['pen']) TypeError at /admin/exhibitors/entry/add/ Field 'id' expected a number but got <django.forms.models.ModelChoiceField object at 0x2b630a6b2100>. -
Django request issue - JSON parse error - Expecting value: line 1 column 1 (char 0)
I am trying to request an access token using the following function and calling to my Django backend. On the django interface I am able to get the access and refresh token. However when I try to call it through python I get the response: {'detail': 'JSON parse error - Expecting value: line 1 column 1 (char 0)'}. Also I am using the pre-built Django Token View and have not modified it. def get_authtoken(username, password): headers = {'content-type': 'application/json'} data = { "username": username, "password": password } response = requests.post('http://127.0.0.1:8000/api/token/', data=data, headers=headers) response = response.json() print(response) return response["access"], response['refresh'] At first I was getting another issue saying the content type is not allowed. I then added the headers to clear that up an now I am running into this problem. When I research the error the solutions either do not apply or do not work. Any help is appreciated. -
How to get username field automatically in Django
I am working on a Django project which is something similar to Fiverr in its working. I have used abstractuser where there is a buyer and seller. The seller creates a gig then the buyer will go through the gig before placing an order. My issue is how to get the seller and place him in the order that the buyer will create from reading the gig. Currently I am using the system whereby the buyer will have to manually choose a gig from a list, which I think is not effective. Here is my Models.py `class User(AbstractUser): is_buyer=models.BooleanField(default=False) is_seller=models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='avatar.jpg', null=True, blank=True) about = models.CharField(max_length=100) def __str__(self): return self.user.username class Gig(models.Model): seller = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False) category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False) title = models.CharField(max_length=500, null=True, blank=True) description = models.CharField(max_length=500, null=True, blank=True) gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Order(models.Model): buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False) seller = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='+', null=False, blank=False) title = models.CharField(max_length=500, null=True, blank=True) description = models.CharField(max_length=500) amount = models.IntegerField(max_length=50, blank=False) is_ordered = models.BooleanField(default=False) order_id = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False) slug = models.SlugField(null=True) def __str__(self): … -
The right way to dynamically add Django formset instances and POST usign HTMX?
I'm making a form with a nested dynamic formset using htmx i (want to evade usign JS, but if there's no choice...) to instance more formset fields in order to make a dynamic nested form, however when i POST, only the data from 1 instance of the Chlid formset (the last one) is POSTed, the rest of the form POSTs correctly and the Child model gets the relation to the Parent model I read the django documentation on how to POST formset instances and tried to apply it to my code, also i got right how to POST both Parent and Child at the same time. For the formsets i'm making a htmx get request hx-get to a partial template that contains the child formset and that works great, the only problem is that this always returns a form-0 formset to the client side, so for the POST the data repeats x times per field and only takes the data placed in the last instance, however i tried to change the extra=int value on my formset to get more forms upright, this gave the expected result, one Child instance per form in extra=int, so my problem is up with htmx … -
Sum the values of a form and add that result to the database
I want to make a form that has 3 number radio values, supposedly look like this: And I'd like for those 3 values to sum and display the sum of those values to then save them into the database. forms.py: class FormTest(forms.Form): CHOICES = [ ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ] num1 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) num2 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) num3 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) total = num1 + num2 + num3 models.py: class Test(models.Model): num1 = models.IntegerField() num2 = models.IntegerField() num3 = models.IntegerField() class Dato(models.Model): dato = models.IntegerField() views.py: def formtest(request): """ if request.method == 'GET': return render(request, 'testform.html', { 'form': FormTest() }) else: Test.objects.create( num1=request.POST["num1"], num2=request.POST["num2"], num3=request.POST["num3"] ) return redirect('forms') """ if request.method == 'GET': return render(request, 'testform.html', { 'form': FormTest(), }) else: Dato.objects.create( dato=request.POST['dato'] ) return redirect('forms') testform.html: {% extends 'layouts/base.html' %} {% block content %} <h1>Test Form</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button>Save</button> </form> {{ totalsum }} {% endblock %} urls.py: from django.urls import path from . import views urlpatterns = [ #path('', views.index), path('', views.index, name="index"), path('about/', views.about, name="about"), path('hello/<str:username>', views.hello, name ="hello"), path('projects/', views.projects, name="projects"), path('tasks/', views.tasks, name="tasks"), path('create_task/', views.create_tasks, name="create_task"), path('create_projects/', views.create_project, name="create_projects"), path('formtest', views.formtest, … -
How to update Django custom dashboard
I am building a custom dashboard that will only be accessible to the support team of a company. These support teams will receive complaints from a contact form but we want to be able to indicate each complaint that has been resolved from the dashboard as resolved after being attended to. Therefore, I created a field of choices (pending and resolved) which I named status. This field is not exposed to the user in the contact form and on the backend, it's 'pending' by default. See the contact model as shown below class Contact(models.Model): STATUS_CHOICE = ( ("1", "Pending"), ("2", "Resolved"), ) name = models.CharField(max_length=100) phone = models.CharField(max_length=15) email = models.EmailField(max_length=254) subject = models.CharField(max_length=100) status = models.CharField(choices=STATUS_CHOICE, default="1", max_length=50, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) body = models.TextField() class Meta: ordering = ["-created"] verbose_name_plural = "Contacts" def __str__(self): return f"Message from: {self.name}" see my forms.py: class ContactForm(forms.Form): name = forms.CharField(max_length=100, required=True) phone = forms.CharField(max_length=15, required=True) email = forms.EmailField(max_length=100, required=True) subject = forms.CharField(max_length=100, required=True) body = forms.CharField(required=True, label='Message', widget=forms.Textarea()) class Meta: model = Contact fields = ['name', 'phone', 'email', 'subject', 'body'] captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) The intent of the view below is to ensure that all users that contact the company using the … -
Django DeleteView SuccessMessageMixin -- how to pass data to message?
I am using SuccessMessageMixin on a CreateView and DeleteView. In the CreateView, I can send the book title to the success_message, like so: success_message = "%(title)s added successfully" Which correctly flashes "Great Expectations added successfully" on the success url. But in DeleteView, I can't access the title. I can send a generic message saying "book deleted", but I can't send a message saying "Great Expectations has been deleted". Is there a way that I can pass info about what's being deleted to the success_message?