Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django create several container columns in a template and fill it with several values from QuerySet
I'm pretty a newbie in Web-Development, so I've met some difficulties while trying to connect html-templates with Django code. My plan for a certain page of my projected site is roughly to have a header on above, then lower there are 3 column-shaped containers (left to right, representing, i.e., different groups) filled with names of members of those groups (with vertical alignment, each member in a separate little container with photo, name and description). I thought that, as I use Django, it would be stupid to hard-code all the members into containers, and there probably are some methods to fill those columns from the code. I used cycles. Here is the template ("core" is a name of the app, templates are located in project/core/templates/core directory): {% extends 'core/base.html' %} {% block content %} <h1>{{title}}</h1> <div>Characters</div> <div> {% for fac in factions %} {% if fac == outers %} <div> <h2>{{fac}}</h2> {% for char in fac %} <div> <h3>{{char.name}}</h3> <h3>{{char.description}}</h3> </div> {% endfor %} </div> {% endif %} {% if fac == resistance %} ... {% endfor %} </div> {% endblock %} File core/models.py: class Character(models.Model): FACTION_CHOICES = ( ('outers', 'Outer World'), ('resistance', 'Resistance'), ('neutrals', 'Neutral characters'), ) name = models.CharField(max_length=100) … -
How to get rid of django.db.utils.OperationalError: no such table?
I'm developing this app in Django where I can't generate the migrations under any circumstances. I have tried other posts on SO, I have spent hours on ChatGPT, but there's no progress. After defining the single model, views and urls, my project is always returning django.db.utils.OperationalError: no such table: vini_rest_plotdata in the code that I will provide below. Can anyone see what is happening here? I have tried to create a whole new project only to find the same error, so I don't believe it is an error in the settings, but something I have in the code that I am repeating but just can't see. views.py: from django.shortcuts import render from django.http import JsonResponse from .models import plotData from .dash_app import app import json # Create your views here. def import_json(request): if request.method == 'POST': data = json.loads(request.body) title = data.get('title') description = data.get('description') url = data.get('url') json_data = data.get('json_data') plot_data = plotData.objects.create( title = title, description = description, url = url, json_data = json_data, ) return JsonResponse({'status': 'success', 'id': plot_data.id}) else: return JsonResponse({'status': 'error', 'message': 'Only POST requests are allowed'}) models.py: class plotData(models.Model): title = models.CharField(max_length = 100, primary_key=True, unique=True) description = models.TextField() url = models.URLField() json_data = … -
'The request signature we calculated does not match the signature you provided' in DigitalOcean Spaces
My django app saves user-uploaded files to my s3 bucket in DigitalOcean Spaces(using django-storages[s3], which is based on amazon-s3) and the path to the file is saved in my database. However when I click the url in located in the database it leads me to a page with this error: The request signature we calculated does not match the signature you provided. Check your key and signing method. The actual url, for example, looks something like this: https://my-spaces.nyc3.digitaloceanspaces.com/media/uploads/Recording_2.mp3?AWSAccessKeyId=DO009ABCDEFGH&Signature=Y9tn%2FTZa6sVlGGZSU77tA%3D&Expires=1604202599. Ideally the url saved should be https://my-spaces.nyc3.digitaloceanspaces.com/media/uploads/Recording_2.mp3 This actually also impacts other parts of my project because the url will be accessed later using requests but because of this error I get status [402]. My settings.py is this: AWS_ACCESS_KEY_ID = 'DO009ABCDEFGH' AWS_SECRET_ACCESS_KEY = 'Nsecret_key' AWS_STORAGE_BUCKET_NAME = 'bucket_name' AWS_DEFAULT_ACL = 'public-read' AWS_S3_ENDPOINT_URL = 'https://transcribe-spaces.nyc3.digitaloceanspaces.com/' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400' } AWS_MEDIA_LOCATION = 'media/' PUBLIC_MEDIA_LOCATION = 'media/' MEDIA_URL = '%s%s' % (AWS_S3_ENDPOINT_URL, AWS_MEDIA_LOCATION) DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage' The url that is saved contains the Access Key, the Signature that was used to write the file to the bucket and a timeout. I want all of that to not be there when the url to the file is saved in the database. I've tried to edit … -
Kong 502 Bad Gateway
I have two VMs. One is running an Apache server with a Django API and the other is running Kong. The two VMs are on the same network and can ping each other, and I can access the Django site on my browser from my Kong VM. I have configured the Kong route to point specifically to the local IP address on the network (192.168.x.x) instead of localhost. On the Kong VM I can do curl requests directly to the API just fine, and I can access the site on my browser, and the test route to httpbin works fine as well. But I still continue to run into this error when I try to access the API through my service. I'm running Kong as is, no docker stuff I tried getting the logs and got no information other than the Bad Gateway stuff, I've triple checked and verified that the routes are pointing to the correct local IP address and route and not localhost, still nothing I also have a web application firewall setup (Modsecurity) but disabling the firewall doesn't fix the problem and no relevant error logs show up that might suggest the firewall is blocking my requests … -
How to optimize a bulk query to redis in django - hiredis
I am porting a rest/graphql api from a Java project to Django in Python. We are using redis in both. We have one endpoint that is rather large (returns several MB). In this endpoint we construct a key and if that key exists in redis we return that data and skip past the other logic in the endpoint. I have deployed the api to a development environment. The Java version of this endpoint returns data between 4-5 seconds faster than the python version. I recognize some of this is that Java is a compiled language vs Python which is interpreted. I'm aware that there are a host of other differences, but I'm trying to see if there is any low hanging fruit that I can pick to speed up my Python api. I ran across an optimized library named hiredis. The website says the library speeds up multi-bulk replies, which is my use case. I repeatedly hit an endpoint that returns a large amount of data. Hiredis is supposedly a parser written in C. I have redis-py and django-redis installed. I read that I need to pip install hiredis. One source says hiredis will automatically be detected and just work … -
How can I show and hide Like/Unlike buttons using Javascript in my Web app?
I'm doing online course CS50W by Harvard and building a web app similar to twitter. When user sees a post I need to show the user Like or Unlike button depending on user liked it or not. There's also a counter showing how many users liked the post so far. I am able to update the counter if the user liked or unliked the post, but I'm having problem with the code showing or hiding the buttons. Here's my code: models.py class Post(models.Model): """ Model representing a post. """ user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) no_of_likes = models.IntegerField(default=0) def __str__(self): return f"Post {self.id} by {self.user.username} on {self.timestamp}" class Like(models.Model): """ Model representing a like. """ user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} likes {self.post}" urls.py path("", views.index, name="index"), path("like/<int:post_id>", views.like, name="like"), path("unlike/<int:post_id>", views.unlike, name="unlike"), views.py def index(request): """ Home page. """ posts = Post.objects.all().order_by('-timestamp') paginator = Paginator(posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) likes = Like.objects.all() # Make a list of liked posts. liked_posts = [] try: for like in likes: if like.user.id == request.user.id: liked_posts.append(like.post.id) except: liked_posts = [] return render(request, "network/index.html", { "posts": posts, "page_obj": … -
Errors in Importing assets folder with static url in React parcel project
I am trying to serverside render a react page using Django. The server-side rendering is working fine for normal react components. The project is using parcel to auto-build javaScript files so that Django could render them. This is the command I am using to compile react to Js. "scripts": { "watch": "parcel watch src/index.tsx --public-url /assets/" } I am new to the parcel, So sorry for the poor framing of the problem and/or any wrong terminology. The problem comes whenever I try to import an assets component in my assets folder into my react components. The import statement in my react code is working fine but I am getting an error in the import statements of the assets folder telling the file path for import is wrong. Here is the below screenshot of the issue. enter image description here @parcel/core: Failed to resolve 'assets/theme/base/typography' from './src/assets/theme/index.js' C:\profitional\BRAVO\Server\assets\src\assets\theme\index.js:23:24 22 | import breakpoints from "assets/theme/base/breakpoints"; > 23 | import typography from "assets/theme/base/typography"; > | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 24 | import boxShadows from "assets/theme/base/boxShadows"; 25 | import borders from "assets/theme/base/borders"; Done in 689.72s. C:\profitional\BRAVO\Server\assets>yarn parcel watch src/index.tsx yarn run v1.22.19 $ C:\profitional\BRAVO\Server\assets\node_modules\.bin\parcel watch src/index.tsx × Build failed. @parcel/core: Failed to resolve 'assets/theme/base/breakpoints' from './src/assets/theme/index.js' C:\profitional\BRAVO\Server\assets\src\assets\theme\index.js:22:25 … -
Django - model images are not loading
I add a ImageField model in my models and save the photos in my project folder. I send the objects to my template but I can't load the images. My app name is observatory and I can have other parts of models except images. Here is my code : Models.py : Class Observatorys (models.Model): ... photo = models.ImageField(upload_to = "photos/%Y/%m/%d") Views.py : From .models import Observatorys def Observatorys(request): Observatorys = observatory.objects.all() context= { 'observatorys': observatorys} return render(request, 'observatorys/observatorys.html', context) Urls.py : urlpatterns = [ path('',views.observatorys,name="observatorys"), path(,'<int:observatory_id>', views.observatory, name="observatory"), Template.html : ... <img src="{{observatory.photo.url}}"> ... -
Does somebody know what technology is the best for the Seo of a blog website backend? [closed]
I heard that the webpage needs to be as light as possible. I am debating if to use php, ASP .Net core, laravel or django. The most comfortable for me would be ASP .Net so i just care about the SEO part. ....................... -
ajax object send to server
i wnat to send this data to that views.py var bookingData = { name: name, email: email, contact: contact, date: date, shift: shift, members: members }; // Send the booking data to the server using AJAX var xhr = new XMLHttpRequest(); xhr.open("POST", "/sendBookingData", true); xhr.setRequestHeader("Content-Type", "application/json"); // Set the event handler before sending the request xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // Booking data successfully sent to the server // You can display a confirmation message or take other actions here alert("Booking successful!"); closePopup(); // Close the popup after successful booking } }; help me solve it out please. this project releated to the book guide system where the userinput details with the popup and when submitting the details it send to guide gmail from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def send_booking_data(request): if request.method == 'POST': # Extract data from POST request contact = request.POST.get('contact') date = request.POST.get('date') email = request.POST.get('email') members = request.POST.get('members') name = request.POST.get('name') shift = request.POST.get('shift') # Construct the email body with booking data email_body = f"New Booking Request\n\n" email_body += f"Name: {name}\n" email_body += f"Email: {email}\n" email_body += f"Contact: {contact}\n" email_body += f"Date: {date}\n" … -
AxiosError: Network Error when calling API from react native in django rest framework
I am running my app on my android device and i am not using any emulator. From postman I can call the APIs defined in django rest framework, however, when calling them from the front end, I am receiving the following error: AxiosError: Network Error Settings.py: DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cadence', 'rest_framework_simplejwt', 'rest_framework', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True SpitifyViews.py: class SpotifyViews(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def create_spotify_token(request): try: url = 'https://accounts.spotify.com/api/token' headers = { "content-type": "application/x-www-form-urlencoded" } data = { "grant_type": "client_credentials", "client_id": "220bc6fbfe2c4df28c4bad2b9095b391", "client_secret": "0bbb4cbabbdc4b229e9220c34c180758" } encoded_data = urlencode(data) response = requests.post(url, headers=headers, data=encoded_data) if response.status_code == 200: return JsonResponse(response.json()) else: return JsonResponse({"error": "Failed to get Spotify token"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except Exception as error: return JsonResponse({"error": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) JS Code: axios.defaults.baseURL = "http://localhost:8000/"; export const sendRequest = async (method, endpoint, body) => { const response = await axios.request({ method: method, url: endpoint, data: body, headers: { // Authorization: `Bearer ${localStorage.getItem("token")}`, }, }); if (response.status === 401) { // … -
how to fix django CSRF error for admin area?
I set up docker-compose to server django v5.0.6 and I see login page but after signin I face with CSRF error. my docker-compose containers: Nginx web (django container) postgres all the configs are correct and I can call APIs and see login page of admin area. nginx.conf server { listen 80; server_name example.com; location / { proxy_pass http://web:8000; } location /static { autoindex on; alias /static; } } .env ... DJANGO_ALLOWED_HOSTS=example.com,web CSRF_TRUSTED_ORIGINS=["example.com"] ALLOWED_HOSTS=['example.com'] ... how can I fix it? I try to setup based on the configs but I gave 403 error only for admin area. all APIs works fine. -
command `sudo systemctl start mybig_app` holds on and service stands in status loaded(activating) never turning to active
I have developed a quite big django app. I have deployed it at path /var/www/mybig_app/ on a server machine (raspberry pi) connected to my LAN. The app uses libraries stored in the virtual environment /var/www/mybig_app/venv/. I have configured a .wsgi file to instruct gunicorn to expose the app on port 8003 of localhost and nginx to stream content form port 8003 to port 3003. So, with current directory being /var/www/mybig_app/, I run python manage.py runserver localhost:8003 or /var/www/mybig_app/venv/bin/gunicorn mybig_app.wsgi:application --bind localhost:8003 and even if I have to wait about 5 seconds, in both cases I can reach my app from a browser of an external device connected to my LAN at address localhost:8003 (I have tryed to login as admin, access all the pages, it works, there is no error). Now I want to manage my app as a service via systemd. So I have prepared a .service file at /var/www/mybig_app/infrastructure/systemd/mybig_app.service, symbollically linked with ln -s /var/www/mybig_app/infrastructure/systemd/mybig_app.service /etc/systemd/system/ ln -s /var/www/mybig_app/infrastructure/systemd/mybig_app.service /etc/systemd/system/multi-user.target.wants/ loaded the configurations for systemd sudo systemctl daemon-reload sudo systemctl enable mybig_app.service (I have done this before for other apps, it works) In the end I want to start it, but when from directory /var/www/mybig_app I run sudo … -
How many lines of code does a website have with strong authentication and content management? [closed]
As someone who doesn't know much about technology, I wonder what's behind my everyday things? And how many lines of code do they have? I know this isn't specifically a problem, but I'm curious and would like to know, My apologies if it sounds a bit 'stupid' -
difficulty assigning a ForeignKey value field to a form within a loop
I'm encountering an issue with assigning a ForeignKey value to a form field within a loop. I have a Django application where users can submit answers to questions, and each answer can have multiple comments associated with it. To allow users to add comments to each answer, I've implemented a form within a loop. However, when users submit a comment using the form, instead of creating a CommentAForm object, it is creating a CommentQForm object. Despite attempting to pass the answer ID as a hidden field within the CommentAForm, the value doesn't seem to be correctly assigned to the CommentAForm. As a result, comments are not being associated with the correct form or model object, i don't know what is going on, How can I fix it views: def view_question(request, slug): question = get_object_or_404(Question, slug=slug) answers = Answer.objects.filter(post=question) answers_comment = CommentA.objects.filter(post__id__in=answers) # this is the comment form for each question if request.method == 'POST': comment_form = CommentQForm(request.POST) if comment_form.is_valid(): my_comment_form = comment_form.save(commit=False) my_comment_form.user = request.user my_comment_form.post = question my_comment_form.save() return redirect('View_Question', slug=slug) else: comment_form = CommentQForm() # This is the comment form each answer if request.method == 'POST': answer_comment_form = CommentAForm() if answer_comment_form.is_valid(): my_answer_comment_form = answer_comment_form.save(commit=False) my_answer_comment_form.user = request.user my_answer_comment.post … -
In mongodb(pymongo) how could i create only the missing path in a nested document
Im using django and mongoDB connected by Pymongo. And i made a collection of users that inside each user there are details, and a calender when the user first register the calendar is an empty array(could be changed if needed), in the calendar would be a list of years, inside every year a list of months, inside every month would be a list of days, and in every day a list of events. And i need that when a user wants to add an event to a specific date it would add it to the correct path meaning if the specified year allready exists it would insert the event in it and so on for the month and day. But if the year isnt exist yet it would create the needed path. Every thing i tried or not updating at all, or adding duplicates and ignores the allready created data. Does someone has a solution for that case? And if thats not the correct architecture for a mongo database feel free to improve it. Thank you very much. For example i tried users = db["users"] users.update_one({"_id": user}, {"$addToSet": {"year": year, "months": [{"month": month, "days": [{"day": day, "events": [new_event]}]}]}}}, upsert=True) But … -
the question is how to use LogoutView class in django to log out the user and also to redirect him to a specific url
misundersting of the usage of LogoutView based class. I would like to ask for an example in how to use this class to logout the user. I tried to use pass inside the class but it redirect me to an empty page -
How to run multiple websocket client connections?
Apologies in advance if this is a redundant question, I'm asking it here as the last resort, after having gone through a lot blogs & articles. Here's the situation: I have a django service(let's call it the "main" service) running an HTTP server & a WebSocket server using django-channels. I have a bunch of other django services(call them target services) wanting to connect to the websocket channels exposed by the main service And target each service needs to establish multiple websocket connections with the main service, and send/receive messages as long the connection is not closed by the main service. Here're some sample connection URLs: URL1 = "wss://main-service.com/ws-connection/1" URL2 = "wss://main-service.com/ws-connection/2" URL3 = "wss://main-service.com/ws-connection/3" And this list of URLs is obviously not known in advance, the main service sends us a mini payload which is used to generate the URL at runtime, and connection is established. The target service needs to have the ability to maintain thousands of websocket connection(serving as stateful connections) & it also needs to expose an HTTP API to serve direct requests. So far, I have gotten the target service API running as django project, and a basic websocket client, and the two look like this: … -
"... && coverage report" not working after switching to pytest-django
I was using unittest in Django to write tests and running the tests with this command: coverage run --omit='src/manage.py,src/config/*,*/.venv/*,*/*__init__.py,*/tests.py,*/admin.py' src/manage.py test src && coverage report It'd run the tests then display the .coverage generated by coverage run ... after running. After installing pytest-django and setting up pytest.ini, I've updated my command to: coverage run --omit='src/manage.py,src/config/*,*/.venv/*,*/*__init__.py,*/tests.py,*/admin.py' -m pytest && coverage report Note, I'm not using pytest-cov just yet. For some reason I can't figure out, the coverage report is not being displayed after the tests run. I can run each commands separately: The coverage run ... runs the tests and generates the report. The coverage report displays the report. I just can't get the report to display doing ... && coverage report after switching to pytest-django. Any reason for this? Versions: coverage = "^6.2" pytest-django = "^4.7.0" -
trouble in installation of django
I have been facing many issue regarding installation django on windows using pip. i have used "pip install django". But I am unable run the command "django-admin startproject myproject" it is showing following error: 'django-admin' is not recognized as an internal or external command, operable program or batch file. Please help me in installation of django on windows 11. please proide me with commans that to be run for installation in detail. -
How to test django channels between two physical devices over a wifi network
Can someone help me configure my django channel app in order for me to be able to test the chatting feature between two users. They must use two different devices and chat over a wifi network Looking through the net I can't find anything -
communication between the server and the user
Front end (React) and Back end (Django) are working on the local server and are sending information to the user, but the Front end code has been updated and the local server is working, but the users still see the old interface, what's the problem? please advise copied and pasted the new changes into the old code and added a new library, the program is working but the new changes are not visible with the old code -
Django login issue: Redirect to user panel not working despite status 200 in console [closed]
I'am building application in django and tailwind css to asking legal questions. I created user in django admin panel, created views etc. But after login(it is success 200 status), it doesn't work. I can't redirect user after login to user panel. How to do it, and where is error? https://github.com/marpot/lex_question Title: I'm encountering an issue with Django authentication where despite receiving a status 200 in the console upon logging in, I'm not redirected to the user panel as expected.I tried to change urls but it's incorrect I think. -
DjangoAdmin render BinaryField as image
I wrote middleware to catch requests and view them on admin page. It successfully views raw text request body, but fails on image render. admin.py class RequestLogEntryAdmin(admin.ModelAdmin): fieldsets = ( ('Request', { 'fields': ('request_headers', 'request_size', 'request_body_'), }) ) def request_body_(self, obj): if b'Content-Type: image/png' in base64.b64decode(obj.request_body): return obj.image_handler(bytes(obj.request_body)) return bytes(obj.request_body) models.py class RequestLogEntry(models.Model): # ... request_body = models.BinaryField(null=True) # ... def image_handler(self, binaryfield): return mark_safe(f'<img src="data:image/png;base64,{binaryfield}" width="150" height="150" />') Before saving request.body is being base64 encoded middleware.py # ... log_entry.request_body = base64.b64encode(request.body) # ... Current code produces the following: Base64 decoded request.body looks like this: My guess is that some extra data being mixed with the image bytes (like 'Content-Disposition' and 'Content-Type' headers), but I'm not sure how can I cut it out from the request body. -
AutocompleteFilter must inherit from 'FieldListFilter'
I want to write custom filter with drop down field using admin_searchable_dropdown I tried two ways too implement this and got error both times first way: the custom filter class PrimaryLabelFilter(AutocompleteFilter): field_name = 'primary_label' title = 'primary_label' in the admin using it like this list_filter = ( PrimaryLabelFilter, ) the error Forbidden (Permission denied): /admin/autocomplete/ model_admin = self.admin_site._registry[remote_model] ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ KeyError: <class 'panel.backend.ad.models.label.Label'> HTTP GET /admin/autocomplete/?app_label=ad&model_name=ad&field_name=primary_label 403 [0.01, 127.0.0.1:52324] second way: in admin class list_filter = ( ('primary_label', PrimaryLabelFilter), ) the error <class 'panel.backend.ad.admin.ad.AdAdmin'>: (admin.E115) The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.