Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
ImportError: No module named pathlib Windows OS and Python version 3.8
Hi im trying to run a venv for my project. Everythin goes well install requirments and creating a my venv. The problem is that when i try to make a manage.py migrate i get this error. Ive looked everywhere and i got python version 3.8 installed. Pathlib is part of the package from python 3.4. I use Windows and python 3.8 with Django version 3.0.12- My project is based on a cockiecutter and i dont want to update to the latest version om django. Does anone know what the problem is and how it can be solved? manage.py migrate Traceback (most recent call last): File "E:\Dev\Fooders\fooders\manage.py", line 4, in <module> from pathlib import Path ImportError: No module named pathlib -
Django rest framework: how to override `is_valid` on a serializer created with `many=True`?
I have tried to override the create method on my viewset class in order to be able to create multiple instances of my model at once. The create method now has the following lines: def create(self, request, *args, **kwargs): ... print('Debug 0') serializer = self.get_serializer( data=request.data, many=True ) print('Debug 1') serializer.is_valid(raise_exception=True) print('Debug 2') self.perform_create(serializer) print('Debug 3') return Response(serializer.data) If I now try to override the is_valid method within the serializer class, I get surprising behavior. Suppose I now try to override the is_valid method within the serializer class with a simple wrapper: def is_valid(self, raise_exception=False): print('is_valid was called') return super(AlbumSerializer, self).is_valid(raise_exception) If there are no validation errors then I would expect the message "is_valid was called" to appear after after "Debug 1". To my surprise though, it appears after "Debug 3" suggesting that my override method did not get invoked till after the items were created! If there is a validation error, then the "is_valid was called" message appears after "Debug 1" as I would expect. So I am really surprised/confused what is going on here, and would like to know please if there is a special way that you need to go about overriding is_valid if the serializer involves … -
Lunching python script from Django View
I wrote an essential python script (data import) which executes a series of commands and, once it is executed, write in the console a message. I would like to implement this script in Django in order to run the script directly in a "frame console" without needing to prepare several JS/AJAX functions to write in the page the operation has been executed. Is this possible in a "simple" way without using sockets or any other tricky method? Thank you -
deployed my website on heroku successfully but when i tried to run it i am getting internal server error
procedure i followed while deploying my website on heroku are . created a Procfile Contents of Procfile are web: gunicorn website.wsgi:application --log-file - then I have done some changes to my settings.py file and here is the settings.Py file """ Django settings for website project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j3t578bbmo+!bmmp27k3+d*nowwo%8y5k7-545j48_$)z0i#67' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1','getmachine.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django_countries', 'core', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'libraries':{ 'cart_template_tags': 'core.templatestags.cart_template_tags', } }, }, ] WSGI_APPLICATION = 'website.wsgi.application' # Database … -
Django re_path picking up negative lookahead as capturing group and a argument for the view
I'm using a urlpattern like so urlpatterns += [ re_path(r'^(?!(?:api/|backend/))', include('an_app.urls')), ] It is so that it doesn't route paths starting with api/ or backend/. I have a specific requirement that needs this pattern, and I can't solely rely on ordering the paths to achieve this (this path captures URLs on / and sends them to a view that renders a SPA). Unfortunately, the Django URL resolver is picking up the negative lookahead (^(?!...) as a capturing group, and inserts a path variable into the view. If I run python manage.py show_urls (from django-extensions): /<var>app/ an_app.views.SomeView an_app:home The "group" behind the ^app/ in the regex is not a capturing group, and the paranthesis is there to denote a negative capturing group (i.e. the path doesn't start with backend/ or api/). But it seems like Django is picking it up as a capturing group and inserts a variable into the URL. Do you know how to configure this so it doesn't get picked up?