Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Solving 502 Bad Gateway Error for a Django Project Nginx - gunicorn - Debian
Hi I am trying to deploy my Django Project to Production for the first time using Nginx and gunicorn on linode. Currently I did not set a venv file I just downloaded all the requirements in the system as a whole. I am using Linode Server and selected Django from the market place and the set system is Debian. The project was working perfectly well with portal 8000 but now I am trying to take it to development. I have made the following steps: sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=Gunicorn service for project After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/DjangoApp/ ExecStart=/usr/local/bin/gunicorn --workers 3 --bind unix:/var/www/DjangoApp/project.sock project.wsgi:application [Install] WantedBy=multi-user.target I can't find the sock file in the project but this is the tree of the project if it helps cd /var/www/DjangoApp: api db.sqlite3 project manage.py media README.md requirements.txt static tac users in the /var/www/DjangoApp/project asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py in my sudo nano /etc/nginx/sites-available/project server { listen 80; server_name 111.111.111.11; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/DjangoApp/; } location / { include proxy_params; proxy_pass http://unix:/var/www/DjangoApp/project.sock; } } here is the log error root@139-177-193-82:~# sudo tail -50 /var/log/nginx/error.log ......................: * connect() to unix:/var/www/DjangoApp/project.sock failed (2: No such … -
Users are not saving in ManyToMany Field drf
I am learning django rest framework and I have a field named users in my Blog Model with ManyToManyField to User and I am trying to save multiple users in .post() request. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name="users") views.py class BlogCreateView(mixins.CreateModelMixin, GenericAPIView): serializer_class = BlogSerializer queryset = Blog.objects.all() def post(self, request, pk, *args, **kwargs): try: return self.create(request, *args, **kwargs) except Exception as e: return Response({"error": "something went wrong"},) serializers.py class BlogSerializer(serializers.ModelSerializer): users = serializers.CharField() class Meta: model = Blog fields = "__all__" def create(self, validated_data): user_usernames = validated_data.pop('users', []) blog = Blog.objects.create(**validated_data) users = User.objects.filter(username__in=users) blog.tagged_users.set(users) return blog It is not saving when I pass user names string like "user1", "user2". Then I thought maybe passing username string may be antipattern then I tried to convert CharField into ListField like users = serializers.ListField(child=serializers.CharField()) but then it showed { "error": "'ManyRelatedManager' object is not iterable" } -
Django how to check if models have a field that contains substring in it
For example class A: logo_img = models.ImageField() cover_img = models.ImageField() So i want to check if model A has any field that contains 'logo' or 'cover' in it. How can i check that -
Djang-Default_storage.open() no such file or directory
I am using default_storage to store contents to a csv file on azure cloud storage. Have used default_storage.open("filepath/subfolder/subfolder1"+filename,"w") to create file. But it gives No such file or directory error when folders and subfolders in "filepath" are not present. Doesn't default_storage creates necessary folders to store a file in a folder? I tried doing same thing on local file system, through which I came to know that it requires those folders to be created at first. I solved the problem using os.mkdir(). But not sure about azure cloud storage. Also can anyone provide any other source of default storage documentation? since the original documentation is difficult to understand as a beginner for me. Thanks!! -
Vercel doesn't detect repository from Gitlab (University Gitlab)
My university has its own gitlab domain (gitlab.xyz.ac.id) and I want to deploy my university project (a django project) in my university gitlab repository, but when I tried to import gitlab repository in Vercel it didn't detect any repositories that was created in my university gitlab and it just detect the repositories that I've created in my gitlab.com (Note: Both my gitlab.com and university gitlab have the same username) I tried the import third party git repositories option in Vercel too but it still didn't workout and it still didn't detect my uni project repository from my university Gitlab. I've already tried deploying one of my django project from my own repository in gitlab.com with CI/CD and it works fine. But for this case, I need to deploy the project that is located in a repository from my university Gitlab. Does anyone have any idea how to solve this problem? Thanks -
issue installing taming-transformers into django framework(python code)
I am trying to run my dev server for django code and only "bug" left is regarding the taming-transformers module. I get this error message "from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer ModuleNotFoundError: No module named 'taming'" and I can see that the folder is there but it is not recognizing it. anyone know how to resolve this? I have tried a lot of methods and no luck so far :( here is the list of what I have tried so far to get it to work when downloading in the mac terminal: pip install taming-transformers-rom1504 pip install taming-transformers pip install -e git+https://github.com/CompVis/taming-transformers.git#egg=taming-transformers pip install -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers conda install -c conda-forge taming-transformers conda install -c conda-forge taming -
How to add support of multiple options in Django?
I created a filter to only show items with certain values. A list of social measures is displayed. There are two questions about having children and unemployment. We have or don't have children, and we are or aren't unemployed. The main problem is that the filter doesn't work correctly, due to the fact that I only add one option "no" to the entity. For example, we have a social measure "child allowance", and it's paid regardless of income. I created this measure with having children "yes" and unemployment "no". And if the user selects having children "yes" and unemployment "yes", then the page won't show this measure, although the person is entitled to it. Because only "no" was introduced into unemployment. How to enter "no" and "yes" at the same time when creating a measure? And for the site to show this measure regardless of the choice of unemployment. measure_list.html <div class="headtext"> <h3>Choose your life features</h3> </div> <form action="{% url 'filter' %}" method="get" name="filter"> <h3>Do you have children?</h3> <ul> {% for measure in view.get_children %} <li> <input type="checkbox" class="checked" name="children" value="{{ measure.children }}"> <span>{{ measure.children }}</span> </li> {% endfor %} </ul> <h3>Are you unemployed?</h3> <ul> {% for measure in view.get_income … -
How to connect /var/www/DjangoApp/project.sock
Hi I am trying to deploy my Django Project to Production. Currently I did not set a venv file I just downloaded all the requirements in the system as a whole. I am using Linode Server and selected Django from the market place and the set system is Debian. The project was working perfectly well with portal 8000 but now I am trying to take it to development. sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=Gunicorn service for project After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/DjangoApp ExecStart=/usr/local/bin/gunicorn --workers 3 --bind unix:/var/www/DjangoApp/project.sock project.wsgi:application [Install] WantedBy=multi-user.target I can't find the sock file in the project but this is the tree of the project if it helps cd /var/www/DjangoApp: api db.sqlite3 project manage.py media README.md requirements.txt static tac users in the /var/www/DjangoApp/project asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py this is the error that I am getting: -- Logs begin at Mon 2023-02-27 20:51:40 UTC, end at Tue 2023-02-28 01:14:42 UTC. -- Feb 28 01:14:09 111-111-111-11.ip.linodeusercontent.com systemd[1]: Started Gunicorn service for my_app. Feb 28 01:14:09 111-111-111-11.ip.linodeusercontent.com gunicorn[29195]: [2023-02-28 01:14:09 +0000] [29195] [INFO] Starting gunicorn 20.1.0 Feb 28 01:14:09 111-111-111-11.ip.linodeusercontent.com gunicorn[29195]: [2023-02-28 01:14:09 +0000] [29195] [ERROR] Retrying in 1 second. Feb 28 01:14:10 111-111-111-11.ip.linodeusercontent.com gunicorn[29195]: [2023-02-28 01:14:10 +0000] [29195] [ERROR] … -
django can i have any more good orm?
this related with previous question: Django models and orm and foreign key problems but here is some changes in MemosInProduct model: class MemosInProduct(models.Model): product_key=models.ForeignKey(ProductInOrder, on_delete=models.CASCADE, related_name="product_key") memo=models.CharField(max_length=100) _is_deleted=models.BooleanField(default=False) blahblah some codes... added '_is_deleted' field is need for SoftDelete functions. except MemosInProduct, any model definitions and quering targets are same as previous questions. that means i steel need all of OrderList datas with related all of datas combine with it(product, memos): EXCEPTED order_list[0].order_key[0].product_key[0].memo order_list[0].order_key[0].product_key[1].memo order_list[0].order_key[1].product_key[0].memo ... here is the start this question: i realized that need filtering a specific table. that means, i only need do filtering MemosInProduct table. with accepted Almabud's answer, i tried many orm queries and finally get: OrderList.object.prefetch_related( Prefetch('order_key', queryset=ProductInOrder.object.prefetch_related( Prefetch('product_key', queryset=MemosInProduct.object.all().filter(_is_deleted=False))).all() ) ).all() it works fit to my goal. all of OrderList and ProductInOrder displayed well but only MemosInProduct table has filterd. but i want to know that this query has optimized or not. at least, i want to know that this query has no N+1 problems. Additionally, I would appreciate it if you could let me know if there are any other improvements to the query. thank you for read this looong question. -
(Django app) Why is it that the same comment on a post is appearing once for every like it receives from a user?
Apologies for the vague title. I can only really explain this one here. I am currently making a Reddit-style app / site using Django in Gitpod as a project for a diploma-level portfolio course I am doing. I'm not an advanced programmer / web developer at all, so this project isn't anywhere close to the complexity of Reddit, but it's basically just a super-super-lite version of it. A list of posts is displayed on the home page, and if you click into one, you are taken to a page for that post, where you can read anything that the poster wrote themselves, as well as any comments that were left below the post. For the posts and the comments, there is a primitive like/unlike button. As mentioned in the title, it is the like button for comments that is buggy, and I'm just about ready to give up trying to fix it. On the surface, the issue is this: If the comment has 0 likes, and one user likes it, the number ticks up to 1 - the expected behaviour - but if another user comes along and likes it as well, the number ticks up to 2, and the … -
How to add Custom Validation Error in FloatField forms Django
Ive tried to make my custom message error if no inputs given, but its always showing the default message "Please fill out this field!" I have floatfield forms that looks like this forms.py class MyForm(forms.Form): RadioSelectDayaTorsi = forms.ChoiceField(label = "Pilih Input" ,choices=(('D','Daya'), ('T','Torsi')), initial='D', widget=forms.RadioSelect) P = forms.FloatField(label="Daya ", widget=forms.NumberInput(attrs={'placeholder': 'kW'})) n = forms.FloatField(label="Kecepatan Putar ", widget=forms.NumberInput(attrs={'placeholder': 'rpm'})) T = forms.FloatField(label="Torsi ", widget=forms.NumberInput(attrs={'placeholder': 'N-mm'})) def clean(self): cleaned_data = self.cleaned_data RadioSelectDayaTorsi = cleaned_data.get("RadioSelectDayaTorsi") P = cleaned_data.get("P") n = cleaned_data.get("n") T = cleaned_data.get("T") if RadioSelectDayaTorsi == 'D': if not P: self.add_error('P', 'TEST') if not n: self.add_error('n', 'Kecepatan putar harus diisi') elif RadioSelectDayaTorsi == 'T': if not T: self.add_error('T', 'Torsi harus diisi') return cleaned_data views.py def input(request): return render(request, "shaft/input.html", { "form": MyForm(), }) def output(request): form = MyForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data RadioSelectDayaTorsi = cleaned_data.get("RadioSelectDayaTorsi") P = cleaned_data.get("P") n = cleaned_data.get("n") T = cleaned_data.get("T") Tried with if RadioSelectDayaTorsi == 'D': if not P: raise forms.ValidationError('TESTING') also if P == "": still no works -
in upload_file raise ValueError('Filename must be a string') ValueError: Filename must be a string
I know this question has been asked before and i am asking it again because as a newbie to stackoverflow, i can't make comments on people's post yet. I am sending a pdf file from my frontend vue js to django via axios, where i get the file through request.Files.get('document') and the goal is to load it to s3 bucket but i am getting an error: "filename is not a string". I know that the first argument of s3 upload file should take a string and i don't know how to provide that from my request.FILES. I was told i don't need to create a model with fields like fileField for the file upload, that i can directly load the pdf to s3 bucket in views.py just from the request.Files coming from the frontend. I would like your helps guys. here is my code #vue template <div class="pdf-form"> <form enctype="multipart/form-data" @submit="upload"> <div> <h2><b>Adicionar Arquivo</b></h2> </div> <div class=" article-title mb-2"> <input type="text" placeholder="Titulo do Arquivo" v-model="titulo"> </div> <div class="article-file mb-3"> <input type="file" ref="file" class="file-input" @change="selectFile" accept="application/pdf"> </div> <div class=""> <button class="btn btn-success" v-if="document"><i class="fa-solid fa-upload"></i> Upload</button> </div> </form> </div> <script> export default { data(){ return{ titulo:'', document:null } }, methods:{ selectFile(){ … -
Django filter for not null
I have a filter defined as such: class MessageFilterSet(filters.FilterSet): seen = filters.BooleanFilter(field_name="seen_at", lookup_expr="isnull") And it sort of works. But it's the wrong way around, passing seen=True will return all the unseen messages. I don't want to have to change the name of the url parameter, how do I invert the lookup expression? -
How to create a pdf download button?
I am trying to create a button to download PDFs as a begginer. This is the code: index.html: <a href="{{ product.pdf }}" download> <button class="text-bg-success rounded mx-auto border-0 shadow rounded" style="width: 100%;height: 100%; margin-top: 30px;"> Download </button> </a> models.py: class Product(models.Model): pdf = models.FileField(upload_to='uploads/pdfs/', blank=False, null=False , validators=[FileExtensionValidator(allowed_extensions=["pdf","epub"])]) When I inspect the button it shows the wright file: <a href="uploads/pdfs/Havamal__the_Words_of_Odin_Paul_Edwards_Hermann_Palsson_z-lib.org.pdf" download=""> <button class="text-bg-success rounded mx-auto border-0 shadow rounded" style="width: 100%;height: 100%; margin-top: 30px;"> Download </button> </a> But when I click it, it opens a new tab and does nothing. I am thinking of instead making a link to a blank page that when opened starts a download since that might work better, but I have no knowledge of what that would require. Or maybe there is a form for this type of stuff. It would be especially useful to find another way since I might need to present it on older computers without newer browser versions. I tried to click the download button for a product with no pdf file attached to it and it downloaded the html code for the page itself. It is not the browser version since it worked with the w3school model provided by them. I … -
Python - How to use renderPM in a temp file to convert a SVG
I need to convert a svg image to a png using renderPM. I'm using a library to generate a payment qr code and it produces a SVG output inside of a temp file. But when i try to convert the svg i got this error: my error the code: with tempfile.TemporaryFile(encoding='utf-8', mode='r+') as temp: order_bill.as_svg(temp) temp.seek(0) drawing = svg2rlg(temp) drawing.scale(300 / 72, 300 / 72) renderPM.drawToFile(drawing, temp, fmt='PNG', dpi=300) order.qr_bill.save('qrbill.png', File(temp), save=True) Thank you very much for your help :) I've tried to convert it using cairo but it does not work on my machine (m1 max macbook) -
Reverse for 'athlete_profile' not found. 'athlete_profile' is not a valid view function or pattern name
the error says: Error during template rendering In template base.html, error at line 80 Reverse for 'athlete_profile' not found. 'athlete_profile' is not a valid view function or pattern name. @login_required def athlete_profile(request): if request.user.is_athlete: athlete = request.user.athlete return render(request, 'users/athlete_profile.html', {'athlete': athlete}) else: return redirect('home') this is my athlete_profile view. <a href="{% url 'athlete_profile' pk=user.athlete.pk %}">Athlete Profile</a> It says that the error is on this line in base.html i've tried changing the view name and urlpattern, commented out parts of my code yet nothing is helping. -
Django changes order for ManyToManyField, but it have to be exactly the same as in post request
I have two models (vehicle and stop). I want to create route for every vehicle, so i've added manyToManyField in my vehicle model. Whenever i send post request with a few stops listed in json object django messes with the order and it won't work like that. What i have to do to save object with exactly the same order as it is provided in post request? Models: class Vehicle(models.Model): nr = models.CharField(max_length=24) route = models.ManyToManyField(Stop, related_name='stop') class Stop(models.Model): name = models.CharField(max_length=64) serializers.py: class VehicleSerializer(DynamicDepthSerializer): class Meta: model = TrainLibrary fields = ['nr','route'] -
How to have multiple SITE IDs?
I'm trying to wrap my head around the Site framework in Django. One part I don't really get is the SITE ID. I am working on a db for my photographer friends to store their content. They have different domains und using the "get_current_site()" shortcut I can get their respective content. However to use the default manager: The CurrentSiteManager is only usable when the SITE_ID setting is defined in your settings. So how would I set multiple SITE_IDs? Can I just make it work based on the domain? And if not how to do a different setting per domain? it's all a single project.. Thank you for your help. -
How to change context in Django using html buttons
So i have 2 models and 1 is associated with other. I have buttons corresponding to a model and i want to pull the data when pressed on the responding button. How can i manipulate context in view (i am using function views) and then update html using buttons with their related context. I don't want to use Javascript. How can i do it with django, or is it possible ? -
How to render the fireball on the canvas?
I recently develop a web game application named warlock using Django. However, I can not render the fireball skill on the web page. This "Fireball" skill says that every time I press the Q and click left mouse button, the player fires an orange fireball. But now I can only render players in the web, not fireballs. I don't know what I wrote wrong. I am still a learner about Django and Python3. If it is a rediculous prolem, please be patients. Thank you. Player code class Player extends AcGameObject{ constructor(playground, x, y, radius, color, speed, is_me){ super(); this.x = x; this.y = y; this.vx = 1; this.vy = 1; this.playground = playground; this.ctx = this.playground.game_map.ctx; this.move_length = 0; this.radius = radius; this.color = color; this.speed = speed; this.is_me = is_me; this.eps = 0.1; this.cur_skill = null; } start(){ if(this.is_me){ this.add_listening_events(); } } add_listening_events(){ let outer = this; this.playground.game_map.$canvas.on("contextmenu", function(){ return false; }); this.playground.game_map.$canvas.mousedown(function(e) { if (e.which === 3) { outer.move_to(e.clientX, e.clientY); } else if (e.which === 1){ if(outer.cur_skill === "fireball"){ outer.shoot_fireball(e.clientX, e.clientY); return false; } outer.cur_skill = null; } }); $(window).keydown(function(e){ if(e.which === 81){ outer.cur_skill = "fireball"; return false; } }); } shoot_fireball(tx, ty){ let x = this.x, y … -
Django Admin search field on foreignkey doesn't work
I am building a django project and try to get a search bar on a "main" field which is called "regnr" (see models & admin modules below) but I get ani contains error when I search. I have tried search_fields = [foreignkey__name] and also [name_id] and also. [name] but nothing seems to work... from django.db import models # Create your models here. class Fordonsregister(models.Model): regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False) namn = models.CharField(max_length=255, null=True, blank=True) tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True) email = models.EmailField(null=True, blank=True) kund_sedan = models.DateTimeField(auto_now=True) kund_points = models.IntegerField(default=0) def __str__(self) -> str: return self.regnr class Meta: ordering = ['regnr'] class ServiceTypes(models.Model): typ = models.CharField(max_length=255, primary_key=True, blank=False) pris = models.DecimalField(decimal_places=2, max_digits=6, null=False, blank=False) beskrivning = models.CharField(max_length=255, null=True, blank=True) def __str__(self) -> str: return self.typ class Meta: ordering = ['typ'] class FordonsService(models.Model): regnr = models.ForeignKey(Fordonsregister, on_delete=models.CASCADE) typ = models.ForeignKey(ServiceTypes, on_delete=models.CASCADE) service_datum = models.DateTimeField() bokat_datum = models.DateTimeField(auto_now=True) kommentar = models.CharField(max_length=1000) class Meta: ordering = ['-service_datum'] And here is the admin module: The problem is with class FordonsServiceAdmin(admin.ModelAdmin): from django.contrib import admin from django.db.models import Count from django.utils.html import format_html, urlencode from django.urls import reverse from django.http import HttpRequest from .models import Fordonsregister, ServiceTypes, FordonsService # Register your models … -
Django Write GenericForeignKey from Serializer
I have four models in my app. The main is called Agency which has a name and the settings of an agency (which can be CTT, GLS or Nacex). So we can have an user who has two agencies of CTT and one of GLS. When I retrieve the agencies it works well, it returns an array of objects. So, for the example of above, it will return something like: [ { "id": 1, "name": "CTT", "type": "ctt", "settings": { "id": 1, "user": "user", "password": "password", "agency_client_code": "12345", "client_code": "12345", "freight_type_code": null } }, { "id": 2, "name": "CTT International", "type": "ctt", "settings": { "id": 2, "user": "user2", "password": "password2", "agency_client_code": "12345", "client_code": "12345", "freight_type_code": null } }, { "id": 3, "name": "dsdsa", "type": "gls", "settings": { "id": 1, "uid": "something" } } ] However, when I try to write to the settings model it gives me an error. I can make it work for just one model by doing this in the AgencySerializer: # In this case, read operations work for every model, but write operations only work for CTT settings = TaggedObjectRelatedField(queryset=CTT.objects.all()) What I need is something like this, so depending on the model, it will return the … -
Fix quotation marks overlapping in Python
The quotation marks here are overlapping (""), escape characters don't work in this example and nor do triple quotation marks. Does anyone have a solution? "<img src="{% static 'images/profile-picture.png'%}" id="profile-picture">" -
How to Run Multiple loops in django template format
I django objects that I need to represent in a table but i need a Sr.Number to iterate for every row. How should i do that?? I tried running miltiple loops {% for patent in patents %} and {% for i in range(len(patents))%} Tried many options but got errors -
close access to url by geolocation reactjs
I have an existential question. Is it possible to block access to a URL by geolocation? The problem is the following, I have a table with its respective QR, the user scanning it allows them to enter table 1, but if the user takes a photo of the QR and takes it home, they can scan it and enter from their house to the table, I need that if you are not in the premises do not allow access, to allow access you have to be within the perimeter. How could I do this using reactjs, nodejs, django, heroku, netlify? thank you so much