Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting a no such column error only when running tests
Perhaps this is leaving out some key detail and exposing my relative newness to django, but I tried to isolate my issue to the fewest steps to reproduce the problem. Starting state: App running fine, tests all passing. Add one nullable column to an existing model. makemigrations migrate New state: App runs fine, running tests produces an error. Creating test database for alias 'default'... Found 23 test(s). Installed 5 object(s) from 1 fixture(s) Traceback (most recent call last): File "/home/f/.virtualenvs/mgmt/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/f/.virtualenvs/mgmt/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: recommended_for_text recommend_for_text is the name of the new column. recommended_for_text = models.CharField(null=True, blank=True, max_length=256) It shows up in my view in the app as expected, just running the tests is causing me an issue. -
Why is django class-based_view not seeing my uploads?
class MultipleFileInput(forms.ClearableFileInput): """ Work around for `widget=forms.ClearableFileInput(attrs={'multiple': True})` >> `widget=MultipleFileInput(attrs={'multiple': True})` """ input_text = 'Select' clear_checkbox_label = 'Clear' initial_text = 'Current' allow_multiple_selected = True class UserUploadForm(forms.ModelForm): file = forms.FileField( widget=MultipleFileInput(attrs={'multiple': True}), required=True, validators=[FileExtensionValidator(allowed_extensions=['csv'])], ) class Meta: model = UserUpload fields = ['file'] class MyFilesView(FormView): template_name = 'data_related/my_files.html' form_class = UserUploadForm success_url = reverse_lazy('my_files') def post(self, request, *args, **kwargs): self.object = None form = self.get_form() files = self.request.FILES.getlist('file') print(files) print("Files received:", request.FILES.getlist('file')) # Debug output to confirm files are received if form.is_valid(): print("Form is valid") # Debug statement return self.form_valid(form) else: print("Form is not valid") # Debug statement for field, errors in form.errors.items(): for error in errors: print(f"Error in {field}: {error}") messages.error(request, f"Error in {field}: {error}") return self.form_invalid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_files = UserUpload.objects.filter(user=self.request.user) files = [{'short_name': file.file.name, 'file_size': file.file_size, 'uuid': file.uuid} for file in user_files] # Pagination paginator = Paginator(files, 10) # Show 10 files per page page_number = self.request.GET.get('page') page_obj = paginator.get_page(page_number) context.update({ 'user_files': files, 'page_obj': page_obj, 'form': self.get_form(), #form_class((self.request.POST, self.request.FILES) or None) # show UserUploadForm, must instantiate form with POST and FILES }) 2024-04-26 03:53:45 [] 2024-04-26 03:53:45 Files received: [] 2024-04-26 03:53:45 Form is not valid 2024-04-26 03:53:45 Error in file: This field is … -
Filtering DataFrames in a Django Dashboard
I am trying to build a Dashboard with Django... I wish to filter the dashboard with category, month and Year. The dataFrame is coming from python code than I am adding the charts with JS. I don't know how to proceed to be able to filter it as I want. views.py: def get_expense_api_data(request, *args, **kwargs): sort_order = ['January','February','March','April','May','June','July','August','September','October','November','December'] exp_df = pd.DataFrame(Expenses.objects.filter(user=request.user).all().values('date_created', 'amount')) categories = dict() if exp_df.empty: default_items_exp = [0] labels_exp = [0] else: categories['expenses'] = pd.unique(pd.DataFrame(Expenses.objects.filter(user=request.user).all().values('categories')).categories.values).tolist() exp_df['date_created'] = pd.to_datetime(exp_df['date_created']) exp_df = pd.DataFrame(exp_df.groupby(exp_df['date_created'].dt.strftime('%B'))['amount'].sum()) exp_df["date_created"] = exp_df.index exp_df.index = pd.CategoricalIndex(exp_df["date_created"], categories=sort_order, ordered=True) exp_df = exp_df.sort_index().reset_index(drop=True) default_items_exp = exp_df.amount.tolist() labels_exp = exp_df.date_created.tolist() inc_df = pd.DataFrame(Incomes.objects.filter(user=request.user).all().values('date_created', 'amount')) if inc_df.empty: default_items_inc = [0] labels_inc = [0] else: categories['incomes'] = pd.unique(pd.DataFrame(Incomes.objects.filter(user=request.user).all().values('categories')).categories.values).tolist() inc_df['date_created'] = pd.to_datetime(inc_df['date_created']) inc_df = pd.DataFrame(inc_df.groupby(inc_df['date_created'].dt.strftime('%B'))['amount'].sum()) inc_df["date_created"] = inc_df.index inc_df.index = pd.CategoricalIndex(inc_df["date_created"], categories=sort_order, ordered=True) inc_df = inc_df.sort_index().reset_index(drop=True) default_items_inc = inc_df.amount.tolist() labels_inc = inc_df.date_created.tolist() try: net_df = pd.merge(inc_df, exp_df, how='outer', on='date_created') net_df = net_df.fillna(0) net_df['amount'] = net_df['amount_x'] - net_df['amount_y'] net_df.index = pd.CategoricalIndex(net_df["date_created"], categories=sort_order, ordered=True) net_df = net_df.sort_index().reset_index(drop=True) default_items_net = net_df.amount.tolist() labels_net = net_df.date_created.tolist() except KeyError: if inc_df.empty: net_df = exp_df elif exp_df.empty: net_df = inc_df net_df.index = pd.CategoricalIndex(net_df["date_created"], categories=sort_order, ordered=True) net_df = net_df.sort_index().reset_index(drop=True) default_items_net = net_df.amount.tolist() labels_net = net_df.date_created.tolist() savings_df = pd.DataFrame(Savings.objects.filter(user=request.user).all().values('date_created', 'amount')) if savings_df.empty: … -
raise ImproperlyConfigured("SECRET_KEY setting must not be empty")django.core.exceptions.ImproperlyConfigured:The SECRET_KEY setting must not empty
I published my Django project into github and I had a lot of variables that stored in .env for secure. And when anyone clone that project and migrate its not reading variables in my .env file that saved in .gitignore. is there any solution without showing these value of the variables, or it's ok and no danger to show this info? ``` import os from pathlib import Path from dotenv import load_dotenv load_dotenv() SECRET_KEY = os.getenv('SECRET_KEY') CURRENT_HOST = os.getenv('CURRENT_HOST') DATABASE_NAME = os.getenv('DATABASE_NAME') DATABASE_USER = os.getenv('DATABASE_USER') DATABASE_PASSWORD = os.getenv('DATABASE_PASSWORD') DATABASE_HOST = os.getenv('DATABASE_HOST') DATABASE_PORT = os.getenv('DATABASE_PORT') HOST_EMAIL = os.getenv('EMAIL_HOST') EMAIL_USER = os.getenv('EMAIL_HOST_USER') EMAIL_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') PORT_EMAIL = os.getenv('EMAIL_PORT') EMAIL_TLS = os.getenv('EMAIL_USE_TLS') SOCIAL_AUTH_GOOGLE_KEY = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_SECRET = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') ``` .gitignore has .env inside, So I thought that it's may be related to the one in my device. I know that it's impossible but i did not find any solution so i hope that anyone can help me, Thanks. -
html button not work on each click - hot to debug it? (chrome)
I've got a (django) app, that displays a page with videojs-record, with ability to record something and send to backend. In general both recording and sending works fine. But - after recording there is a button to send (button with id=submit), and the click there works sometimes immediately, sometimes, I need to click it two or three times, to make it work. After sending, the button is hidden, and another one is showed to move to next question. And the behaviour is similar - it works sometimes, and sometimes needs to be clicked couple of times. I've no idea how to debug it... {{questionText}} <video id="myAudio" playsinline class="video-js vjs-default-skin"></video> <button class="btn btn-sm btn-primary" id="submit" disabled>sent</button> <a href="{% url 'video2_module:NextQuestion' %}" id="next" style="display: none;" class="btn btn-sm btn-primary" >next-> </a> <input type="hidden" id="myVar" name="variable" value="{{ file_name }}"> <script> $(document).ready(function () { var options = { controls: true, bigPlayButton: false, loop:false, width: 480, height: 360, fluid: false, plugins: { record: { audio: true, video: { // video media constraints: set resolution of camera width: { min: 480, ideal: 480, max: 480 }, height: { min: 360, ideal: 360, max: 360 } }, // dimensions of captured video frames frameWidth: 480, frameHeight: 360, maxLength: … -
Which way is better to store data about Transactions? (Django)
I need to store data about Transactions in Django (Postgres). There are different type of transactions (replenishment of balance, withdrawal from balance, payment of salaries, purchase of equipment, parking expenses, bonuses and etc.). Depend on type of transaction I need to store different data, for example: For replenishment of balance and withdrawal from balance - customer (Id of customer, can be empty), date, comment, total For salaries - employee (Id of employee), date, comment, sub total and total (there may be bonus or fine) For purchase of equipment - provider (Text), date, comment, total For parking expenses - date, comment, total Also I need to implement API (to retrieve salaries, transactions of client, all transactions, sum of all expenses, sum of all income and etc.) Also it will be good if Admin would be able to add custom transaction types (I think that it's not a good idea to store transaction type as a String, because it may cause some problems if Admin put wrong data (For example: "Salari" instead of "Salary")) So, here are my questions: Is it a good approach to store all Transactions in one table (Model) or it's better to split them and why? Any ideas … -
How do I display the list items on the site as links
This is my question and I'm just starting to learn django ^-^ these are urls from django.urls import path, include from . import views urlpatterns = [ path('', views.index), path('<int:days_week>/', views.get_info_week_intoviy), path('<str:days_week>/', views.get_info_week, name = 'day-week'), path('type/', views.teplt, name='types'), ] def teplt(request, types): dnay = ['CHETNIY', 'NECHETNIY'] rez = '' for typess in dnay: new_ser = reverse('types', args = (typess,)) rez += f'<li><a href="{new_ser}">{typess}</a></li>' response = f''' <ol> {rez} </ol> ''' return HttpResponse(response) this is the part of the code that should output as links along such a path http://127.0.0.1:8000/HOROS/type CHETNIY NECHETNIY I tried to fix the url and view somehow, but all attempts were in vain and returned to the previous code -
I keep on getting GET http://127.0.0.1:8000/room/f5428fc5 404 (Not Found):
Im making a Next.js and Django full stack app with Spotify api, and Im having trouble fetching the get-room api, when ever I click on the button to create a room in the create page the room is created and a unique code is generated but the room is not found. can anyone help me?: from create page const handleRoomButtonPressed = () => { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ votes_to_skip: votesToSkip, guest_can_pause: guestCanPause, }), }; fetch("/api/create-room", requestOptions) // Update the URL path .then((response) => response.json()) .then((data) => router.push("/room/" + data.code)) .catch((error) => setErrorMsg("Error creating room...")); }; const renderCreateButtons = () => { return ( <div className="flex flex-col items-center mt-2"> <button className=" bg-spotifyGreen text-white rounded-lg px-4 py-2 mb-2 hover:bg-spotifyLight " onClick={handleRoomButtonPressed} > Create A Room </button> <button className="bg-red-500 text-white rounded-lg px-4 py-2 hover:bg-red-400" onClick={() => router.push("/")} > <ArrowBackIcon /> Back </button> </div> ); }; from the room page: const [roomDetails, setRoomDetails] = useState({ votesToSkip: 2, guestCanPause: false, isHost: false, spotifyAuthenticated: false, song: {}, }); const { roomCode } = router.query; const getRoomDetails = () => { fetch("/api/get-room" + "?code=" + roomCode) .then((response) => { if (!response.ok) { leaveRoomCallback(); navigate("/"); } return response.json(); }) … -
I want to link my subcategory to related category in forms.py. How to do that?
I'm currently working on a Python project where I'm trying to get category from its own related subcategories. However, I'm encountering an issue where the subcategory field, it doesn't show anything. There are 4 files that i'm uploading: This is models.py class Category(models.Model): category_name=models.CharField(max_length=100,unique=True,null=False) def __str__(self): return self.category_name class Subcategory(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE) subcategory_name=models.CharField(max_length=100,null=False) This is forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Ad,Photo,Subcategory,Category class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError("This email is already taken.") return email class AdForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label=None) subcategory = forms.ModelChoiceField(queryset=Subcategory.objects.none()) class Meta: model = Ad fields = ['title', 'description', 'category', 'subcategory', 'price', 'location'] This is my views.py def publish_ad(request): if request.method == 'POST': form = AdForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('index') # Redirect to a success page or any other URL else: form = AdForm() return render(request, 'market/publish_ad.html', {'form': form}) This is a html file {% extends "market/base.html" %} {% load static %} <!-- publish_ad.html --> {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Publish Ad</button> </form> {% endblock content %} ** … -
Django does not access PostgreSQL Database using Docker
Here is the error message: Got an error checking a consistent migration history performed for database connection 'default': connection failed: could not receive data from server: No route to host Here is my .env POSTGRES_DB=ibm_skiller POSTGRES_PASSWORD=mYP@sSw0rd POSTGRES_USER=ibm_skiller POSTGRES_HOST=172.19.0.2 POSTGRES_PORT=5432 Here is my docker-compose.yml: postgres: container_name: postgres env_file: - ./.env image: postgres:alpine3.19 ports: - 5432:5432 volumes: - postgres16:/var/lib/postgresql/data # - ./ibm_skiller_init.sql:/docker-entrypoint-initdb.d/ibm_skiller_init.sql healthcheck: test: ["CMD-SHELL", "pg_isready -U ibm_skiller"] interval: 5s timeout: 5s retries: 5 networks: - skillernet Here is the output of the docker ps command: docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a2d40d97e3f0 postgres:alpine3.19 "docker-entrypoint.s…" 3 hours ago Up 3 hours (healthy) 0.0.0.0:5432->5432/tcp postgres f86b9bacd25e bd43f03c087b "./entrypoint.sh" 5 hours ago Up 5 hours 0.0.0.0:8000->8000/tcp, 0.0.0.0:9000->80/tcp skiller -
Serialize a nested object with Django Rest Framework
I'm currently trying to serialize the following object into the models listed below, the current relationship is A Category has many quizzes, a quiz belongs to one category, while containing many questions, a question belongs to a quiz, while containing many choices. Any help would be much appreciated! { "category": 1, "title": "Basic Java", "question": { "title": "Boolenas", "text" : "adafasad", "correct_words": [], "choice_type": "SINGLE", "choices": [ { "text": "asdadawd", "is_correct": true }, { "text": "adwasda", "is_correct": false }, { "text": "asdawd", "is_correct": false } ] } } The models are the following: class Category(models.Model): title = models.CharField(max_length=50) def __str__(self) -> str: return self.title class Meta: verbose_name_plural = 'Categories' class Quiz(models.Model): title = models.CharField(max_length=100) created_date = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self) -> str: return self.title class Meta: verbose_name_plural = 'Quizzes' class Question(models.Model): title = models.CharField(max_length=100, default='placeholder') text = models.CharField(max_length=200, null=True) correct_words = ArrayField(models.CharField(max_length=255), blank=True, null=True) # choice_type = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) quiz = models.ForeignKey(Quiz, related_name='questions', on_delete=models.CASCADE) class Choice(models.Model): text = models.CharField(max_length=200, null=True) is_correct = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE, default=1) And lastly these are my serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields= ('id', 'title') def validate(self, data): if Category.objects.filter(title=data.get('title')).exists(): raise serializers.ValidationError("Category … -
i couldnt redirecting my django app from int to string in the url
I'm having trouble with my Django URL patterns. The URL exercise4/1/ is not matching any of my defined patterns, even though I have a pattern defined for exercise4/int:month/. Can you help me figure out why it's not matching?" from django.shortcuts import render from django.http import HttpResponseNotFound,HttpResponse,HttpResponseRedirect month_chalenge = { 'JAN': 'IT IS NEW YEAR CONGRATS', 'FEB' : 'WELCOME TO NEW MONTH OF FEBURARY', 'APRIL': 'FASTING MONTH', 'MAY': 'EDEPENDENCE DAY' } def month_chalenge_bynumber (request,month): months = list( month_chalenge.keys()) redirect_month = months[month-1] return HttpResponseRedirect("/exercise4/"+ redirect_month) def monthchalenge(request,month): try: chalenge_list = month_chalenge[month] return HttpResponse(chalenge_list) except: return HttpResponseNotFound('sorry ! we dont have data for this data') -
djangos cmd like how do i make my C:\Users\user\Desktop\djangodemo> go into C:\Users\user\Desktop\DjangoCourse\djangodemo>
enter image description here enter image description here its little different since i had to start another one but i encounter '[Errno 2] No such file or directory' and it has become quite the problem for me so do y'all have any suggestions? well i have asked couple of people but they couldn't explain it well since they aren't sure themselves what causes the error to happen and i do not have solution for it so i would appreciate some suggestions or help from this community :) -
Filter a query set depending on state at a given date
Given the following model (using django-simple-history): class MyModel (models.Model): status = models.IntegerField() history = HistoricalRecords() I would like to get all instances that didn't have a certain status on a given date (i.e. all instances that had a different status on the limit date, plus all instances that didn't exist at that time). The following query will return all instances that never had status = 4 at any point before the limit date: MyModel.filter (~Exists ( MyModel.history.filter ( id = OuterRef ("id"), history_date__lte = limit_date, status = 4)) But unfortunately it also removes instances that had status = 4 at some past date, then changed to a different status by the limit date, and I want to keep those. The following should give the correct result: MyModel.filter (~Exists ( MyModel.history.filter ( id = OuterRef ("id"), history_date__lte = limit_date) .order_by ("-history_date") [:1] .filter (status = 4))) Unfortunately it doesn't work: Cannot filter a query once a slice has been taken. This question links to this documentation page which explains that filtering is not allowed after the queryset has been sliced. Note that the error comes from an assert in Django. If I comment out the assert in django/db/models/query.py:953, then the code … -
I want to link my subcategory to relevant category in forms.py? How to do that?
enter image description here dasdasdadadsadsadasdadadasdaadsdasdadasarasdfadkdvskfds and dasfkasfkfas mdasjkdkad;ksla;kdk;l sfkdlfkslkdflkslkdfs, kfslkdfsdfsdfsfsdfs and asffasfaskmfakmsfmkakmfsfas asfdsfds ewsf asd asdada dasdas dasdasd -
Setting page layout to landscape at specific page or after appendPageBreak() in google doc file using google app script
I have a google doc template file named 'TemplateDOC' which will append a paragraph heading at last "11. Annex of Google Sheet Records." at page 11 after appendPageBreak(). I need to set the page layout landscape so I can insert data range from a googlesheet named 'logDATA'. The code goes like this but the result is null, please help to reach out the solution. body.appendPageBreak(); body.appendParagraph("\n11. Annex of Google Sheet Records."); var paragraphs = body.getParagraphs(); var pageCounter = 1; var switchToLandscape = false; for (var pLen = 0; pLen < paragraphs.length; pLen++){ var paragraph = paragraphs[pLen]; if(paragraph.getText() == "11. Annex of Google Sheet Records." ){ switchToLandscape = true; break; } } if(switchToLandscape && paragraph.getType() == DocumentApp.ElementType.BODY_SECTION){ pageCounter++; } if(pageCounter==11){ var element = paragraph; var parent = element.getParent(); if(parent.getType()==DocumentApp.ElementType.BODY_SECTION){ var attribute = {}; attribute[DocumentApp.Attribute.PAGE_WIDTH]=792; attribute[DocumentApp.Attribute.PAGE_HEIGHT]=612; parent.setAttributes(attribute); } -
my nginx is active and gunicorn is active, but i got "ERR_CONNECTION_REFUSED" when i access to my domain, and even with ip
I am now using aws ec2 to deploy my django project, and route 53 as DNS server. At first time, i everything works fine. i can access to my website via ip or my domain. But i wanted to change some appearance of my blog site, and changed from local machine, pushed to main branch, and pulled it from my instance, and did sudo systemctl restart gunicorn which made disaster for me. When doing sudo systemctl status nginx sudo systemctl status gunicorn it gives me failed results. However i eventually make them active again, but if i try to access my website via public ip or domain, it giving me "ERR_CONNECTION_REFUSED" followings are my configuration for nginx, and gunicorn. server { listen [::]:80; server_name mydomain.com www.mydomain.com <public-ip-address>; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/ultraviolet/ultraviolet_dev/ultraviolet_dev.sock; } location /static/ { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } location /media { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } } server { listen [::]:443; server_name mydomain.com www.mydomain.com <public-ip-address>; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/ultraviolet/ultraviolet_dev/ultraviolet_dev.sock; } location /static/ { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } location /media { root /home/ubuntu/ultraviolet/ultraviolet_dev/; } } [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/ultraviolet/ultraviolet_dev ExecStart=/home/ubuntu/ultraviolet/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/ultraviolet/ultraviolet_dev/ultraviolet_dev.sock ultraviolet_dev.wsgi:application [Install] WantedBy=multi-user.target i made nginx configuration file … -
getting django cors error for subdomain but is working on different domain
I've a django app running with gunicorn and nginx. While making request from [ALL https] project.vercel.app to backend.domain.com works correctly. But when i make request from domain.com (Devtools>RequestHeader>Origin : www.domain.com) to backend.domain.com, it gives CORS error "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.". Django CORS_ALLOWED_ORIGINS=("www.domain.com", "project.vercel.app") BOTH ARE HTTPS Both project.vercel.app and www.domain.com should work and cors error shouldn't be seen cause it's similar approach! -
"applicant": [ "This field may not be null."]
serializers.py from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from .models import FieldUser, BaseApplicant, Applicant, CoApplicant, Guarantor class VerificationMobileSerializer(serializers.Serializer): mobile_number = serializers.CharField(max_length=15) class FieldUserSerializer(serializers.ModelSerializer): class Meta: model = FieldUser fields = ['id', 'username', 'first_name', 'last_name', 'email', 'mobile_number', 'profile_photo', 'address', 'pin_code', 'city', 'state'] profile_photo = serializers.ImageField( required=False) def update(self, instance, validated_data): validated_data.pop('profile_photo', None) instance.username = validated_data.get('username', instance.username) instance.first_name = validated_data.get( 'first_name', instance.first_name) instance.last_name = validated_data.get( 'last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.mobile_number = validated_data.get( 'mobile_number', instance.mobile_number) instance.address = validated_data.get('address', instance.address) instance.pin_code = validated_data.get('pin_code', instance.pin_code) instance.city = validated_data.get('city', instance.city) instance.state = validated_data.get('state', instance.state) instance.save() return instance class ApplicantSerializer(serializers.ModelSerializer): class Meta: model = Applicant fields = '__all__' class CoApplicantSerializer(serializers.ModelSerializer): class Meta: model = CoApplicant fields = '__all__' class GuarantorSerializer(serializers.ModelSerializer): class Meta: model = Guarantor fields = '__all__' class ApplicantSubmissionSerializer(serializers.Serializer): applicant = ApplicantSerializer() coApplicants = CoApplicantSerializer(many=True) granters = GuarantorSerializer(many=True) def to_internal_value(self, data): # Extract applicant data applicant_data = data.pop('applicant') # Extract applicant ID applicant_id = None if 'id' in applicant_data: applicant_id = applicant_data['id'] # Prepare co-applicants data with the applicant field populated with ID co_applicants_data = [] for co_applicant_data in data.get('coApplicants', []): co_applicant_data['applicant'] = applicant_id co_applicants_data.append(co_applicant_data) # Prepare guarantors data with the applicant field populated with ID granters_data = [] for granter_data in data.get('granters', … -
What is the Bearer token set in Authorization header, why it is so important?
Im using Django-rest-framework where the authorization is being done using bearer access token. The thing is, I want to do auth using the access token stored in cookie storage with HTTP-only. I'm using JWT, How can I handle the auth in django backend? -
am getting this error django.views.static.serve
am working on my django project , after uploading my file,picture or documents , when i try to download or view a file , I get error django.views.static.serve . my project is django project is connected to postgresql .i expect to be able to view or download an uploaded -
Django csrf token cannot be read
I am writing a website with Vue as a frontend framework and django as a backend framework. I have included the csrf token in every single request from my frontend to my backend to ensure that I dont get a 403 Forbidden error. All requests are ok and function normallu. Now here is where things are not working. I sent my code as a zipped file to someone else for them to run it. The frontend and backend both run with no issues, its just that no requests to the backend can be performed. Every request returns a 403 Forbidden error, and that is due to the csrf token not being included in the request. bear in mind that is is the same code that works on one laptop but doesnt on the other. What can I do to fix this? request from frontend to backend: try{ const response = await fetch('http://127.0.0.1:8000/logout', { method:'POST', headers:{ 'Content-Type': 'application-json', 'X-CSRFToken': Cookies.get('csrftoken'), } , credentials: 'include', }) Value of csrf token when attempting to print it on laptop that doesnt work: undefined Django settings.py file: Django settings for api project. Generated by 'django-admin startproject' using Django 5.0.1. For more information on this file, … -
Python + JavaScript good? [closed]
I learned python and I'm good on python but is python good choice to use it with JavaScript(React + Next.js) And I use Python(Django + FastApi) as a backend lib Is JavaScript(React+Next.js) good with Python(Django + FastApi) as freelancer I tried to search about that thing and every web and video say "everything is good" but I need to search it for a free lance work -
How do i accept a list of base64 images in django rest framework
So i am trying to accept multiple base64 images through an endpoint to create a post and this is the object dummie data i want to send. { "user": "username of the user", "caption": "Reasons why my Husky got mad at me today.", "location": "location of the post", "tags": [], "hashtags": [{"name":"Husky"}, {"name":"Angry_husky"}], "images": [ { "image_name": "image.png", "image_base64": "base64_string" }, { "image_name": "image2.png", "image_base64": "base64_string" } ] } Here are my models: class Hashtag(models.Model): name = models.CharField(max_length=100, unique=True) class Post(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) caption = models.TextField(_("Caption"), max_length=5000, null=True) location = models.CharField(_("Location"), blank=True, max_length=255) is_deleted = models.BooleanField(_("Is Deleted"), default=False) likes = models.ManyToManyField( CustomUser, related_name="liked_posts", blank=True, verbose_name=_("Liked By") ) tags = models.ManyToManyField( CustomUser, related_name="tagged_users", blank=True, verbose_name=_("Tagged Users"), ) hashtags = models.ManyToManyField( Hashtag, related_name="posts", blank=True, verbose_name=_("Hashtags") ) date_posted = models.DateTimeField(_("Date Posted"), auto_now_add=True) class Meta: ordering = ["-date_posted"] class Image(models.Model): post = models.ForeignKey( Post, null=True, on_delete=models.CASCADE, related_name="images" ) image_name = models.CharField() image = models.ImageField(_("Image"), upload_to="post_images/", null=True) Here are my serializers: class HashtagSerializer(serializers.ModelSerializer): class Meta: model = Hashtag fields = ["name"] class ImageSerializer(serializers.ModelSerializer): image = Base64ImageField() class Meta: model = Image fields = "__all__" class PostCreateSerializer(serializers.ModelSerializer): user = serializers.CharField() hashtags = HashtagSerializer(many=True) images = ImageSerializer(many=True, read_only=True) class Meta: model = Post fields = … -
How can I integrate AJAX infinite Scroll with Django View
I have a Django view that originally displays a list of applicants, and using the filter by session, it is expected to display list of applicants by the selected academic session. And using pagination, user is expected to scroll through pages using AJAX. The problem I am currently having is that records are been repeated in the list as the user scroll through the list and serial numbers are also repeated too. See Django view code: `@login_required(login_url='accounts_login') def application_list_by_session(request): logged_user = request.user if not (logged_user.profile.role == 'ADMISSION-OFFICER' or logged_user.profile.role == 'Admin' or logged_user.profile.role == 'Super Admin' or logged_user.is_superuser): messages.warning(request, 'Something Went Wrong') return redirect('accounts_login') # Log user activity UserActivityLog.objects.create(user=logged_user, action='Visited Application List by Academic Session Page') # Academic Session Form form = ApplicationlistBySessionForm(request.GET or None) if request.method == "GET" and form.is_valid(): academic_session = form.cleaned_data['academic_session'] # Filter Application by Academic Session submitted_application_list = ApplicationSubmission.objects.filter(academic_sess=academic_session) count_submited_applications = submitted_application_list.count() # Log user activity UserActivityLog.objects.create(user=logged_user, action=f' Generated Application list for {academic_session} Academic Session with {count_submited_applications} Applicants ') paginator = Paginator(submitted_application_list, 2) # Change 10 to your desired number of items per page page = request.GET.get('page') try: submitted_applications = paginator.page(page) except PageNotAnInteger: submitted_applications = paginator.page(1) except EmptyPage: submitted_applications = paginator.page(paginator.num_pages) context = { 'count_submited_applications': count_submited_applications, …