Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
AttributeError: 'function' object has no attribute 'get_extra_actions'
I was setting two endpoint for registring and login using DRF and DRF_simpleJWT, and i run into error when i tried to test them. I am using rest_framework.viewsets.Viewset class as parent for my veiwset but it's not working.What should I try, or change? my serializers from Core.Serializers.serializers import UserSerializer from rest_framework import serializers from Core.models import User from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.settings import api_settings from django.contrib.auth.models import update_last_login # The Serializer for the Login functionnality : class LoginSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) # This method is used to validate the data entered by the user. refresh = self.get_token(self.user) # get_token is a method of parent class TokenObtainPairSerializer that is used to retrieve specific token from the database based on the user detail and adding those details. data['user'] = UserSerializer(self.user).data # data is a dict, we are adding the field 'user' to it. data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) # Updating the user last_login fields in the database on condition return data # Data is a dictionnary, it can also be a JSOn, the magic of serializer; # With Django, we need to write form in order to retrieve information # from a post … -
How to redirect an anonymous user until he gets the captcha right
How can I force the an anonymous user to stay in a page by always redirecting him back to it until he gets the captcha in there right? To handle the captcha form I can use django simple captcha, my problem is in how to know if the captcha was solved and if not how I could redirect him. confirmation.html {% extends 'base/base.html' %} {% block content %} <div class="content"> <h2 class="title">Captcha test.</h2> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <div> <button type="submit">Update</button> </div> </form> </div> {% endblock %} forms.py from django import forms from captcha.fields import CaptchaField class ConfirmationForm(forms.Form): captcha = CaptchaField() class Meta(): fields = ['captcha'] def save(self): # some type of anonymous user confirmation variable that I could set to true to stop redirecting the user anonymous.human = True urls.py from django.urls import path from home.views import Confirmation, Home urlpatterns = [ path('', Confirmation, name='confirmation'), path('', Home, name='home'), ] views.py def Confirmation(request): if request.method == 'POST': if anonymous.human == True: return redirect('home') if anonymous.human == False: return redirect('confirmation') else: form = ConfirmationForm() context = { 'form': form, } return render(request, 'base/confirmation.html', context) def Home(request): if human == False: return redirect('confirmation') context = { ... } … -
Save batton doesn't save review changes to the server
Learning Django and have some problem. I created a function to change user review, but when I click on the save button, nothing happens. "Submit" doesn't submit data to the database. views.py def my_reviews(request): reviews = ProductReview.objects.filter(user=request.user).order_by('-id') return render(request, 'user/reviews.html', {'reviews':reviews}) def save_review(request, pid): product = Product.objects.get(pk=pid) user = request.user review = ProductReview.objects.create( user=user, product=product, review_text=request.POST['review_text'], review_rating=request.POST['review_rating'], ) data = { 'user': user.username, 'review_text': request.POST['review_text'], 'review_rating': request.POST['review_rating'], } avg_reviews = ProductReview.objects.filter(product=product).aggregate(avg_rating=Avg('review_rating')) return JsonResponse({'bool': True, 'data': data, 'avg_reviews': avg_reviews}) def update_review(request, id): review = ProductReview.objects.get(pk=id) msg=None if request.method=='POST': form = ReviewAdd(request.POST,instance=review) if form.is_valid(): saveForm = form.save(commit=False) saveForm.user=request.user saveForm.save() msg = 'Отзыв изменен' return redirect('user/reviews') form=ReviewAdd(instance=review) return render(request, 'user/update-review.html', {'form':form, 'msg':msg}) review.html {% extends 'base.html' %} {% load static %} {% block content %} <main class="container my-4"> <h3 class="my-4 border-bottom pb-1">Reviews</h3> <div class="row"> <div class="col-md-3"> {% include 'user/user-sidebar.html' %} </div> <div class="col-md-9"> <div class="table-responsive"> <table class="table-bordered table"> <thead> <tr> <th>Title</th> <th>Image</th> <th>Price</th> <th>Review text</th> <th>Review rating</th> </tr> </thead> <tbody> {% for review in reviews %} <tr> <td><a href="/product/{{review.product.id}}">{{review.product.title}}</a></td> <td> <img width="100" src="/media/{{review.product.image}}" alt="{{review.product.title}}"> </td> <td>{{review.product.price}}</td> <td> <a href="{% url 'update-review' review.id %}" class="float-right"><i class="fa fa-edit"></i></a> {{review.review_text}} </td> <td>{{review.review_rating}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </main> {% endblock %} update-review.html … -
Geodjango: Annotate count points within polygons
I have two models: class State(models.Model): geom = models.MultiPolygonField() name = models.CharField() class Disease(models.Model): geom = models.PointField() date = models.DateField() How can I annotate the count of Disease points within the State model. -
How to check if two polygons have internal points in common, with geodjango and postgis
I am am using geodjango with postgis backend. Giving two polygons I want to check if they overlap. I mean, they have interior points in common. If we check A.function(B) In the following picture "Example 1" would be False, "Example 2", would be False (cause they only have edges in common) and "Example 3" Would be True, cause they have interior points in common. If both polygons are equal, the the function would return True as well. -
Django and AJAX: stop setTimeout after a value is updated
I want to use AJAX to "watch" a webpage while some data processing is ongoing in the background using celery AJAX file, worklist_download_ajax.js (function worker() { console.log('worker'); var ids = $('#Ids').val(); var timer = setTimeout(worker, 5000); data = { 'ids': ids } $.ajax({ url: "/update_worklist_download_status", type: 'get', data: data, dataType: "json", success: function(data) { var div = $('#download-status-info'); div.replaceWith(data.html_worklist_sample_container); // get done boolean value from data and if done, then all // data processing is done and want to stop setTimeout if (data.done === true) { console.log('done = true'); clearTimeout(timer); // doesn't seem to work timer = 0; }; console.log('replaced') }, // complete: function(data) { // // Schedule the next request when the current one's complete // setTimeout(worker, 5000); // } }); })(); django view ajax request, views.py def update_worklist_download_status(request, **kwargs): logger.info('update_worklist_download_status()') data = dict() if request.is_ajax(): logger.info('AJAX') ids = request.GET.get('ids', None) if ids: object_list = MyModel.objects.filter( id__in=ids.split('&')) # check is still need downloading downloading = object_list.filter(download_technical_report=False) logger.info(downloading) if downloading.count() >= 1: data['done'] = False else: data['done'] = True data['html_worklist_sample_container'] = render_to_string( 'results/worklist_templates/worklist_sample_container.html', {'object_list': object_list}) return JsonResponse(data) else: print('NO Ids') The view passes the done=True value correctly to AJAX function worker(), however I can't get it to stop "watching" the … -
connect Oracle 19c database schema/tablespace with Django application
The client provided the single oracle( version 19c ) database in which 2 custom schemas are created and each has a separate tablespace. I need to connect those schemas/tablespaces with 2 separate Django projects, One schema for each Django project. I am unable to connect those schemas/tablespaces with the Django projects. When I run migration all the tables are created under the USERS tablespace of the oracle database. I tried with few possible solutions that are available on the internet, such as, Add DEFAULT_TABLESPACE in the settings.py file of each Django project. add class Meta and configure db_tablespace in each class in the models.py file. kindly help me with this and provide any possible solution. Let me know If anyone requires more details. Thank you.