Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %} -
Conditional Boolean Attribute in Django
I want to have a BooleanField private in my models for my project, but I only want to show this, if another field has a particular value. This is my Model: class Scope(models.TextChoices): COMPANY = 'company', _("Company") TEAM = 'team', _("Team") INDIVIDUAL = 'individual', _("Individual") class Objective(models.Model): name = models.CharField(max_length=500, verbose_name=_("name")) scope = models.TextField(_("Scope"), max_length=15, choices=Scope.choices, db_index=True, default=Scope.TEAM) is_private = models.BooleanField(default=False, verbose_name=_("private")) def __str__(self): return self.name Now I only want to show the is_private BooleanField in the Form, when the Scope of the Objective is INDIVIDUAL. How can I do this? -
Handle revoke command from inside task
Is there a way to handle revoke commands inside the task logic? Since I'm doing some computations and database manipulation on RUNNING tasks I'd like to handle a revoke user request using the data of the task itself. I've already tried capturing the celery.exceptions.Terminated or celery.exceptions.WorkerTerminated exceptions but it doesn't seem to work as expected. from celery import shared_task, exceptions @shared_task( name="tasks.trigger_sales", bind=True ) def trigger_sales_job(self): try: logger.info('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(self.request)) # Do some work on DB return True except (exceptions.Terminated, exceptions.WorkerTerminated) as e: logger.warning(f"Task {self.request.id} has been terminated by user request.") -
Convert model objects in OrderedDict to Json django
In [32]: obj OrderedDict([('code', 'COO21'), ('name', 'sai'), ('country', <Country: INDIA>)]) Error:- TypeError: Object of type Country is not JSON serializable Not able to convert model objects in ordered dict to json -
Django Channels tests: Task x got Future y attached to a different event loop
Whilst trying to test a websocket consumer, I get this error: Error Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/usr/local/lib/python3.10/asyncio/queues.py", line 159, in get await getter asyncio.exceptions.CancelledError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/asgiref/testing.py", line 73, in receive_output async with async_timeout(timeout): File "/usr/local/lib/python3.10/site-packages/asgiref/timeout.py", line 65, in __aexit__ self._do_exit(exc_type) File "/usr/local/lib/python3.10/site-packages/asgiref/timeout.py", line 102, in _do_exit raise asyncio.TimeoutError asyncio.exceptions.TimeoutError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/asgiref/sync.py", line 218, in __call__ return call_result.result() File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 439, in result return self.__get_result() File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 391, in __get_result raise self._exception File "/usr/local/lib/python3.10/site-packages/asgiref/sync.py", line 284, in main_wrap result = await self.awaitable(*args, **kwargs) File "/opt/project/backend/src/sergei/websocket/tests.py", line 57, in test_connection_with_login connected, _ = await self.communicator.connect() File "/usr/local/lib/python3.10/site-packages/channels/testing/websocket.py", line 36, in connect response = await self.receive_output(timeout) File "/usr/local/lib/python3.10/site-packages/asgiref/testing.py", line 82, in receive_output await self.future RuntimeError: Task <Task pending name='Task-14' coro=<AsyncToSync.main_wrap() running at /usr/local/lib/python3.10/site-packages/asgiref/sync.py:284> cb=[_run_until_complete_cb() at /usr/local/lib/python3.10/asyncio/base_events.py:184]> got Future <Task cancelling name='Task-13' coro=<CoreWebsocketConsumer() running at /usr/local/lib/python3.10/site-packages/channels/consumer.py:92>> attached to a different loop With the following code: class CoreWebsocketTest(TransactionTestCase): def setUp(self): self.communicator = WebsocketCommunicator(CoreWebsocketConsumer.as_asgi(), WEBSOCKET_PATH) async def test_connection_with_login(self): connected, _ = await self.communicator.connect() assert connected … -
Improve performance of Graphql (graphene-django) for 4 levels of nested lists
I am using Django 4 with graphene-Django 3 and I need to structure a response that must be 4 levels of lists and the bottom level a dictionary. Here the implementation class FailureSensorType(DjangoObjectType): class Meta: model = FailureSensor spectra = graphene.Field(SpectraGraphType) ... rest of fields class SpectraGraphType(graphene.ObjectType): name = graphene.List(graphene.String) spectra_z = graphene.List(graphene.List(graphene.List(SpectraZGraphType))) class SpectraZGraphType(graphene.ObjectType): _id = graphene.String(required=False) collection_name = graphene.String(required=False) values = graphene.List(graphene.Float, required=False) values_names = graphene.List(graphene.Int, required=False) sidebands = graphene.List(graphene.Float, required=False) rpm_detected = graphene.Int(required=False) anomaly = graphene.Int() def resolve_spectra(self, info): if self.anomaly_type == "spectra": spectra_name = set() for graph_y in self.get_map_Y(): spectra_name.add(str(self.id) + '-' + graph_y.split()[-1]) spectra_z_list = list() spectra_z_list_new = list() for i, x in enumerate(np.split(self.get_map_Z(), id_z)): spectra_z_list.append(x.tolist()) for spectra_z in spectra_z_list: zero_index_list = list() for index_obj, graph_z_obj in enumerate(spectra_z): zero_index = list() for i, graph_z_value in enumerate(graph_z_obj): if graph_z_value != '{"anomaly": 0}': zero_index.append(i) zero_index_list.append(zero_index) new_z_list = list() for z_obj in spectra_z: new_z = [v for i, v in enumerate(z_obj) if i in zero_index_set] z_dict_list = list() for dict_string in new_z: r = json.loads(dict_string.replace("|", ",").replace("(", "[").replace(")", "]")) if "_id" not in r: r["_id"] = "" if "collection_name" not in r: r["collection_name"] = "" if "rpm_detected" not in r: r["rpm_detected"] = -1 if "values" in r: r["values"] = … -
Why does Django password reset email not sent to btopenworld?
I'm using the Django built in password reset functions and I'm having a weird thing happen. The emails seem to get sent for some people and not others. I tried the system for myself (I have two email addresses) and the Django password reset function works for one of my addresses and not for the other, i.e. I do not receive an automated email with a link to a password reset facility. I'm having problems with a '@btopenworld.com' address. Is this inconsistency a known problem in Django, or have I likely missed something? All my other email functions in the app work perfectly. Thanks -
is there a way to pass string id in django url?
Template.html for all model row This Template is a table to show all my model data when the user click one row tr tag its should direct them to the view of the row to edit or update. tr onclick="location.href='{% url 'quality_control_point_view' object.id %}'" When this object.id was int AutoField it worked just fine for me but when i modify my model so that the primary key is Charfield. an error keep coming <form action="" method="post"> {% csrf_token %} <table id="material_issued"> <tr > <th>{% translate 'Reference' %}</th> <th>{% translate 'Title' %}</th> <th>{% translate 'Product' %}</th> <th>{% translate 'Operation' %}</th> <th>{% translate 'Control Per' %}</th> <th>{% translate 'Type' %}</th> <th>{% translate 'Team' %}</th> </tr> {% for object in table %} <tr onclick="location.href='{% url 'quality_control_point_view' object.id %}'"> <td>{{ object.id }}</td> <td>{{ object.title }}</td> <td> {% if object.raw_product is not None %} {{ object.raw_product }} {% elif object.spare_product is not None%} {{ object.spare_product }} {% else %} {{ object.bom_product }} {% endif %} </td> <td >{{ object.operation.capitalize }}</td> <td>{{ object.control_per.capitalize }}</td> <td>{{ object.type.capitalize}}</td> <td>{{ object.team }}</td> </tr> {% endfor %} <input type="hidden" name="length" id="num" value="{{ table.count }}"> </table> </form> Urls.py for specific row path('Quality/QualityControlPoint/<str:qcp_id>', views.QualityControlPointView.as_view(), Urls.py for all model row path('Quality/QualityControlPoint', views.AllQualityControlPointView.as_view(),name='all_quality_control_point'), View.py … -
In Django how would you setup user permissions for a user to only have access to a rest api?
In our project users can generally login to the system and access vaious web-pages. There is also a rest-api - users can access certain information through rest api as well (token authentication). Now there is one user that only should have api-access - login only through an api call returning the token. Access to web-pages in not desired and should be prevented for this user. How can we set this up? Is it possible right out of the box or is it necessary to adapt permission classes?