Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should i dockerize django app as non-root?
Should i dockerize Django app as a root user? If yes how can i set up non-root user for Django? Because in node.js app should have USER:node which is a better practice. Code example from official docker page which does not include non-root: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ -
Creating a templete with xlsxwriter in django webframework
I'm new to django and still trying to figure out logic. I watched a bunch of videos and I know how to create those examples but I'm not quite there. I'll explain what I want and maybe someone can explain to me a logic how to do, yes? I created an app and inside an app I connected urls, settings, html and I have working site. Now I want to input data in django website, django to pass data to xlsxwriter script to create xlsx document, and to pass that document to user to download. My logic: What I need now, is to create some kind forms (but not for registered users, it can use anyone who uses a website) to input data. Which forms are best? Than I need to pass () that data to function that are in views that will get an arguments from html page through some kind of forms, create document, and pass that to download button. -
My ajax jquery script does not display image src with conditions but it displays video src and audio src with conditions
I am using django rest framework. From backend everything is fine. But when i display my img src with my conditions.It does not display my image source but My video and audio src displays properly with conditions but img src does not display. I want to display image src according to ajax jquery script conditions.Without these conditions image src displays properly but i want to display image source with conditions as mentioned in the code. Here is my code: My html file: It includes my html code with django jinja template {% extends 'layout.html' %} {% block body %} <!DOCTYPE html> <html> <head> <title>Blog</title> <link rel="stylesheet" href="/static/css/blog.css"> <link rel="stylesheet" href="/static/css/create_blog.css"> <link rel="stylesheet" href="/static/css/update_blog.css"> </head> <body> <main> <h1 class="display-4">Dashboard <small> Welcome, {{request.user.username}} </small> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createModal"> Create Blog </button> </h1> {% include 'create_blog.html' %} {% include 'update_blog.html' %} <div class="card" id="card" style="width: 27rem;"> </div> </main> <script type="text/javascript" src="/static/js/blog.js"></script> </body> </html> {% endblock %} ajax jquery script code: It incudes my ajax script code with different file src // Read or Retrieve blog data (this function calls in create, update and delete success messages) read_retrieve_blogs() function read_retrieve_blogs() { var card = document.getElementById('card'); card.innerHTML = '' $.ajax({ url: "http://localhost:8000/user_blogs/", cache: … -
How to Solve 403 Forbidden Apache2 While Deploying a Django Application to an Ubuntu Server?
The exact error that I got is: Forbidden You don't have permission to access this resource. In /etc/apache2/sites-enabled/portfolio.conf, I copied 000-default.conf and added the following lines: Alias /static /home/kailicen/portfolio/static <Directory /home/kailicen/portfolio/static> Require all granted </Directory> <Directory /home/kailicen/portfolio/portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/kailicen/portfolio/portfolio/wsgi.py WSGIDaemonProcess django_app python-path=/home/portfolio/portfolio python-home=/home/kailicen/portfolio/venv WSGIProcessGroup django_app I also wrote the permission to my project directory: drwxrwxr-x 7 kailicen www-data 4096 Aug 10 06:48 portfolio I don't know what goes wrong. Hope you can help me out. Thanks in advance. -
How can I implement this in my views.py file?
I am working on a network monitor Django website and want to implement tx and rx monitoring commands. wifi_tx = "apstats -a | grep -i 'Tx Data Bytes' | awk '{print $5}'" wifi_rx = "apstats -a | grep -i 'Rx Data Bytes' | awk '{print $5}'" eth_tx = "cat /proc/net/dev | grep -i eth0 | awk '{print $10}'" eth_rx = "cat /proc/net/dev | grep -i eth0 | awk '{print $2}'" -
Using python/Django, is there a way draw a shape in contained in a rectangle box(specifically map of a land) with specific line length and angle
I am trying to generate land ownership certificate using python/django. It needs to include 2d map of the land and I was wondering if there was a way/tool in python to draw it. Thanks in advance -
What can I do to don't show csrf token in the URL line?
I have a form like <form id="..." class="...">. Inside this form, I have 2 buttons, which are tracked with JS like: function one(event) { $.ajax({ type: 'POST', url: "...", data: { 'csrfmiddlewaretoken': csrf[0].value, }, ... }) } function two(event) { $.ajax({ type: 'POST', url: "...", data: { 'csrfmiddlewaretoken': csrf[0].value, }, ... }) } btn1.addEventListener('click', one) btn2.addEventListener('click', two) So, everything works fine. But when I press a button, it creates a post request and in my URL appears something like ?csrfmiddlewaretoken=randomDigits&symbols=&text= What can I do to don't show csrf in my URL? By the way, I don't want to add method="post" to my form. Maybe there are an obvious solution, but I'm new to Django:) -
Django: Null value in column "category_id" of relation "APIs_api" violates not-null constraint
I'm trying to save data into my PostgreSQL database but I seem to get an error on the category_id column that it's null. All other data seems to be submitted correctly but I keep getting this error. Null value in column "category_id" of relation "APIs_api" violates not-null constraint DETAIL: Failing row contains (1, Twilio SMS, Twilio's Programmable SMS API helps you add robust messaging cap..., Twilio's Programmable SMS API helps you add robust messaging cap..., 1, null). The 1 in this case refers to the User ID. Referencing the category_id seems to be the problem. The category in question is SMS with an ID of 34. So the category_id should be 34, since I have 47 categories. I can't find any solution online as many tutorials have the admin input items from the admin dashboard that have a Category as a Foreign Key. I want to achieve these through a form. I have 2 models, API & APICategory Here is my Models.py from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify class API(models.Model): api_name = models.CharField(max_length=30, default='', unique=True, verbose_name="API Name") short_description = models.CharField(max_length=250, default='', unique=True, verbose_name="Short Description") full_description = models.TextField(default='', unique=True, verbose_name="Full Description") category = models.ForeignKey(APICategory, on_delete=models.CASCADE, … -
How do I edit a form with Imagefield without updating Photo?
I've tried numerous ways to fix this error and I can't seem to solve it. I have a form for a user profile, the profile automatically gets created when the user registers and they receive a default photo until they upload their own. When they upload the photo it works just fine including the profile information. However, if they only edit the profile information after already having their own profile photo and do not change the photo I get a MultiValueDictKeyError and the exception value for 'image' below is my views.. def editProfile(request): if 'user_id' not in request.session: return redirect('/') user = User.objects.get(id=request.session['user_id']) context = { 'user': user, } return render(request, 'editProfile.html', context) # updates edited information on profile and updates new image photo. def updateProfile(request, user_id): userProfile = User.objects.get(id=request.session['user_id']) userProfile.profile.location = request.POST['location'] userProfile.profile.favorite = request.POST['favorite'] userProfile.profile.about = request.POST['about'] userProfile.profile.image = request.FILES['image'] userProfile.save() return redirect(f'/userProfile') this is my models: class User(models.Model): first_name = models.CharField(max_length=45, null=True) last_name = models.CharField(max_length=45, null=True) username = models.CharField(max_length=255, null=True) email = models.EmailField(unique=True) password = models.CharField(max_length=45) confirm_pw = models.CharField(max_length=45) objects = UserManager() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.username class Profile(models.Model): user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE) location = models.CharField(max_length=45, null=True) favorite = models.CharField(max_length=255, null=True) … -
Debugging and logging when using Celery
I've been searching through StackOverflow about this topic and haven't found anything updated so I'm asking again: What is the best practice to log when using celery? I've tried many ways and it still doesn't work. Also when I'm trying to use the remote debugger with rdb it doesn't detect the breakpoint -
how to add scroll bar to a CheckboxSelectMultiple for a m2m field in admin panel in django?
I have two models App and Country and there is a many to many field in App to country(the other_countries field) . class Country(models.Model): name = models.CharField(max_length=100, blank=False, null=False) numeric = models.BigIntegerField(blank= True, null= True) key = models.CharField(max_length= 5, blank= True , null = True class App(models.Model): name = models.CharField(max_length=250, blank=True, null=True) description = RichTextField(blank=True, null=True) core_asset = models.CharField(max_length=250, blank=True, null=True) country_of_origin = models.ForeignKey( Country, related_name='country_of_origin', on_delete=models.DO_NOTHING) other_countries = models.ManyToManyField( Country, related_name='other_countries',) in admin panel if I want to add more than one country to my new app model I have to hold the control and select those. but I got more than 200 counries and it gets too difficult to add like 10 countries to app. how can I add a checkbox next to the name of the countries . I added this code in my admin panel class AppAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } admin.site.register(App, AppAdmin) but it shows a very long list of coutries with checkbox.(but without scroll) how can I handle m2m field in admin panel if the numbers of models are too many to use cntrl key and pick them. ps: I have to handle this in admin panel. thank's in advance. -
serialize don't show data
serializer ///////////////////////////////////////////////////////////////////////////// class CommentSerializer(serializers.ModelSerializer): response_to = CommentSerializer2(many=False, read_only=True) # like = LikeSerializer(many=False, read_only=True) like = LikeSerializer(many=False) class Meta: model = Comment fields = ['id', 'user', 'text', 'created', 'response_to', 'post', 'like'] def create(self, validated_data): comment = Comment(user=self.context["user"], **validated_data) comment.save() return comment //////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// model ///////////////////////////////////////////////////////////////////////////// class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments") text = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) response_to = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name="comments") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") like = models.ManyToManyField(User, related_name="like", blank=True) ////////////////////////////////////////////////////////////// view ///////////////////////////////////////////////////////////// @api_view(['PATCH']) @permission_classes((permissions.IsAuthenticated,)) def Comment_like(request, comment_id=False): if request.method == 'PATCH': _comment = get_object_or_404(Comment, id=comment_id) user = request.user if user in _comment.like.all(): _comment.like.remove(user) like = False else: _comment.like.add(user) like = True return Response({'like': like, 'likes': LikeSerializer(_comment.like, many=True).data}, status=status.HTTP_200_OK) -
React components not rendering using babel, webpack and django
I've created Django application and integrated React using Babel and Webpack. I've also created components which don't render (when I replaced component with <h1> and typed some text it worked). index.js import React from 'react'; import ReactDOM from 'react-dom'; import Home from './components/Home'; ReactDOM.render( <Home />, document.getElementById('root') ); index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1" > <meta name="theme-color" content="#000000" /> {% load static %} <link rel="stylesheet" type="text/css" href="{% static "css/index.css" %}" /> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet"> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script src="{% static "frontend/main.js" %}"></script> </body> </html> component function Home() { return ( <> <h1>Home page</h1> </> ); } export default Home; -
How Can I Auto Add URL to User Shared Post with Django Form
I want users to be able to share posts in my web app. How can I automatically generate a unique url in the background while doing this using a django form. I tried a little myself but failed. The reason why I want to create a url: After the posts are shared, they will be listed in the index and users will enter and comment on the post. This is the thing that got me in trouble. Model Form URL (I collected the urls in another app called Pages) Views -
I got a probelm when I was trying to deploy my Django project to Digital Ocean. I followed that tutorial step by step, but it doesn't work on gunicorn
A little background-- Our deployment process is now on using gunicorn, so that means specifically our .wsgi file will be used. But since we never used our .wsgi file when we ran it on our local pycharm to view the site, we figured it would still work when we tried to connect to the server (We have a .wsgi file). However, every time we try to connect the .wsgi file, we get too many errors, and we do not know why. We are very close. What I would like for you to do is please watch this video below, and please tell me why we are running into this error, if possible. Here's the resource we used. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 -
DRF FormData. Passing arguments in querydict as list of one element
Front I request to the server with something like: { "name": "myname" } Back in request.data <QueryDict>: {"name": ["myname"]} And I had to set this for param, val in params.items(): val = val[0] for every dict item. What should I do for getting the correct data? -
Why is the MySQL query taking 25 seconds to give the output?
I have created a MySQL Database in PythonAnywhere but the problem is that it is taking too long to show results. As shown in the image below, it is taking almost 25 seconds to show the databases which I think is not normal. What can I do to solve it? SQL Query -
Making Django model Query case-insensitive
I would like to look up users by their email without worrying about uppercase letters. How would I do this? I tried customer = Customer.objects.get(email__lower="test@gmail.com") and got this error. django.core.exceptions.FieldError: Unsupported lookup 'lower' for EmailField or join on the field not permitted. -
why do i keep getting locking file error install django or django packages?
When I install django or django packages every time I get this error.Pipfile.lock does't occur.Is it a serious problem?If it is, how can ı fix it? -
Does not reflect current user in comment
Hello I am new in the community and in the world of programming so I hope you can excuse my ignorance. I'm creating an Instagram-style application with Django 3.2.5. Where users have profiles to visit and upload photos. I am implementing a commenting system, I have it almost finished or so I think ... Turns out I am stuck ... When generating the comment as a user with a registered profile, the comment is rendered as if it were anonymous. I have investigated and it happens that in the model of the comment I made a relationship with user and profile giving the null parameter as true. When removing this parameter and resubmitting a comment on a post I get an error of 'Not Null Constraint Failed' for profile_id and for user_id (The image shows the first comments made from the admin. And the last one with the null = true parameter in the model) Sample picture Here I leave my models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) text = models.TextField(max_length=200) created_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_date'] def __str__(self): return self.text Here I leave my views.py def create_comment(request, pk): … -
how to output the judgement that is related to the title
I am trying to make website which shows the judgements of various cases based on some conditions. I pushing the data from database, where i upload the title of the judgment and the contents of the judgement. Now in the html file i have written this: {% for data in law_data %} {% if data.law_type == 'civil' and data.law_category == 'limitations' %} <div class="tab"> <button class="tablinks" onclick="openLawtype(event,'title')">{{data.title}} &nbsp<i class="fas fa-chevron-circle-right"></i></button> </div> {% endif %} {% endfor %} Here, after checking the conditions the titles are printed as buttons. The titiles are pushed from the database. Now i want that indvidual titles should show the judgements related to them. i wrote the following code for it: {% for data in law_data %} {% if data.title in data.judgments %} {{data.judgments|safe}} {% else %} <p> no data available</p> {% endif %} {% endfor %} However irrespective of whatever button i press all the judgements that are present in the databse are printed. I am unable to develope the logic for how to print the juudgement that contains the title as part of it and print only the judgement that is related to title. It will be very help full if you can help … -
Python Why Django won't let me load a new product
I'm in this page: Filling the details The link of orange image is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg When I'm pressing 'save' it gives me this: Error message Couldn't understand the issues I tried various ways to solve it like take another picture and re-run the server. From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20 I do not know what this double space between 'user' and 'old' means and I really need help with this I'm stuck on this from Sunday models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('Hello World') def new(request): return HttpResponse('New Products') admin.py from django.contrib import admin from .models import Product admin.site.register(Product) pyshop - urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("products/", include('products.urls')) ] products - urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] -
Django template tags for changing key names in a dictionary
I'm working on a kanji website with Django templates. I have a dictionaries made out of an external xml. I set xml tags as keys. Here is an example of one of those dicitionaries (which casually happens to be about dictionaries... paper ones :P) 'dictionaryEntries': {'nelson_c': '43', 'nelson_n': '81', 'halpern_njecd': '3540', 'halpern_kkd': '4354', 'halpern_kkld': '2204', 'halpern_kkld_2ed': '2966', 'heisig': '1809', 'heisig6': '1950', 'gakken': '1331', 'oneill_names': '525', 'oneill_kk': '1788', 'moro': '272', 'henshall': '997', 'sh_kk': '1616', 'sh_kk2': '1724', 'jf_cards': '1032', 'tutt_cards': '1092', 'kanji_in_context': '1818', 'kodansha_compact': '35', 'maniette': '1827'} Using the following code on template, they are displayed on the website: <ul> {% for key, value in dictionaryEntries.items %} <li><b>{{key}}: </b>{{value}}</li> {%endfor%} </ul> And they get something like following on html: <ul> <li><b>nelson_c: </b>2991</li> <li><b>nelson_n: </b>3715</li> <li><b>halpern_njecd: </b>3497</li> <li><b>halpern_kkd: </b>4309</li> <li><b>halpern_kkld: </b>2179</li> <li><b>halpern_kkld_2ed: </b>2933</li> <li><b>heisig: </b>1555</li> <li><b>heisig6: </b>1675</li> <li><b>gakken: </b>29</li> <li><b>oneill_names: </b>214</li> <li><b>oneill_kk: </b>67</li> <li><b>moro: </b>21670</li> <li><b>henshall: </b>42</li> <li><b>sh_kk: </b>44</li> <li><b>sh_kk2: </b>44</li> <li><b>sakade: </b>34</li> <li><b>jf_cards: </b>71</li> <li><b>henshall3: </b>44</li> <li><b>tutt_cards: </b>43</li> <li><b>crowley: </b>9</li> <li><b>kanji_in_context: </b>49</li> <li><b>busy_people: </b>2.4</li> <li><b>kodansha_compact: </b>1327</li> <li><b>maniette: </b>1569</li> </ul> However, as you can see, key values such as nelson_c are not very user-friendly. I don't want to change the tag name on xml. Is there a way, maybe via tags, to change … -
Django project with Eureka server
Can any one help me how to do django project with Eureka server end to end proper implementation -
Django - How do I leave some fields empty when I click "Save as new"?
I am trying to clone an existing item exactly as is, make edits, and save the new version in the admin. However, I do not want to pre-fill specific fields. I need to leave those specific fields empty in the cloned version and have the user fill them in. How can I do this? What function do I have to override?