Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
setting conditional serializer class removes the custom serializer class for extra action in Django rest framework
I have one modelviewset and couple of extra actions for it. class TestViewset( mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, GenericViewSet, ): permission_classes = [CustomPermissionClass] def get_serializer_class(self) -> Type[ModelSerializer]: if self.action == "list" or self.action == "get": return FirstSerializer return SecondSerializer @action( detail=True, methods=["POST"], url_path="test-path", url_name="test-path", serializer_class=MyCustomSerializer, ) def test_path(self, request: Request, **kwargs) -> Response: print(self.get_serializer()) # Despite setting the 'MyCustomSerializer' it still gives me 'SecondSerializer' return Response(status=status.HTTP_200_OK) If I remove the get_serializer_class method and give only one serializer it works. What could be the best solution for this or is this any bug in drf? Ideally the extra action should use the serializer class that has been provided but its not. -
Compare and groupby using Django ORM
I have 8 objects from 2 different models. Say, Fruit and Colour I want to filter and group Fruits based on Benefits. For instance, Orange and Grapes can be grouped together because they share similar benefits , i.e. "rich in vitamin C" Here's my code: models.py class Fruit(models.Model): name = models.CharField(max_length=40, blank=True, null=True) colour = models.CharField(max_length=40, blank=True, null=True) benefits = models.JSONField(default=dict) class Benefit(models.Model): health_benefit = models.CharField(max_length=240, blank=True, null=True) I tried the following: all_benefits = Benefit.objects.values_list('health_benefit') Fruit.objects.filter(benefits__in=all_benefits) Not sure if this is the correct way to query. Thanks in advance. -
How to pass non string to innerHTML
I am using django, basically i am trying to change some part of the html code using javascript. below chart work nicely <div id='treemap_charts'> {{ treemap_code.first.treemap_price_difference_yesterday|safe }} </div> with final result being <div id='treemap_charts'> HTML code </div> However, when I added some javascript to alter the content inside the div id='treemap_charts' as shown below: <script> document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#treemap_options").onchange = function() { if (this.value==='day') { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_yesterday}}'; } else { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_month}}'; } } }); </script> <div> <select id='treemap_options' name='Treemap Charts'> <option value='day' selected>1 Day Performance</option> <option value='week'>1 Week Performance</option> </select> </div> <div id='treemap_charts'> {{ treemap_code.first.treemap_price_difference_yesterday|safe }} </div> the HTML result end up as a string instead of HTML code <div id='treemap_charts'> "HTML code" </div> PS:I try to use this code but it does not work <script> document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#treemap_options").onchange = function() { if (this.value==='day') { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_yesterday|safe}}'; } else { document.querySelector('#treemap_charts').innerHTML='{{treemap_code.first.treemap_price_difference_month|safe}}'; } } }); </script> Anyidea how I can pass {{ treemap_code.first.treemap_price_difference_yesterday|safe }} to the div without it changing to string? I search around the forum but seem unable to get the answer but one thing I learn is at least in the HTML need to have |safe else it will not work... -
Editing foreign keys in django-forms
I recently got into django and django forms. What i'm trying to do is make a form where my foreign key is editable. (a form of the other model where my foreign key is refering to inside a form). so lets say I have these models class Model2(models.Model): name = models.CharField(max_length=50) class Model1(models.Model): type = models.ForeignKey(Model2, on_delete=models.CASCADE) value = models.CharField(max_length=50) # other fields When you render the form for Model1, the foreign key must be editble aswell. I'm wondering if anything like this is possible -
Is there way to gracefully remove a Django plugin from the project
We have installed a charting plugin in our Django project, but we found another one that more suits our requirements. Is there a way to gracefully remove the plugin from our project? -
Django how to force page reload on event
I am developing an application that communicates with measurement system. Clicking "start test" button causes redirection to the "test_in_progress" view which is just a sign "test in progress" with progress spinner. In that view the application awaits response from the measurement system. I want to redirect to the "test_results" view when the message comes and I don't really know how to do that. Should I just set some flag and in "test_in_progress" page poll for the flag periodically with js (if this is the right approach then how to do that?). Or is there any way to force page redirection from within python? -
using Hebrew language in django and xhtml2pdf to save pdf
Hi I can't figure this up but how do I save pdf with Hebrew charcters in xhtml2pdf I can't find anything online the code suppose to acceses a property from the database and then create a pdf file and sent it to the client mail pyhon code that convert template to pdf from django.template.loader import get_template from os.path import join from .utils import render_to_pdf from django.http import HttpResponse from xhtml2pdf import pisa def generate_pdf(property): template = get_template("main/pdftabo.html") context = { "address": f'{property.street} {property.building_number} {property.city}', "owners": property.owners, "loan": property.loan, "plot": property.plot, } html = template.render(context) filepath = join('static',f'media/{property.block}{property.lot}.pdf') write_to_file = open(filepath, "w+b") result = pisa.CreatePDF(html,dest=write_to_file) write_to_file.close() the pdf template html code <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> {% load static %} <html lang="heb"> <head> <meta charset="character_set"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> @font-face { font-family: MyRightToLeftFont; src: url("{% static 'fonts/ahronbd.ttf' %}") } p { font-family: MyRightToLeftFont } </style> </head> <body> <pdf:language name="hebrew" /> <p>שלום</p> <table> <tr> <th>מגרש</th> <th>מס' בית</th> <th>מס' הדירה לפי הסכם המכר</th> <th>מהוות הנכס</th> </tr> <tr> <th>{{plot}}</th> <th>7</th> <th>1</th> <th>{{address}}</th> </tr> </table> </body> </html> image of what i get -
How to embed a Django application on a Wix website?
How do I embed a Django application inside a Wix website? I have my app hosted on a server, but now I want to embed this app inside a Wix website. I've made a couple of changes to the settings.py such as Commenting out csrf middleware and Xframeoptions middleware. Added these lines SESSION_COOKIE_SAMESITE = 'None' # As a string SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'ALLOWALL' XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE'] Added @csrf_exempt on top of every function in my views.py file. Although it's rendering the website, the only function that does not work is the sign in and register option, and that too only in the Wix website, it works fine when I sign in or register through the actual server domain but not when I do it through Wix. I'm not sure if it has something to do with Wix itself or Django, so can someone help my figure this issue out if it is even possible in the first place? -
Changing the default user while using REST framework JWT
I have a proxied user model: class TheDude(User): class Meta: proxy = True And I'm using the Django REST framework JWT to do JWT auth in the REST API. I'd like to get the user object from the request but currently it's a User object. Because it's proxied I can't use AUTH_USER_MODEL. I've tried doing a middleware component to override the user in the request but it's not set at that stage. I've also tried using JWT_RESPONSE_PAYLOAD_HANDLER however my function isn't called so I can't set it there either. If I want to be able to get TheDude object when I call request.user instead of User in my views, how would I do this while authing using the REST framework JWT Auth library? -
Django, How to update DateTimeField attribute only when one specific attribute is changed
I would like to update the attribute date_assigned only when the attribute Customer is changed. I know that I have to overwrite the save function within the same model but i don't know exactly how. class Ip(models.Model): customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) ip = models.GenericIPAddressField(protocol="IPv4", null=False, unique=True) date_created = models.DateTimeField(auto_now_add=True,) date_updated = models.DateTimeField(auto_now=True,) date_assigned = models.DateTimeField(auto_now=True) Any ideas? thanks in advance. -
Unable to publish data from inherited class - paho django
Initialized paho mqtt as a class class Initializer(): def __init__(self): self.client = mqtt.Client(mqtt_server+str(int(time.time()))) self.client.username_pw_set( username=mqtt_username, password=mqtt_password) self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_subscribe = self.on_subscribe self.client.connect(broker, mqtt_port) self.client.loop_start() def on_connect(self, client, userdata, flags, rc): if rc == 0: #app_logger.info("Device Connection Established") print("Device Connection Established") else: #app_logger.info("Bad Connection") print("Bad Connection") then i have created a another class that inherits initializer class class send(Initializer): def __init__(self): super().__init__() self.client.publish("topic","data") able to print the value of self.client inside the initialization of send class but not able to publish data. -
Does form_valid() in CBV not call is_valid() method?
When I used function views, It was able to handle cleaned_data with overriding form.clean() method. I thought when I call form.is_valid method, form.clean() is called too. Form validation happens when the data is cleaned. If you want to customize this process, there are various places to make changes, each one serving a different purpose. Three types of cleaning methods are run during form processing. These are normally executed when you call the is_valid() method on a form. Now I'm trying to do same things with class-based-view, but it does not work as I thought. Here's my forms.py: class PublishForm(forms.ModelForm): class Meta: model = models.Article exclude = [ 'author', ] def __init__(self, user, *args, **kwargs) -> None: self.user = user return super(PublishForm, self).__init__(*args, **kwargs) def is_valid(self): print('IS_VALID METHOD CALLED') return super(PublishForm, self).is_valid() def clean(self): print('CLEAN METHOD CALLED') cleaned = super(PublishForm, self).clean() cleaned['author'] = self.user return cleaned and views.py: class PublishView(generic.CreateView): form_class = forms.PublishForm success_url = '/' template_name = 'ex00/publish.html' def form_valid(self, form): print(form.cleaned_data) return super(PublishView, self).form_valid(form) def form_invalid(self, form): print(form.errors) return super(PublishView, self).form_invalid(form) It seems form_valid() does not call neither form.is_valid() or form.clean(). But It was able to get form.cleaned_data(). How does form_valid() work? What should I do to manipulate cleaned_data … -
Django: traceback appears on form as text after Bad Request 400
I have ajax views for editing and saving objects. When I am editing an object, the appropriate forms and formsets are loaded with instantiated data. Now I am getting this error when a user tries to add more than 1000 fields: POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. The problem is that the traceback code is inserted directly on the form and becomes visible to all: By design, I am expecting a response code on frontend, which is 400 for django form errors. However, in this case, the 400 error comes from the bad request, and not from form errors. As a result, after saving the object, I have the full traceback displayed right in the form as plain text. How can I avoid this behaviour? I want not to display the traceback/bad request error text on the form to the users. My only idea is to change the default status code of django form errors to some 444 and to display only the 444 errors on forms, while ignoring the 400 errors traceback. But I don't know how to do it and don't think this is the best option either. -
The default django `User` model generating huge number of queries, when working with views in DRF?
I am trying to build an endpoint for the default User model, which we have in django, which being imported from from django.contrib.auth.models import User, This is my serializer:- class SuperUserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'username', 'groups', 'user_permissions', 'organization_users', ) and the views goes as this:- class UserDetailView(RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = SuperUserDetailSerializer with the above codes, the number of queries which being hit are 216-219, which is due to the field user_permissions, I checked the User model, but it doesn't contains any field as user_permissions, but in the response, I get this field, and also in the html form field the permissions are populated(DRF Browsable page). I am trying to implement prefetch_related or select_related for the user_permissions field, but I am not able to reduce the the number of query, (It is hitting the database each time for getting all the permissions). This is what I am trying to do but not able to achieve it:- queryset = User.objects.prefetch_related(Prefetch('user_permissions', queryset = Permission.obects.select_related('content_type')))...I am not sure where I am doing the mistake. -
Django Rest Best practice of handling complex data composition
I am a bit of a django newbiew so forgive me if I miss somehow something obvious. I have a database table representing a linguistinc term called terms. This term can be included in several string attributes of not directly related tables such as say article. Now I have a direct requirment to return those items when aksed for the details of a term. An example schema could look like the following { 'name': 'Some term definiton', 'another_attribute': 'some attribute value', 'articles': ['Articles that include text'] } Not the most efficient way but in order to find the 'associated' articles I have method called find_associated_articles which in essense performs a full text search on the articles text to find potential matches of particular term. No the question is what would be the most Django way of compositing this information in a Rest Response (Idealy in the context of a retrieve action within a viewset)? -
How to upload and process large excel files using Celery in Django?
I am trying to upload and process excel file using Django and DRF with Celery. There is an issue when I am trying to pass the file to my Celery task to be processed in the background, I get a following error: kombu.exceptions.EncodeError: Object of type InMemoryUploadedFile is not JSON serializable Here is my view post request handler: class FileUploadView(generics.CreateAPIView): """ POST: upload file to save data in the database """ parser_classes = [MultiPartParser] serializer_class = FileSerializerXLSX def post(self, request, format=None): """ Allows to upload file and lets it be handled by pandas """ serialized = FileSerializerXLSX(data=request.data) if serialized.is_valid(): file_obj = request.data['file'] # file_bytes = file_obj.read() print(file_obj) import_excel_task.delay(file_obj) print("its working") return Response(status=204) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) And my celery task: def import_excel_helper(file_obj): df = extract_excel_to_dataframe(file_obj) transform_df_to_clientmodel(df) transform_df_to_productmodel(df) transform_df_to_salesmodel(df) @shared_task(name="import_excel_task") def import_excel_task(file_obj): """Save excel file in the background""" logger.info("Importing excel file") import_excel_helper(file_obj) Any idea what is the way to handle importing Excel files into celery task so that it can be processed by other functions in the background? -
Mapbox add marker on click
I am building a website in django, and im using Mapbox as a way to add markers on a map. Right now my solution is a django form, with fields for 'longitude', 'latitude', 'Marker_Title'. A solution would be to either add the longitude and latitude to the form by clicking on the map, or clicking on the map and then a popup appears where you can write the marker title. I am not sure how i get the longitude and latitude information by clicking right now. Here is a picture of how it looks right now: Picture of the map and form I would love if anyone can help me with this! Thanks in advance! -
Compare data from a week(or minute) ago using a queryset in Django
I have some data as follows: class myModel(models.Model): date = models.DateTimeField user_ID = models.CharField index_a = models.CharField cnt_a = models.BigIntegerField cnt_b = models.BigIntegerField I would like to get Result data as follows: date user_ID sum(n.a) sum(-5min) sum(n.b) sum(-5min) 2021-08-01 13:00 a10 7011 6625 9239 8766 2021-08-01 13:00 a20 6968 6628 9238 8765 2021-08-01 13:00 a30 6940 6646 9238 8766 2021-08-01 13:00 a40 6974 6644 9238 8764 2021-08-01 12:55 a10 6625 6621 8766 8692 2021-08-01 12:55 a20 6628 6580 8765 8691 2021-08-01 12:55 a30 6646 6596 8766 8693 2021-08-01 12:55 a40 6644 6614 8764 8692 I tried SQL query as follows: and get the Result as above Table I am trying to use queryset in Django to perform the following query without using raw SQL. any idea how can do that? Thanks in advance! SELECT n.date, n.user_ID, sum(n.cnt_a), sum(p.C_AAA), sum(n.cnt_a), sum(p.C_BBB) FROM myModel AS n LEFT JOIN ( SELECT t1.date, t1.user_ID, t1.index_a, t1.cnt_a as C_AAA , t1.cnt_b as C_BBB FROM myModel AS t1 ) AS p ON p.date = DATE_SUB(n.date, INTERVAL 5 MINUTE) AND p.user_ID = n.user_ID AND p.index_a = n.index_b -
nginx websocket not working with django channels (url not found)
I want to implement a realtime chat app using django channels and redis. Everything works in development, but in production i can't get websockets to be configured correctly. I have gunicorn running as a server for handeling http requests and now i am trying to set up daphne for handeling websockets. Nginx proxies all http requests correctly to gunicorn and therefor all urls using only http work fine. However, when i try to connect to the websocket in my frontend, daphne says that the url was not found. The same happens, when i use uvicorn as an asgi server instead of daphne. Also, when i let daphne handle http and websocket requests, daphne has no problem with http but cannot find the websocket urls. My setup is as follows: settings.py WSGI_APPLICATION = 'config.wsgi.application' ASGI_APPLICATION = 'config.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('127.0.0.1', 62148)], }, } } asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') django_asgi_app = get_asgi_application() import chat.routing application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) routing.py from django.conf.urls import url from .consumers import ChatConsumer websocket_urlpatterns = [ url(r"^ws/chat/$", ChatConsumer.as_asgi()), … -
How can I pass two queryset in same function using Django Rest Framework
def getProducts(request): products = Product.objects.all() p = Product.objects.all().filter(category = 1) serializer = ProductSerializer((products,p), many=True) return Response(serializer.data)** I want to pass p and products value in the serializer object. Can I do this here? -
ImportError: cannot import name 'Translatable' from 'translations.models'
When I wrote this:python manage.py makemigrations I get this error:ImportError: cannot import name 'Translatable' from 'translations.models' How can i solve this problem? enter image description here -
Prevent django send_mail timimg attack
I have different REST-API views where I either send a mail (if an account exists) or do not send a mail. For example, the user can input the email in the forgot-password form and a mail is sent if the account exists. I am using from django.core.mail import send_mail to send the mail. The problem is, that this takes some time, and so requests for valid emails are generally longer than requests for non-exiting emails. This allows an attacker to compare the request times to find out if an account exists or not. Is there any way that I can call send_mail() without sending the mail? Or what would be the fix to make request times equally long for both cases? Note: I could check how long send_mail() needs on average and wait this time if I do not send the mail. As the app runs on different servers with different configs, this can not be generally done in my case. I would rather not store the average execution time per server in a database to solve this. -
can't show error message into error function in ajax - django
i'm trying to show error message from server to client site using ajax , but it wont work when i make a function for error messages , #other codes for saving the post,there is not error success_meesage = f'success' return JsonResponse({'success':'success','success_msg':success_meesage}) else: error_message=f'there is an error into your two dates please make sure check in smaller than check out' return JsonResponse({'success':False,'error_taken':True,'error_message':error_message}) my ajax code const form = document.getElementById('post-form') form.addEventListener("submit",submitHanler); function submitHanler(e){ e.preventDefault(); $.ajax({ type:'POST', url:"my-url", data:$("#post-form").serialize(), dataType:'json', success:successFunction, error:errorFunction, }) } function successFunction(data){ // console.log(data) if(data.success='success' && data.success_msg){ form.reset(); alertify.success(data.success_msg) } } function errorFunction(request, status, error){ console.log(request.responseText) if(error.error_taken == true){ alertify.alert('warning !','message') alertify.alert(error.error_message,function(){ }); } } } i also tried this : function errorFunction(jqXHR, exception) it shows nothing as well , i tried many ways but none of them worked ! thank you in advance .. -
How to add in instance field which not in model but created in Django form?Django
I have a model Book: class Book(core.BaseModel): name = models.ForeignKey( FishingGear, verbose_name="Name", on_delete=models.PROTECT, related_name='name', ) library = models.ForeignKey( Library, models.PROTECT, related_name='library_places', verbose_name='Library', ) tag_number = models.PositiveIntegerField('Tag Number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) In forms.py I created new field : class BookChangeStatusForm(core.ModelForm): start_tag_number = forms.IntegerField(label='Start number', min_value=1) In the same forms.py I have method which takes old data and create new book!But I want that without tag_number it will create field 'start_tag_number': def save(self, commit=True): # instance = super().save(commit=False) instance = Book.objects.create( name=self.instance.name, library=self.instance.library, tag_number=self.instance.**start_tag_number**, ) return instance class Meta: model = Book fields = () But I got Error: Book object has no attribute 'start_tag_number' My views.py class BookTagView(core.UpdateView): form_class = BookChangeStatusForm template_name = 'book/book_tag.html' success_url = reverse_lazy('book:book-list') I want to take in forms.py OLD instance in UpdateView and create new instance with old data but without 'tag_number' insert 'start_tag_number'!Please help me to undestand where is mistake! -
Django change hasher algorithm for user password
I need to transfer SHA512 passwords from another db to Dango. example password - b792e3c67205a800d16fceb2dacf5b70fada6f31e905352750e093bedc95ab970c0121f7c3f2a3bfcab32f3cb8a2c0d2273ada96b082dd0fbd012dbae379dcb1 and i need use auth with this password I try this. but it doesn't work hasher.py import hashlib from django.contrib.auth.hashers import BasePasswordHasher, mask_hash from django.utils.crypto import constant_time_compare from django.utils.translation import gettext_noop as _ class CustomPasswordHasher(BasePasswordHasher): algorithm = 'sha512' def salt(self): return '' def encode(self, password, salt): hash = hashlib.sha512(password.encode()) return hash def verify(self, password, encoded): encoded_2 = self.encode(password, '') return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): return { _('algorithm'): self.algorithm, _('hash'): mask_hash(encoded, show=3), } settings.py PASSWORD_HASHERS = [ 'restorating.hasher.CustomPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', ]