Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting WebKitFormBoundary in my post request using the JS Fetch API?
I am trying to send data to my Django server from JS. My code looks like this? let url = play_selected.dataset.url; const csrf_token = getCookie('csrftoken'); let data = JSON.stringify( { selects: arr } ); console.log(data); const response = await fetch(url, { method: 'POST', // Specify the HTTP method body: data, // JSON.stringify(data), // Convert data to JSON string (if object) headers: { 'Content-Type': 'application/json', // Set content type header 'X-CSRFtoken': csrf_token } }); data = await response.json(); console.log(data); The selects arr is just an array of numbers which I will eventually do something in my django back end. Currently all I am doing is printing out the request.POST variable which is always empty. When I print out request.body I get the following: (Pdb) p request.POST <QueryDict: {}> (Pdb) p request.body b'{"selects":["29"]}' (Pdb) I would imagine that request.POST should display something similar to what is in request.body. Why is request.POST empty? -
How to read PDF file from Django?
I need to create an app in Django that scrape data from a PDF file, how can I do this? I really don't have any clue all I know is that python has a few libraries to read PDF files like for example PYPDF2 but I don't know how to integrate all of this in DJANGO. I tried PYPDF2 in a python shell but it didn't work for me all it prints is blank line -
Django CORS issue
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://url/. (Reason: header ‘authorization’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). The api is made using djangorestframework and i have configured corsheader in the settings.py,error pop up when im trying to put authorization in headers in the fetch request -
Lots of issues using openAI in Python only on Ubuntu
I have a project utilising openAI One of the changes required me to run openai migrate, it says "You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface. " I did that on windows and had no issues. I can't remember how I did it. I think I just opened up powershell or terminal and wrote openai migrate (which doesn't really make sense to me, is it scanning my entire system and makes changes to update the code? Whatever, I digress). Anyway, I'm moving to linux and ran my program (Django). It says the exact same thing as before - that you need to run openai migrate. So I open a terminal on my desktop, 'openai migrate' and viola..nothing. OpenAI not found. I know that openai is installed in ./local after trying to follow another debugging step. It seems I have 2 options 1 - manually refactor my code to comply with the new API or 2 - run the openAI migrate command which I believe does that already for you?? Anyway, I'm going with option #2 but I cannot even run open ai migrate. I'm not a linux expert (yet..) and don't know about … -
Is the structure of the project correct?
Here is the structure of my project: ├─── applications │ ├─── about │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ ├─── migrations │ │ │ │ └─── __init__.py │ │ ├─── models.py │ │ │ ├─── services │ │ │ │ └─── __init__.py │ │ ├─── templates │ │ ├─── tests.py │ │ │ └─── views.py │ ├─── account │ │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ ├─── migrations │ │ │ │ └─── __init__.py │ │ ├─── models.py │ │ │ ├─── services │ │ │ │ └─── __init__.py │ │ ├─── templates │ │ ├─── tests.py │ │ │ └─── views.py │ ├─── blog │ │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ … -
how can i fix my ui in django jinja template everything is messed up?
i was adding image sharing functionality to my project but now i messed up its ui and i am unable to fix it!! <div class="room__message"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> {{ message_form.body }} </div> <div class="mb-3"> {{ message_form.image }} </div> <input type="submit" class="btn btn-primary" value="Send Message"> </form> </div> the above code has "message_form.body" has a text area without id so it a name="body" and the code "message_form.image" is the image upload button. i don't know what went wrong but the text area and button are hard stuck and send message button is expanded. i attached the image or the ui pls help. i just want to adjust text area and the upload and send message button this is my site at 100% scale this is at 33% scale the website is working properly just the UI is messed up need help to fix it -
Add two time values and display in template
I am having trouble on how to correctly display the addition of two time values in a template. Here is my code. models.py class UserTimesheet(models.Model): employee = models.ForeignKey(Employee, models.SET_NULL, blank=True, null=True) date = models.DateField() monday_start_time = models.TimeField(_(u"Start Time"), null=True, blank=True) monday_end_time = models.TimeField(_(u"End Time"), null=True, blank=True, ) @property def get_monday_total(self): if self.monday_start_time is not None and self.monday_end_time is not None: return self.monday_end_time - self.monday_start_time I have tried using: {{ get_monday_total }} {{ UserTimesheet.get_monday_total }} And a lot of different other things, but I cannot, for the life of me, figure out how to display this logic within a template. Any ideas? Any and all help is grateful. -
Deplying django and vue don't load the site
Im trying to deploy django with the dist folder generated from the npm run build command, I tested the site with the serve npm package and works just fine, but when I copy that folder into the django project directory and run python manage.py runserver the page renders blank and the browser console tells these errors. The resource from “http://localhost:8000/assets/index-422b98df.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). and Loading module from “http://localhost:8000/assets/index-4435c3df.js” was blocked because of a disallowed MIME type (“text/html”). I just wrote the simplest view to render the index.html. def index(request): return render(request, 'dist/index.html') Any help will be useful, thanks in advance. -
Django display crossed tables
I have an event signup page where the participant insert's details upon signing up. Then in a view I am trying to display a listing of their name, title, and details. I am stuck trying to get the details field to display if there were any for the participant. Thank you. ######## Model - Events ######## class Event(models.Model): Event_ID = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) Event_Description = RichTextField(null=True, blank=True) Event_Category = models.ForeignKey(EventCategories, default=1, on_delete=models.CASCADE) Event_participants = models.ManyToManyField(User, blank=True, related_name='events') def __str__(self): return self.Event_Name ######## Model - Events ######## class Submission(models.Model): participant = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="submissions") event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True) details = models.TextField(null=True, blank=False) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) def __str__(self): return str(self.event) + ' --- ' + str(self.participant) ######## View ######## def single_event(request, pk): try: event = Event.objects.get(Event_ID=pk) submitted = Submission.objects.filter(event=event) submitted = list(submitted.values('participant','details')) except: return render(request, 'events/single-event.html', {"success":True,}, status=200) context = {'events':Event.objects.filter(Event_ID=pk), 'event':event, 'submitted':submitted} return render(request, 'events/single-event.html', context) ######## Template - single-event.html ######## {% for event in events %} {% for user in event.Event_participants.all %} <tr> <td>{{ user.profile.title }}</td> <td>{{ user.first_name }} {{ user.last_name }}</td> <td>{{ ??????????? }}</td> #This is where i need help. I would like to display 'details' from the Submission model here </tr> {% endfor … -
Django-allauth Third-Party Login Failure
I've got an instance of an application where I'm trying to authenticate users using Google/Github. All the configuration is as documented, the callbacks are as required by the docs, the client ID and secrets are alright. Yet, when receiving the callback, I get shown the following page The callback url i am getting is (with no error msg): http://localhost:8000/accounts/github/login/callback/?code=1216195be45faf4d04af&state=jYUTOFAXVKeiqzpk I do not know what code and state in uri is referring to. The page I am getting redirected to after login attempt I was using version 0.61.1 Downgrading to 0.54.0 and removing allauth.account.middleware.AccountMiddleware middleware solved the problem. But now I can not use LinkedIn Open ID Connect authentication as it is not supported in version 0.54.0. Looking for the solution so that i can use google,github, and linkedin social auth in version 0.61.1 -
Rendering a form with Django using crispy forms
I am rendering a review form on a product page, however the basic rendering is not working. I know I have crispy forms installed correctly as I have used it elsewhere without problem. Can anyone see where I am going wrong? models.py from django.db import models class Review(models.Model): """ Model for review form. Assistance with the positive integer field came from: https://www.geeksforgeeks.org/positiveintegerfield-django-models/ """ stars = models.PositiveIntegerField(choices=( (1, '1 star'), (2, '2 stars'), (3, '3 stars'), (4, '4 stars'), (5, '5 stars'))) body = models.TextField(blank=False) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["created_on"] def __str__(self): return f"Review {self.body}" forms.py from django import forms from .models import Review class ReviewForm(forms.ModelForm): """ Review form set up """ class Meta: model = Review fields = ('stars', 'body') views.py from django.shortcuts import render from .models import Review from .forms import ReviewForm from django.contrib import messages def review(request): """ A view to return review """ # reviews = Review.objects.order_by('-created_on').all() # if request.method == 'POST': # review_form = ReviewForm(request.POST) # if review_form.is_valid(): # review_form.instance.name = request.user.username # review_form.save() # review_form = ReviewForm() # messages.add_message(request, messages.SUCCESS, # 'Your review has been successfully posted!') # else: review_form = ReviewForm() context = { 'review_form': review_form, } return render(request, 'product/product_detail.html', context) … -
PyCharm: how to add multiple arguments after manage.py, without paying for Django support?
Running tests for my django app I use ./manage.py test --settings=soardataDJ.settings.testing which runs fine in a terminal window. When I try to run/debug it in PyCharm with a run configuration, it fails if I add anything after "test" in the script parameters, as I did in the screenshot. I see answers on how to add more arguments within PyCharm's Django support plugin. But how do I add arguments without paying for the support? Why can't PyCharm interpret arguments just like my terminal does? Does PyCharm block this to get people to pay? -
django for-loop to calculate laon repyament and interest for a period only displaying the last iteration
Am building a loan system to calculate the repayment period. am having this issue when i run the code it only display the last row. below is my view.py please i need it to display all the rows not only the last row def sveloan(request): if 'userid' in request.session: if request.method == 'POST': balance = 120000 annual_interest_rate = 42 monthly_payment_rate =0.3 monthly_interest_rate = annual_interest_rate / 12 monthly_payment = monthly_payment_rate * balance new_balance= (balance - monthly_payment) * (1 + monthly_interest_rate) for month in range(1, 6): monthly_payment = 20000 balance = (balance - monthly_payment) rateint = (balance / 100 * monthly_interest_rate) mydist = ('Month: %d \n Minimum monthly payment: %g \n Remaining balance: %g \n Minimum Interest payment: %g'\ % (month, round(monthly_payment, 2), round(balance,2), round(rateint, 2))) context={ 'mylist': mydist } return render(request,'loantest.html',context) else: return render(request,'index.html') else: return render(request,'index.html') in my template: {% for p in mylist %} {{p}} {% endfor %} -
Removing a non-nullable Django field with SeparateDatabaseAndState
Let's say I have the following model: class Product(models.Model): name = models.CharField(max_length=128) is_retired = models.BooleanField(default=False) I want to remove the is_retired field. I'm using blue-green deployments to release changes to production so I'm using SeparateDatabaseAndState in my migration. My initial migration to remove the field from the application state is simple: class Migration(migrations.Migration): dependencies = ... operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.RemoveField( model_name="product", name="is_retired", ), ], database_operations=[], ), ] I can successfully run the migration. However, I'm getting the following error when I attempt to create a new product with Product.objects.create(name="Wrench"): self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x106bf4050> query = 'INSERT INTO "core_product" ("name") VALUES (?) RETURNING "core_product"."id"' params = ('Wrench',) def execute(self, query, params=None): if params is None: return super().execute(query) # Extract names if params is a mapping, i.e. "pyformat" style is used. param_names = list(params) if isinstance(params, Mapping) else None query = self.convert_query(query, param_names=param_names) > return super().execute(query, params) E django.db.utils.IntegrityError: NOT NULL constraint failed: core_product.is_retired Looks like the INSERT query is failing because the is_retired field is defaulting to null, instead of its correct default of False. I've fixed it by making Product.is_retired nullable before removing it from the state: class Migration(migrations.Migration): dependencies = ... operations = [ migrations.AlterField( … -
Method Not Allowed (GET): /accounts/logout/
there is an issue in Django with the LogoutView. when I put the link 'accounts/logout' it prompts in the cmd "GET /accounts/logout/ HTTP/1.1" 405 0 Method Not Allowed (GET): /accounts/logout/ Method Not Allowed: /accounts/logout/. this is the urlpatterns: urlpatterns = [ path('', include('django.contrib.auth.urls')), path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('profile/', showProfile, name='profile'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), ] and this is the 'registration/logged_out.html' file content: {% extends "generic_base.html" %} {% block content %} <form method="post" action="{% url 'user:logout' %}"> {% csrf_token %} <button type="submit">Logout</button> </form> {% endblock content %} I saw a lot of ways to fix this. but none of them worked. -
Hosting django with celery and redis
I want to host my django project.But i donot know which hosting site will support celery and redis.Can someone suggest me some website for hosting. -
How do I make my test behave as expected when my model is updated?
My view class MovieUpdateView(UpdateView): model = Movie template_name = "movie_update.html" fields = [ 'movie_name', 'movie_year', 'movie_director', 'movie_rating', 'movie_cover_image' ] def get_success_url(self): return reverse_lazy('movie_detail', kwargs={'pk': self.object.pk}) My test update def setUp(self): self.movie = Movie.objects.create( movie_name='Avengers - Endgame', movie_year= 2019, movie_director='Anthony Russo, Joe Russo', movie_rating=10.0, movie_cover_image = '\movies\images\movies_covers\1f8373201516a4657649d61e97b1f91a_WhvCLCe.jpg' ) def test_movie_update_view(self): self.assertEqual(self.movie.movie_name, 'Avengers - Endgame') movie_update = { 'movie_name' :'Title Updated', 'movie_director' :'New Director', } response = self.client.post( reverse('movie_update', kwargs={'pk': self.movie.pk}), data=movie_update ) self.movie.refresh_from_db() self.assertEqual(self.movie.movie_name, 'Title Updated') File "E:\\Users\\Santiago\\Desktop\\web-projects\\personal_blog\\reviews\\tests.py", line 99, in test_movie_update_view self.assertEqual(self.movie.movie_name, 'Title Updated') AssertionError: 'Avengers - Endgame' != 'Title Updated' - Avengers - Endgame + Title Updated I want to test my MovieUpdateView view based on the UpdateView generic class, but when I try to update through the test, I can't, but manually through the site, everything is fine, when I update it's ok, I'm still starting with the tests, maybe I did something wrong! -
Django Django administration shows more objects then the actual datapoints
I have created a Django model and uploaded some data, around 90 data point. I deleted and uploaded these data points multiple times for testing purposes. I notice my Django admin showing object number much higher then the actual data point present in the database. PeptideSeq object (695) While the total data point I have around 90. Is these normal behavior or is there a way to correct this issue and start the count from zero when you delete all objects. I used Django admin GUI to delete objects. Thanks! -
failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1
I am using this Dockerfile for my Django + React(Vite) application. Its giving the same error every time when I am running it with docker-compose build GitHub: click here Dockerfile (Django) FROM python:3.10-slim ENV PYTHONUNBUFFERED=1 ENV EMAIL_HOST_USER=email ENV EMAIL_HOST_PASSWORD=password WORKDIR /backend RUN apt-get update && apt-get install -y libpq-dev build-essential RUN pip install -r requirements.txt COPY . . EXPOSE 8000 Dockerfile (React) FROM node:20.6-buster-slim WORKDIR /frontend COPY . . RUN npm install EXPOSE 5173 CMD ["npm", "run", "dev"] docker-compose.yml services: backend: build: ./backend ports: - "8000:8000" volumes: - ./backend:/backend command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" frontend: build: ./frontend ports: - "5173:5173" volumes: - ./frontend:/frontend I would appreciate if anyone can help me with solving the issue and make the build successful with dockerizing the whole application. -
Dynamic chat page on django channel
At the moment my chat room functions through 2 simple pages: home.html (chat list) and chat_room.html with input field and connection to a web socket: <!DOCTYPE html> <html> <head> <title>Chat Rooms</title> </head> <body> <div> <h1>Chat Rooms</h1> <ul> {% for room in chat_rooms %} <li><a href="{% url 'chat_room' room.id %}">{{ room.name }}</a></li> {% endfor %} </ul> </div> </body> </html> chat_room.html: <!DOCTYPE html> <html> <head> <title>{{ room.name }}</title> <script> var room_id = {{ room.id }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + room_id + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; var sender = data['sender']; var chatMessages = document.querySelector('#messages'); var messageElement = document.createElement('p'); messageElement.innerHTML = '<strong>' + sender + ':</strong> ' + message; chatMessages.appendChild(messageElement); }; function sendMessage() { var messageInputDom = document.querySelector('#id_content'); var message = messageInputDom.value; var sender = "User"; chatSocket.send(JSON.stringify({ 'message': message, 'sender': sender })); messageInputDom.value = ''; } </script> </head> <body> <h1>{{ room.name }}</h1> <div id="messages"> {% for message in messages %} <p><strong>{{ message.sender }}:</strong> {{ message.content }}</p> {% endfor %} </div> <form id="message-form" onsubmit="event.preventDefault(); sendMessage()"> {% csrf_token %} {{ form }} <button type="submit">Send</button> </form> </body> </html> Both pages are received by the user through the view renderer: def home(request): … -
Error occurred during python3.7 pip install mysqlclient
When I tried to use pip install mysqlclient, I encountered the error shown in the screenshot. My Python version is 3.7, and I attempted to install mysqlclient version 2.1.1. I'm using MacOS with Anaconda. Initially, I executed brew install mysql-connector-c and then brew install mysql-client in the macOS terminal. I configured the environment variables according to the official documentation, but I still encountered installation errors later on. I downloaded the compressed source code files, extracted them, and moved them to the site-packages directory of Anaconda. However, when I tried pip install mysqlclient, I encountered the following error. How can I resolve this issue?Installation error I need to resolve these issues before I can install it. -
Phone won't vibrate when receiving firebase push notification
I am sending firebase push notification using the python sdk but I am having an issue. Even though the notifications are being delivered, however it doesn't vibrate the phone. Below is my code. message = messaging.Message( token=token, notification=messaging.Notification( title=title, body=body, ), ) messaging.send(message) I have tried everything, used data message also but no difference. I have also tried some examples on here but still the same thing. I would really appreciate any help. Thank you -
Is Postgres good for long text?
I designed a corporate website with Django and Postgres. I made a blog section for him. I am uploading the contents that I wrote in WordPress to the blog of the new site. But I get an error OperationalError at /en/admin/blog_app/blog/add/ index row size 3144 exceeds btree version 4 maximum 2704 for index "blog_text_key" DETAIL: Index row references tuple (24,1) in relation "blog". HINT: Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing. I researched about this error and found out that the WordPress content is too big for the Postgres database. What is your suggestion? Should I change the database? Or can the problem be solved? Thank you for your guidance. -
Switching from directory-based URL to subdomain-based URL in ReactJS and Django
I have developed a web application using ReactJS and Django, allowing users to create custom websites. Currently, these websites are stored in the website.com/applicationname directory. However, I want to switch to a subdomain-based URL structure, where each user's custom website is accessible via applicationname.website.com. How can I achieve that? My application is hosted in Heroku. -
Django link table row to detail view with buttons to other views
Hey thanks in advance for any help its always much appropriated. So I found this post on here that help do this and it worked great. So i have my table and when you click a row it goes to the right detail view for that row. What i would also like to do is have a column in the table with a button for delete and one for edit for each row. I was able to add the buttons but it looks like the JS code that makes the rows clickable is overriding the buttons. without the JS code the buttons work. Any guidance on what to look up or helpful terms to make the rows clickable and and buttons not be lumped into it. Sorry I've very new to this in general and especially inexperienced in javascript I tested with the rows not clickable (no javascript) and the buttons that are in work and go to the intended view. I also tried moving data-href="{% url 'detail' part.pk %}"the tag in the html the Table tag. this made a single cell clicked as expected (not what i want) but the buttons become clickable again but don't route properly. I …