Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Q, Max in Django Queryset Models?
I would like to know how it is used and the concept of Django Models aggregation -
Django-Celery Stopped Working After Switching Branches
I used cookiecutter-django to create my Django project with celery=yes and docker=yes. I spent some time modifying the Celery config/structure to match the HackSoftware Django Guidelines for Celery. It took me a while to get everything figured out but I did eventually get it all working with a sample task which just logs a few lines. This was done on a feature branch. So once I confirmed that everything was good, I committed and pushed my changed and merged the PR with my Main branch. Back in my terminal, I switched to Main and pulled the changes. At this point, there should be no diff between my main branch and my configure_celery branch. However, when I brought up all of the containers, my sample task was no longer executing. I've spent many hours now trying various things to get it working to no avail. I've brought the containers down, pruned everything with docker system prune -a, used Docker Desktop to manually clear out all of the volumes, tried a different Redis db config, switched back to my configure_celery branch and nothing has worked. I can see that the worker is successfully discovering my task: brew_dash_local_celeryworker | [2022-02-03 21:35:27,194: INFO/Process-1] Connected … -
How to limit serializing in Django Rest Framework?
I have 2 serializers that add and subtract (they are the same, with the difference being add +=1 and subtract -=1) points to an answer. I want to limit them so that a user can only use add point to an answer once. Do you have any idea how to get to it in Django Rest Framework? class Answer(models.Model): number_of_points = models.IntegerField(default=0) class SubtractPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points -= 1 instance.save() return instance -
Uncaught ReferenceError: $ is not defined in console
I am trying to append a div when a checkbox is selected in dajngo template but i keep receiving Uncaught ReferenceError: $ is not defined in the console the template: {% extends 'base_layout.html'%} {%load static%} {% block content %} <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in categories%} <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'></div> </div> <script> $('.category-checkbox input[type="checkbox"]').click(function (){ if ($(this).is(':checked')) { // Add the element to the div with an id identifier $('.items').append('<div id="[{{category.id}}]">123</div>'); } else { // Remove the element from the div targeted by the id identifier $('.items #[{{category.id}}]').remove(); } }); </script> {% endblock %} -
Improve Django intermediary tables
I'm working on a Django app that contains the following structure: There are Checklists consisting of one or more ChecklistItems. We want to assign however many checklists as we want to a Job, and fill these Job-Checklist's questions. An example would be to create a Checklist containing ChecklistItems: "How are you?" "What is your name?" So, each ChecklistItem is just a question in a checklist. This means now we can use this Checklist that consists of 2 ChecklistItems in any job and fill it out after assigning it. We create Job #1, and assign it this Checklist #1, create Job #2 and assign it Checklist #1 also. Same checklist to be answered in two different jobs. Whoever's working on that particular job will then fill the checklist out according to them. The way we first approached this was with Job and Checklist being connected by a JobChecklist intermediary table, and JobChecklistItemAnswers being assigned to each answered checklist item (question). class Checklist(models.Model): """A class to represent a checklist.""" name = models.CharField(_("name"), max_length=150) class ChecklistItem(models.Model): """A class to represent an item of a checklist.""" checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE) question = models.CharField(_("question"), max_length=200) class Job(models.Model): """A class to represent a job.""" checklists = … -
Django_React_SQL website product searching
I am working on a project the backend is in python Django and frontend in react-js and database is MySQL. Now the problem is I need to search products from database in my project but don’t know how to get query for frontend to backend. I don’t know the code Moreover I am using rest-framework and Axios library to connect. I am very thankful to you if you help me to create search related queries in my project. Thank you -
How to use Django backands with Kivy
I would like to connect my website in Django with my mobile application in kivy but I don't know how? I know the different approaches I should use to solve the problems. I tried the APIs but I didn't succeed so help me! -
Django usage of forms everywhere
I think I have a wrong understanding of Django Forms / handling databases, especially because I'm completely new For this, let's just take YouTube comments as an example. If I write a comment on a YouTube video and press submit, the comment is published directly, everyone can see it, the page does not need to be updated by me. YouTube then stores the comment in the database. How would you implement something like this from theory in Django? According to current knowledge, I have to use the comment function put it in HTML form > submit button > refresh page Or we take another example, a website popup where the email address can be entered which will be saved. According to my current knowledge, I would have to create Form -> Submit Button -> Refresh Page which would make the user go back to the beginning of the website, which is annoying. When I read through stuff and watch tutorials it's all kind of muddled into forms. -
How to display multidimensional API response in Django?
I am new in Django and I am trying to learn this framework. I am trying to display the individual data from an API response. From my views.py, I am passing order in a context. order = response.json()['order'] return render(request, 'orders.html', {'order': order}) I need to display fulfillment_date and fulfillment_status These are the tags I have tried on my frontend. {{ order.order_date }} is working {{ order.fulfillments }} is also working But these are not working. {{ order.fulfillments.fulfillment_date }} {{ order.fulfillments[0].fulfillment_date }} {{ order.fulfillments[0][0] }} {{ order.fulfillments.['fulfillment_date'] }} Thanks! API response: "order": { "order_date": "2022-01-09T00:00:00", "order_name": null, "checkout_token": null, "payment_method": null, "total_price": null, "subtotal_price": null, "currency": null, "landing_site_url": null, "source": "orders_api_v3", "payment_status": null, "cancellation": null, "customer": { "external_id": "111222", "first_name": "First Name", "last_name": "Last Name", "email": "newnew@newnew.com", "phone_number": null, "accepts_email_marketing": null, "accepts_sms_marketing": null, "custom_properties": null }, "billing_address": null, "shipping_address": null, "custom_properties": null, "fulfillments": [ { "fulfillment_date": "2022-01-09T00:00:00", "status": "success", "shipment_info": { "shipment_status": null, "tracking_company": null, "tracking_url": null, "tracking_number": null }, "fulfilled_items": [ { "external_product_id": "223553388", "quantity": 1 } ], "external_id": "112121212" } ], "line_items": [ { "id": 5554786884, "created_at": "2022-01-10T03:59:28", "updated_at": "2022-01-10T03:59:28", "quantity": 1, "total_price": null, "subtotal_price": null, "coupon_code": null, "custom_properties": null, "product_id": 303170668, "external_product_id": "223553388" } ], "id": 2824686328, … -
Django: Hierarchy model query
Imagine there is a model: class OrgUnit(models.Model): parent = models.ForeignKey( 'self', on_delete=models.CASCADE, verbose_name=_('parent'), related_name='children', blank=True, null=True, ) name = models.CharField(_('name'), max_length=255) type = models.CharField(_('type'), max_length=55, null=True, blank=True, db_index=True) And hierarchy sample: It is easy find all stores if one knows cluster id (cluster_id=1): stores = OrgUnit.objects.filter( type='store', parent__parent_id=cluster_id ) It is also easy find cluster by sales department id (sales_department_id=5): cluster = OrgUnit.objects.select_related('parent__parent').get(pk=sales_department_id).parent.parent And finally find stores for sales department: cluster_id = OrgUnit.objects.select_related('parent').get(pk=sales_department_id).parent.parent_id stores = OrgUnit.objects.filter(type='store', parent__parent_id=cluster_id) Getting stores by sales department id will make 2 queries to database. I wonder to know whether it possible to fetch stores by sales department id in one query? If yes how? -
Is there a Windows alternative to a certain Unix command?
I'm working with a database (MySQL) and use Django, I can't seem to find an alternative to this command: python manage.py inspectdb > models.py is there a windows alternative to this? Thank you -
Django is receiving image into a React Native FormData instance as an dict
I have a React Native app, there is a screen to upload a logo (an image). When the logo gets uploaded, Django should receive the image, save into an user row and create the file into local assets folder (as usual). The problem is, i don't even know if i am sending the data from React Native in a correct way, but Django REST API is receiving the image as an Python dict. I'm following the instructions from many other people, but still not working, here's how i load the logo into a React Native FormData instance: const fd = new FormData(); fd.append('logo', { name: logo.fileName, uri: logo.uri, type: logo.type, }); The logo variable is an Asset instance, from react-native-image-picker library. And here, how Django receive the data, with pdb (Python debugger): For a better look: {'_parts': [ ['logo', { 'name': 'logo.png', 'uri': 'file:///data/user/0/com.micandidato/cache/rn_image_picker_lib_temp_9b3907e0-3f13-4ad5-9ca9-13f491473440.png', 'type': 'image/png' }] ]} I'm pretty sure Django is not going to save this object as an image. The request method from React Native is PATCH (if relevant). Thanks. -
Trying to link my HTML form to a view function in Django
I've been trying to create a user registration page and have gotten the form itself and the render for the form set up. I have also gotten the form to save user input as POST, but haven't been able to send that info to a view function I have created to save that info to a database. Here is my html/css template form:(userinfo.html) <div> {% block content %} <form action="register" method="post" name="Userinfo" id="Userinfo"> <label for="fname">First Name</label> {% csrf_token %} <input type="text" id="fname" name="firstname" placeholder="Your first name.."> <label for="lname">Last Name</label> <input type="text" id="lname" name="lastname" placeholder="Your last name.."> <label for="DOB">Date Of Birth</label> <input type="text" id="DOB" name="DOB" placeholder="The Date you were born"> <label for="Email">Email Address</label> <input type="text" id="Email" name="Email" placeholder="Your email address"> <input type="submit" value="Submit"> </form> {% endblock %} </div> The name of my view function is register and here it is:(views.py) def register(request): if request.method == 'POST': first_name = request.POST['first_name'], last_name = request.POST['last_name'], date_of_birth = request.POST['DOB'], email = request.POST['email'] newuser= User.objects.create_user(first_name=first_name,last_name=last_name, email=email) newuser.save() print('user created') return redirect('/home') else: return render(request,'register.html') This is supposed to save the user input into django's user database table. How would I go about linking the form to the view I have set up? -
Django how to search for one Model based on multiple foreign keys?
I'm essentially trying to build a filter based on the model's name and multiple foreign keys. class Foo(models.Model): name = models.Charfield() class Bar(models.Model): name = models.ForeignKey(Foo) Foo can have the same names, but different Bars. I want to search for the specific Foo based on Bars. So far I am able to parse user input and create a list ["foo.name", "bar.name", "bar.name"] How do I filter the product based on that specific Foo? and with trailing Bars? # pseudocode process foo = foo.objects.filter(name__contains=list[0] and foo.objects.filter(bar_name__in=[list] -
Internal server error in production with https in Django when change path
I have changed the path for admin.site.urls to /admindjango, in local it works fine, but in production(https and domain) it gives error 500, I already enabled allowedhost '*' and debug=False. urlpatterns = [ path('admindjango/', admin.site.urls), path('', include(('administracion.urls', 'administracion'), namespace='administracion')), ] -
How to keep the original filename in React when fetched from Django?
I'm working with a Django-Graphene-React stack and in my frontend, the user must be able to download a file from the backend. It works perfectly. However, the filename is defined in the backend and sent through the Content-Disposition header in the HttpRequest sent from Django. But I cannot retrieve it when I fetch it in the frontend. Here is my backend Django view that generates the file: import io from django.http import HttpResponse def download_file_view(request): buffer = io.BytesIO() # Generate an Excel file and put it a buffer... ... buffer.seek(0) response = HttpResponse( buffer.read(), content_type="application/vnd.openxmlformats-officedocument" ".spreadsheetml.sheet", ) # The filename is generated in the backend (Django) and cannot be # generated from the frontend (React) response["Content-Disposition"] = "filename.xlsx" return response If I download it directly by entering the url assign to this view in my browser, I get the filename correctly when my browser prompt me to save the file. However, I want to fetch the file in the frontend in order to get a loading state during the time the file is being generated in the backend. Here is my frontend component in React: import {useState) from "react"; const DownloadButton = ({downloadUrl}) => { const [isLoading, setIsLoading] = useState(false); … -
Check if user has sent a request before Django Rest Framework
I've got these serializers for adding and subtracting points in an answer on a forum. class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points += 1 instance.save() return instance class SubtractPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points -= 1 instance.save() return instance Viewset looks like this (the same is for adding): class SubtractPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = SubtractPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) Now, every user can only upvote once and downvote once. So someone might accidentally downvote and then upvote once again a particular answer. The urls are questions/int:pk/addpoint. questions/int:pk/subtractpoint So i'd like to make a limit on the Serializer that user_limit = 0 if request.user has already clicked upvote the user_limit = 1 and if user_limit = 1 return response that its already upvoted. But i have no idea how to implement this logic in a serializer since im very new to Django Rest Framework. Or maybe you have a better idea how to limit amount of upvotes per user? -
How to display mongodb data in html table using django
i want to display mongodb data into the html table but the problem is mycode first print all the time field and then print the all the status and then all the level instead of of printing one at a time my view.py code is as follows def generate(request): a=str(request.POST.get('level')) b= request.POST.get('status') c=(request.POST.get('startdate')) g=datetime.strptime(c,"%Y-%d-%m") d=datetime.strftime(g,"%Y/%d/%m") e=request.POST.get('enddate') h=datetime.strptime(e,"%Y-%d-%m") f=datetime.strftime(h,"%Y/%d/%m") output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\intern mongo\\indicator\\work\\water.py',a,b,d,f],stdout=PIPE,text=True) client=pymongo.MongoClient("mongodb://localhost:27017") db = client["water"] colle= db["waterlevel"] data_from_db = colle.find({}) return render(request,'result.html',{'task':data_from_db}) my result.html page template which display the table is as follows <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>time</th> <th>status</th> <th>level</th> </tr> </thead> <tbody> {% for ta in task %} <tr> <td>{{ ta.time }}</td> <td>{{ ta.status }}</td> <td>{{ ta.level }}</td> </tr> {% endfor %} </tbody> </table> </div> i want to create a table which display one datetime unit then on status and level value then move to next row please suggest the possible ways it would be very helpful -
Syncing Production values with Local
When I run my site on localhost it works using a Sql database now when I try to run it on production. It produces the following it seems to not have created the field receiverDeleted. ProgrammingError at / column pages_messages.receiverDeleted does not exist LINE 1: ...r_id" = 1 AND NOT "pages_messages"."read" AND NOT "pages_mes... ^ Request Method: GET Request URL: https://arundeepchohan.herokuapp.com/ Django Version: 3.2.9 Exception Type: ProgrammingError Exception Value: column pages_messages.receiverDeleted does not exist LINE 1: ...r_id" = 1 AND NOT "pages_messages"."read" AND NOT "pages_mes... ^ Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py, line 84, in _execute Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Thu, 03 Feb 2022 12:16:13 -0800 -
Django PostgreSQL ArrayField does not work
I have just switched to PostegreSQL. Now whenever I add the following code to my Custom User Model, the database is broken, no new values are added to the database, for example during registration from django.contrib.postgres.fields import ArrayField class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email'), unique=True) username = models.CharField(max_length=150, unique=True) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(default=timezone.now) code = models.ImageField(blank=True, upload_to='code',) #part that breaks the databse: ip_addresses = ArrayField( models.CharField(blank=True), default=list) From the moment also no more migrations are recognized. Or I get something like this django.db.utils.ProgrammingError: column "ip_addresses" does not exist LINE 1: ...ER COLUMN "ip_addresses" TYPE varchar(15)[] USING "ip_addres... What error I get is 50 50 chance but atleast the first error is always here. I also tried this which did not work either ip_addresses = ArrayField( models.CharField(max_length=15), default=list) -
What am I doing wrong with action url in my form
I am trying to do search method in my_app. Code in my navbar.html is as below. It is not full code. The other buttons in the navbar work fine. These are not forms - just regular links. <form class="d-flex" action="{% url 'search_record' %}" method="POST"> {% csrf_token %} <input class="form-control me-2" type="text" placeholder="Search"> <button class="btn btn-primary" type="button">Search</button> </form> In my urls.py I have name "search_record" urlpatterns = [ path('show/', show_record, name="show_record"), path('new/', new_record, name="new_record"), path('edit/<int:id>/', edit_record, name="edit_record"), path('del/<int:id>/', delete_record, name="delete_record"), path('search_record/', search_record, name="search_record")] I have the appropriate entries in the file views.py def search_record(request): return render(request, 'my_app/search_record.html', {}) And I also have a template file search_record.html in the directory templates/my_app whose content is as follows: {% extends 'my_app/index.html' %} {% block title %} Search Results {% endblock %} {% block page %} <h1>Results ...</h1> {% endblock %} When I am using the url: http://127.0.0.1:8000/my_app/search_record/ in the browser then search_record.html works good it shows me "Results ...", but clicking the Search button in the navbar does't work. After clicking this button, nothing happens. What am I doing wrong ? I have django 4 in my app. -
How do I parse a string in Django templates?
I am trying to have my django app display some text on the page. My string, coming in from the view, would be something along the lines of: 'Hello! This is my twitter @profile! send me an email at me@mail.com Now I want to be able to display the string as: 'Hello! This is my twitter @profile! send me an email at me@mail.com BUT @profile (without the '!') must be a link to https://twitter.com/profile If I make my logic in views and send as a string: Hello! This is my <a href="https://twitter.com/profile" target="_blank"> send me an eamil at me@mail.com The result will be to actually to see the tags, which I obviously don't. How do I fix this? considering that the strings coming in will be many and I display them via a python-enabled loop. Thanks! -
how to set Referer-Policy for static javascript files in Django
I have a static Javascript file in a django project that sends a request to another domain to render an iFrame which has my site listed in frame ancestors. At the moment I don't think the referer header is being set as Referer-Policy is set to 'same-origin'. I've tried setting this with SecurityMiddleware in Middleware: SECURE_REFERER_POLICY = 'strict-origin-when-cross-origin' How can I set this policy? Which is still no good, Referer-Policy header stays as 'same-origin' The file in question is connect-streams.js from here, which is used for embedding Amazon Conncet CCP within a website. https://github.com/amazon-connect/amazon-connect-streams/blob/master/Documentation.md All other settings within Connect and in the HTML are OK as it works in an S3 bucket. The Django app is deployed in a docker compose on EC2 with nginx and gunicorn, with correct SSL certificates. -
Django - Need helping writing annotated query
I'm trying to better understand how to write some more advanced queries. I'm used to the basic Model.objects.all() and .filter(), etc, but I'm having trouble writing out queries that are annotated. Here is my model setup (I have removed any additional fields that are not necessary for this question): from django.db import models class Client(models.Model): name = models.CharField(max_length=100) class Project(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) class Campaign(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="campaigns") class Advertisement(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='advertisements') What I need is a query that shows how many Advertisements each client has, ordered by most to least. I'm trying to follow the docs from here: https://docs.djangoproject.com/en/4.0/topics/db/aggregation/ but their annotation example isn't as nested, the publisher model example is a foreign key on the book object, where as with mine the client is a foreign key of a project, which is a foreign key of a campaign, which is a foreign key of advertisements. Any advice on how to drill down through the layers of the models to get the info I need? -
django: submit form and redirect to the new page
I need to render and redirect to the new page called CreateOrder.html at path: "homepage/order/", after user click the form submit button (i.e."Order Now button) in the home page. what is the correct way to update(render) the CreateOrder.html and redirect to this page) #views.py def CreateOrder(request): navi_load = request.session['navi_load'] navi_unload = request.session['navi_unload'] dist = request.session['dist'] charge = request.session['charge'] return render(request, 'OnlinePricing/CreateOrder.html', {'pickup_address': navi_load, 'delivery_address': navi_unload, 'distance': dist, 'charge': charge}) #urls.py urlpatterns = [ path('', views.OnlinePricing, name='OnlinePricing'), path('order/', views.CreateOrder, name='CreateOrder'), ] #home page HTML <form> ... <button type="submit">Get Price</button> <button type="submit" style="margin-left:10px;">Order Now</button> </form> #CreateOrder.html <html> <div> <label>pickup_address:</label> <span id="pickup_address"> {{ pickup_address }} </span> </div> <div> <label>delivery_address:</label> <span id="delivery_address"> {{ delivery_address }} </span> </div> <div> <label>dist:</label> <span id="distance"> {{ distance }} </span> </div> <div> <label>charge:</label> <span id="charge" style="color: #ff0000;font-size:25px"><b>{{ charge }}</b></span> </div> </html>