Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why isn't "SELECT" query run in Django?
I have person table as shown below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) And, I have test view with print(Person.objects.all()) as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): print(Person.objects.all()) # Here return HttpResponse("Test") Then, when I run test view, SELECT query is run as shown below: Now, I replace print(Person.objects.all()) with Person.objects.all() as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): Person.objects.all() # Here return HttpResponse("Test") Or, I replace print(Person.objects.all()) with persons = Person.objects.all() as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): persons = Person.objects.all() # Here return HttpResponse("Test") Then, when I run test view, SELECT query isn't run as shown below: So, why isn't SELECT query run in Django? -
Django queryset filter based on slug
I want to put a filter on a page which shows videos selecting an album shows up on album page not all the videos but my current filter is showing all the published videos. I couldn't find a way to put a filter based on slug that if an album's slug is matching with the current url then shows the video selecting that album. I am all confused help me. models.py from django.db import models from django.urls import reverse STATUS = ( (1, "Publish"), (0, "Draft") ) class WatchCategory(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(max_length=2000, unique=True) def __str__(self): return self.title class Genre(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(max_length=2000, unique=True) def __str__(self): return self.title class Album(models.Model): title = models.CharField(max_length=2000) slug = models.SlugField(max_length=2000, unique=True) image = models.CharField(max_length=2000, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('Watch:album', kwargs={ 'slug': self.slug }) class Video(models.Model): title = models.CharField(max_length=2000) slug = models.SlugField(max_length=2000, unique=True) thumbnail = models.CharField(max_length=2000, unique=True) updated_on = models.DateTimeField(auto_now=True) file = models.CharField(max_length=2000) time = models.CharField(max_length=2000, blank=True) about = models.TextField(blank=True) category = models.ManyToManyField(WatchCategory) album = models.ManyToManyField(Album) genre = models.ManyToManyField(Genre) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('Watch:video', kwargs={ 'slug': self.slug }) views.py class Album(ListView): … -
using pipreqs getting unknown error while to create requirements.txt
pipreqs .\ the following error is comming. i searched on the google i didn't find any solution. ERROR: Failed on file: .\static\bower_components\jvectormap\converter\converter.py Traceback (most recent call last): File "C:\Users\bsant\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\bsant\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "C:\Users\bsant\Pictures\lms_m16\venv\Scripts\pipreqs.exe_main.py", line 7, in File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 488, in main init(args) File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 415, in init candidates = get_all_imports(input_path, File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 131, in get_all_imports raise exc File "C:\Users\bsant\Pictures\lms_m16\venv\lib\site-packages\pipreqs\pipreqs.py", line 117, in get_all_imports tree = ast.parse(contents) File "C:\Users\bsant\AppData\Local\Programs\Python\Python310\lib\ast.py", line 50, in parse return compile(source, filename, mode, flags, File "", line 139 raise Exception, "Wrong geometry type: "+geometryType ^ SyntaxError: invalid syntax -
How to authenticate with the right scope via OAuth in Django?
I am trying to login to my Django API from my other web app. I setup a application with the Django OAuth Toolkit (Resource owner password-based). The login works fine and I get back an accessToken but the scope I requested is not right. I get back r:profile but wanted instead rw:serverAdmin. The user is a superuser in my Django application and I also added the rw:serverAdmin scope to the oauth toolkit list. So the problem is: How do I login and have the rw:serverAdmin scope assigned? Can anybody help me with this? -
Cannot import name ... from partially initialized module
For a few days, app1 has been importing model2 I have just added model1 to app2 and I am getting this error I cannot undo this error, if I remove the line 'from app1.models import (U_model1)', the error remains - meaning the way it was set up for the last few days no longer works app1 - models.py from app2.models import (U_model2) class model1(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) name = models.CharField(max_length=100, verbose_name="Name") def __str__(self): return self.name class Meta: ordering = ('id', ) app2 - models.py from app1.models import (U_model1) class model2(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) name = models.CharField(max_length=100, verbose_name="Name") def __str__(self): return self.name class Meta: ordering = ('id', ) Why after reverting it to how it's been for the last few days by removing the line causing the error, does it no longer work? -
Django : Downloading PDF generated by the library FPDF
I have a view that contains a wizard form. When the form is submitted, a httpresponse is sent with a PDF file. I generate the PDF file with the FPDF2 Library from the data got in the form submitted by the user. To be sure that the PDF class using this library works, I tested it in a simple python script. My problem comes from the pdf that I download, I can not open it. I have an error "We can't open this file. Something went wrong". So I think that the issue is on the way I send the data of the pdf in the Httpreponse. Here is my code : class FormWizardQR(SessionWizardView): template_name = "invoices/qr.html" form_list = [FormStepOneBeneficiary, FormStepTwoPaymentInfos, FormStepThreeDebtor] def done(self, form_list, **kwargs): # GET DATA FROM FORMS form_data = dict(ChainMap(*[form.cleaned_data for form in form_list])) # PREPARE DATA FOR QR-PDF GENERATOR list_str_pay_to = [form_data.get('iban_beneficiary'), form_data.get('name_beneficiary'), f"{form_data.get('street_beneficiary')} {form_data.get('street_number_beneficiary')}", f"{form_data.get('npa_beneficiary')} {form_data.get('locality_beneficiary')}", form_data.get('country_beneficiary')] list_str_pay_by = [form_data.get('name_debtor'), f"{form_data.get('street_debtor')} {form_data.get('street_number_debtor')}", f"{form_data.get('npa_debtor')} {form_data.get('locality_debtor')}", form_data.get('country_debtor')] reference = form_data.get('ref_number') # GENERATE QR-IMAGE qr = SWISS_QR(data="https://www.20min.ch/fr") image_qr = qr.generate_qr() pdf = PDF('portrait', 'mm', 'A4') pdf.set_margins(left=0, top=0, right=0) pdf.add_page() pdf.border_bill() pdf.r_title("Récépissé") pdf.r_zone_indications(reference=reference, list_str_pay_to=list_str_pay_to, list_str_pay_by=list_str_pay_by) pdf.output(name="myfilename.pdf", dest="S") print(type(pdf)) print(pdf) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=myfilename.pdf" return … -
Django admin get updated model (and updated relative models that are inlines) when "Save" is clicked
I have a model named User and it has some fields, and also some relative models. It's registered in the admin page and some of its relative models are registered as inlines of it. Now, I have a function let's call it update_api(user) which takes the user as an argument (which is an instance of class User) and sends it to an API. Note that this function also uses the relative models of User. I want to call update_api when a user is saved in the admin page but I want all his fields and relative inline models to be updated. Moreover I want this function to be called only once per save. I have tried overriding User.save() or UserAdmin.save_model() but that lead me nowhere because the related fields were not updated by then. When user is saved via a view, I call this function manually at the end after doing a request.user.refresh_from_db(). -
Doubled value when using annotate Sum,Count
I am using this code and I get a result which is not what I expect queryset= User.objects.annotate(earned_leave=Sum('logs__work_hours')) Here is my data "logs": { "id": 96, "time_in": "11:43:34", "time_out": "21:25:49", "user": "admin", "date_created": "2022-10-21", "work_hours": 10, "last_action": "logout", "earned_credit": "0.38400" } and here is the result "earned_leave": 20 Tried this solution but I'm not comfortable with it queryset= User.objects.annotate(earned_leave=Sum('logs__work_hours')/2) I cannot use distinct=True since it won't count same values -
DRF multiple update with reduced database hits
I'm using DRF's example of multiple updates which works fine except every self.child.update is a separate update query to the database. Is there a way I can rewrite this to call the updates as one query as a bulk update? class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) ret.append(self.child.update(book, data)) return ret class BookSerializer(serializers.Serializer): id = serializers.IntegerField() class Meta: list_serializer_class = BookListSerializer -
Django ORM question about methods for the QuerySet Object
Can someone explain to me why you can use a method like count() for a QuerySet Object but something like pop() does not work. -
Djstripe: ensuring new subscription payment succeeds before confirming successful subscription to customer
We use Djstripe to create Stripe subscriptions on our Django site like so: # Create the Stripe subscription stripe_subscription = stripe.Subscription.create( customer=customer_id, items=[{'price': plan_id}], expand=['latest_invoice.payment_intent'], metadata=metadata, ) # Sync subscription from Stripe subscription = Subscription.sync_from_stripe_data(stripe_subscription) The process on Stripe's end seems to be something like: Create the subscription (return status 200) Create the payment intent object that will charge the customer for the subscription Attempt to charge the customer If the charge fails, put the subscription to status "incomplete" Naively, when we get 200 back from step (1), we proceed as if the payment went through ok, but sometimes it doesn't (step (4) happens). What is a good way to confirm a successful subscription creation to the customer oly if the subsequent charge succeeds? -
Return a specific field using ForeignKey
class Client(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) client_name = models.CharField('Nom et prénom', max_length=120) def __str__(self): return self.client_name class OtherInfos(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) client_name = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) client_detail = models.TextField('détails', blank=True) def __str__(self): return str(self.client_name) class information(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) info_name = models.ForeignKey(patientlist, null=True, on_delete=models.CASCADE) info_data = models.TextField('More info', blank=True) info_evolution = models.ForeignKey(OtherInfos, null=True, on_delete=models.CASCADE) def __str__(self): return str(self.info_name) Hello everyone, I have these 3 tables : a "Client" can have multiple "information" and "OtherInfos", and i would like to show all data in one html page, i managed to do 90% of it using Foreignkey where i can get "information" and "Client" data in the html page, but it didn't work with "OtherInfos", any suggestions please ? thank you -
Rendering model in Django
New to Django. Instead of writing a template, is there a way to render a model similar to crispy rendering input forms? {{ pro_form|crispy }} -
Is there a way to file.create() a file with file type of MISCBINARY aka other binary file with suitescript
Title says it all, has anyone figured out a way to create and save a file with the equivalent of what would be the enum file.type.MISCBINARY via suitescript suitelet N/file module (this does not exist in any documentation) I have already found that I can upload any file to whatever ns file type I want regardless of file mime or .ext however I would like to not just upload files to the wrong NS enum just to get the job done. example, I am currently creating .msg files under the type enum file.Type.MESSAGERFC as this is the closest match however if uploaded through drag and drop the type field is MISCBINARY I have been through all of the documentation and even dug into several of the object properties, I also took a look at the form object of a MISCBINARY file uploaded through the NS drag and drop feature. I have tried in the type field: file.Type.MISCBINARY 'MISCBINARY' 'miscbinary' 'otherbinaryfile' I also tried to set the file.fileType property by file.fileType = 'MISCBINARY' of course this did not work since this property is readOnly but it was worth a shot. -
How can i group by my model into multiple table in django as below?
Let's say i have this table: | Name | Age | Country | -------------------------- | A | 17 | England | -------------------------- | B | 18 | Swiss | -------------------------- | C | 19 | Italy | -------------------------- | D | 19 | Italy | -------------------------- | E | 19 | England | ------------------------- as any column will contain distinct value like in this example country column contain 3 distinct value (England, Swiss, Italy) as well as age (17, 18, 19) And i want django query to sort the table by the country column as follow: >England | Name | Age | Country | -------------------------- | A | 17 | England | -------------------------- | E | 19 | England | -------------------------- >Italy | Name | Age | Country | -------------------------- | C | 19 | Italy | -------------------------- | D | 19 | Italy | -------------------------- >Swiss | Name | Age | Country | -------------------------- | B | 18 | Swiss | -
how to prevent from resize the image with every save object in dadtabase?
I have this model: class Book(models.Model): title = models.CharField(max_length=256) price = models.IntegerField() category = models.ForeignKey('Category', on_delete=models.PROTECT) rating = models.FloatField(validators=[MaxValueValidator(10), MinValueValidator(1)]) discount = models.IntegerField(blank=True, default=0) final_price = models.IntegerField(blank=True) created_date = models.DateTimeField(auto_now_add=True) description = models.TextField(blank=True, null=True) count = models.IntegerField(default=0) author = models.ForeignKey('Author', on_delete=models.PROTECT) image = models.ImageField(upload_to=_get_product_cover_upload_path, null=True, blank=True) def resize_image(self): img = Image.open(self.image.path) img.thumbnail((300, 300)) img_w, img_h = img.size background = Image.new('RGBA', (400, 400), (255, 255, 255, 255)) bg_w, bg_h = background.size offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2) background.paste(img, offset) background.save(self.image.path) def __str__(self): return f'{self.title}' def save(self, *args, **kwargs): self.final_price = self.price * (100 - self.discount) / 100 super().save(*args, **kwargs) self.resize_image() it worked well but when I modify the book model for example change the price, image will get smaller than last time and with every save the object it get samller... How can I fix it? -
Why does accessing Django object cause page to not finish loading?
I'm setting up my django project in a production environment and I'm getting this strange behavior where a page will render, but the loading icon in the Chrome tab will keep spinning. It ultimately ends in a "Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR" error after it hits the timeout limit. After extensive debugging, I found that this happens whenever a database call is made on a view. It's most easily seen when trying to open up a table on the admin site. The main screen itself loads just fine, but then won't load when you select a table to edit. On the main webpage, the data itself loads just fine, and the resulting template looks just as expected, except the page never finishes loading. As a final note on the issue, this works perfectly fine in the local dev server, but not when I run this site in a production environment I've tested this both in Chrome and Edge, incognito window, and had a friend look up the page from their home to make sure it wasn't something on my end. I'm using Django 4.1 and python 3.10 with a sqlite database: # I realize this is redundant since the user … -
ModuleNotFoundError: No module named 'wagtail.contrib.postgres_search'
I am new to Django and I try to setup an existing project on my local computer. I installed: python -m pip install wagtail and then try to run the project: python manage.py runserver Got this error: File "C:\Python310\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'wagtail.contrib.postgres_search' I also tried to run python manage.py migrate and got the same error. What am I doing wrong? I tried to google it and read https://docs.wagtail.org/en/v2.13.2/reference/contrib/postgres_search.html carefully, INSTALLED_APPS and WAGTAILSEARCH_BACKENDS is set in my settings.py Here is my python version: Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32 What should I install to get rid of this error and finally launch the project? -
How to modify a GET request to trigger a file attachment response (legitimately)?
I have a Django project that uses the python chess module to show a chess board in the main view. It defaults to a blank board: views.py import chess, chess.pgn def index(request, pgn_slug=None): board = chess.Board() game = chess.pgn.Game.from_board(board) game.headers["DrawOffered"] = "False" The main index function catches AJAX requests and serves responses: from django.http import JsonResponse if request.headers.get('x-requested-with') == 'XMLHttpRequest': ... return JsonResponse(response_obj) Or it will render the page: from django.http import HttpResponse else: html = get_html(game, board) return HttpResponse(html) I want one elif to return a .txt attachment based on the python-chess game writing functions. How do I achieve this with well-formed requests and responses? Django seems to have a dedicated response object for this kind of thing but I can't quite put two and two together. Something like this maybe?: from django.http import FileResponse elif request._____ == 'download': # what could mark the request? file_name = 'foo.txt' file = open(filename, 'wt') file.write(str(game)) return FileResponse(file, as_attachment=True, filename=file_name) The request is triggered by a button on the same page and a JavaScript function and would either call up the URL of the window or one that gets dynamically passed to the function from AJAX: <script> function downloadPGN(URL) { if (URL … -
Django - Get user with highest bid
I need to get the user who placed the highest bid for the listing on an auction site. models.py: class Listing(models.Model): class Category(models.TextChoices): BOOKS = 'Books' SPORTS = 'Sports' DEATHLY_HALLOWS = 'Deathly Hallows' CLOTHING = 'Clothing' WANDS = 'Wands' JEWELRY = 'Jewelry' title = models.CharField(max_length=64) description = models.TextField(max_length=320) starting_bid = models.DecimalField(max_digits=10, decimal_places=2, default=0) current_price = models.DecimalField(max_digits=10, decimal_places=2, default=0 ) img_url = models.URLField(blank=True) category = models.CharField(choices=Category.choices, max_length=64, blank=True) is_closed = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) winner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="Winner") def __str__(self): return f"{self.title}" class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, default=1) bid = models.DecimalField(max_digits=10, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="Bidder") views.py: def listing(request, listing_id): highest_bid = Bid.objects.aggregate(Max('bid')) winner = highest_bid.user print(winner) Returns the error: 'dict' object has no attribute 'user'. How can I get the user from the maximum bid placed on the listing? -
how to transfer money directly from website paypal to bank using python
I need Help I have a website from which user add money to my paypal and i want a python script to send money from my wallet on one website to any bank account. -
nginx location points to django but it is going to react app
I have a React frontend and a Django backend, both organized in a docker-compose with port 7000 exposed to React, and port 9000 exposed to Django. This system is hosted in a server machine whose nginx location config is the following: [...] location / { proxy_pass http://localhost:7000/; } location /django { proxy_pass http://localhost:9000/; } [...] Suppose the server_name is example.com. The problem is: if I access example.com/django/admin, a blank react page is returned instead of the django-admin login one. How can I solve it? -
PostgreSQL using a FK wih two databases (Django)
This might be a duplicate, I've looked at some solutions but I can't figure out how to implement this. I have the following Django models: class ClientInfo(models.Model): client_name = models.CharField(max_length=400) class PatientFiles(models.Model): client = models.ForeignKey(ClientInfo, on_delete=models.CASCADE) file_name = models.CharField(max_length=400, blank=True) file = models.FileField(upload_to=content_file_name) For the purpose I'm developing this, I need the ClientInfo to be on a separate database from the one in which I have the uploaded files for each client. I've read that this isn't possible without some rough implementation, which I really don't want to do. Would there be any other way I could get the same result? One of the requirements is specifically using other database for the ClientInfo so I really can't budge here. I was thinking on possibly creating the ClientInfo model on a model_save manually and adding a possibly hashed ClientInfo id in the PatientFiles model. Is this a good idea, if not, does anyone have a suggestion? Thank you in advance. -
How to use Django json_script in a for loop
Let's say we have in a template a table like {% for object in object_list %} <tr> <td id="id-{{object.id}}">{{ object.id }}</td> </tr> {% endfor %} How do you use json_script to get the object.id in a JavaScript script? -
'AnonymousUser' object has no attribute '_meta' error in Django Register function
I was trying to do Register and Login form but I am taking "'AnonymousUser' object has no attribute '_meta'" error I hope somebody can help me. And also if you have suggestion for better code writing or better way for this form I would be happy. Here is my views.py from django.shortcuts import render,redirect from .forms import RegisterationForm from django.contrib import messages from django.contrib.auth import login as dj_login from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import logout as dj_logout def register(request): if request.method == "POST": form = RegisterationForm(request.POST) if form.is_valid(): user = { "username" : form.cleaned_data["username"], "email" : form.cleaned_data["email"], "password1" : form.cleaned_data["password1"], "password2" : form.cleaned_data["password2"] } user = form.save() dj_login(request,user) messages.success(request,"Kayıt İşleminiz Başarıyla Gerçekleştirilmiştir.") return redirect("index") else: messages.error(request,"Kayıt İşlemi Sırasında Bir Hata Meydana Geldi.") return render(request,"register.html",context={"RegisterForm":form}) else: form = RegisterationForm() return render(request,"register.html",context={"RegisterForm":form}) And here is my register.html file. {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block title %} Register {% endblock title %} {% block body %} <h1>Register</h1> <form method="post"> {% csrf_token %} {{RegisterForm.username.label}} {{RegisterForm.username}} <br><br> {{RegisterForm.email.label}} {{RegisterForm.email}} <br><br> {{RegisterForm.password1.label}} {{RegisterForm.password1}} <br><br> {{RegisterForm.password2.label}} {{RegisterForm.password2}} <br><br> <button type="submit">Kayıt Ol</button> </form> {% endblock body %}