Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Send data to oauth client using django-oauth-toolkit
I want to update my OAuth-client database whenever there is any update in the OAuth-server database instead of making a call to get data and update the database. I tried to find a way to do that through django-oauth-toolkit, but couldn't find any. Is there a way to achieve that through django-oauth-toolkit or should I use webhooks to achieve that? -
Not able to install django and use an existing django project
I am studying Django for the first time and everything was going well until the last day. Today when I tried opening my Django project, the terminal returns an error saying :- Unable to create process using 'C:\Users\User1\AppData\Local\Programs\Python\Python310\python.exe manage.py runserver' Thinking that it might be an issue with the virtual env, I tried checking my Python Interpreter to make sure I am currently in my venv. Fortunately, I am currently using my venv but Pycharm indicates me to Install Python Packaging Tools. I tried the link to install it but it notifies a "Non Zero Exit Code(101)" and Invalid Python SDK error. Googling for the error asked me to check the path in Environment Variables where two are present - C:\Users\User1\AppData\Local\Programs\Python\Python310\ C:\Users\User1\AppData\Local\Programs\Python\Python310\Scripts\ Recently I had added MingW Compiler to the path and that was it. I've never touched the path of Python. I would like to mention that there are no errors in creating a new virtual envirnoment nor activating it. But things get worse when I try to pip install django. CMD tells that unable to create process. Please help! I am actually stuck with my project. -
Fill a ChoiceField in Django template with external data
I'm new to Django and I'm having a hard time understanding forms when the data to choose from are not taken from the database nor user input that they're generated on the go. I currently have a template with a single ChoiceField. The data inside this field aren't fixed and they're calculated on the go once the page is requested. To calculate it I need the username of the User who is logged in. Basically, the calculation returns a list of lists in the form of ((title, id),(title,id),(title,id)), etc. that I need to put into the ChoiceField to make the User choose from one of the options. Now, I'm not understanding how to pass the calculated list of lists to the form. I've tried to add the calculations inside the form as below but it is clearly the wrong way. The main issue is that, to calculate my list of lists, I need the request value, and I don't know how to access it from the form. Another idea was to add the generate_selection function inside the init but then I don't know how to pass main_playlist to being able to add it to ChoiceField Below my not working forms.py … -
Returning HTML View vs. JSON Object with HTML using Flask & AJAX
I'm developing a single page Flask app using AJAX to navigate through my routes. For example, when a user clicks on a nav-link, a GET request is made with AJAX that calls a route like "/profile", which returns a JSON including the HTML to be replaced on the screen. If I type an existing route in the browser without calling an AJAX request, the HTML will be returned as expected as a JSON and simply pasted as text on the screen. I would like to give users the ability to type routes in the address bar and have the page load instead of just pasting the JSON with the HTML. What is the proper way to instead return a view instead of simply the JSON from my Flask end-point if no AJAX request was made (someone just types in "/profile" in the browser without clicking the profile nav-link)? My first thought is to pass some type of parameter as part of every AJAX request and have the backend check if the parameter exists upon being called, where I would return a view instead of the JSON. That seems very inefficient and would make the code more complex by adding many … -
Django annotate double nested key in JSONField
My JSONField contains data like this: class Car(models.Model): data = JSONField() Car.objects.first().data { u'colors': [ {u'color_id': u'1', u'source': u'Manufacturer 3'}, {u'color_id': u'2', u'source': u'Manufacturer 2'}, {u'color_id': u'3', u'source': u'Manufacturer 1'}, ] } I know that I can filter results with: Car.objects.filter(data__colors__contains=[{'color_id':'3'}]) Is there any way I can annotate queryset so that 'color_id' are contained in a list? Something like: Car.objects.all().annotate(color_ids=...) That would enable me to do: Car.objects.first().color_ids ['3', '2', '1'] Or something along those lines, just to filter with color_id value. Using Django 1.11 and Postgres 13. -
How to start cron service on Dockerfile
I have installed django-crontab==0.7.1 and added to INSTALLED_APPS Django configuration. I'm trying to start cron service on the Docker image build and add the command cron task with python manage.py crontab add but nothing occurs. Dockerfile: FROM python:3.8-slim-buster LABEL maintainer="info@albertosanmartinmartinez.es" version="1.0.0" ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update -y && apt-get install -y build-essential postgresql python-scipy python-numpy python-pandas libgdal-dev && apt-get clean && rm -rf /var/lib/apt/lists/* RUN mkdir /industrialareas COPY ./project /industrialareas/ COPY ./requirements.txt /industrialareas/ WORKDIR /industrialareas RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 CMD service cron start docker-compose.yml: version: '3.7' services: django: container_name: industrialareas_django_ctnr build: context: . dockerfile: Dockerfile-django restart: unless-stopped env_file: ./project/project/settings/.env command: python manage.py check command: python manage.py collectstatic --noinput command: python manage.py runserver 0.0.0.0:8000 command: python manage.py crontab add volumes: - ./project:/industrialareas depends_on: - postgres ports: - 8000:8000 But when I go into the container and run the service cron status command, I get the error. [FAIL] cron is not running ... failed! Anybody could help me please ? Thanks in advance. -
Installing Django
I want to install django but I am facing with this error. C:\Windows\system32>pip install django WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', TimeoutError('_ssl.c:980: The handshake operation timed out'))': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)'))': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000002A70BBAAFB0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000002A70BBAB430>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))': /simple/django/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000002A70BBAB610>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))': /simple/django/ ERROR: Could not find a version that satisfies the requirement django (from versions: none) ERROR: No matching distribution found for django -
How to create a custom Django session
I am creating an app where I am sending a post request with the user_phone and password if the password is correct the API return user_phone and success status. Now I understand if normal django app we simply put user = authenticate(user_phone=user_phone, password=password) if user: login(request, user) this the response of my api if the user enters correct credentials {'status': 'success', 'data': {'user_phone': 38938339839}} But I don't understand How should I save here as this I can;t use the login function here. Please I have been stuck here for days. -
Django-react native (axios) Request failed with status code 403 Post
I was doing put and post operations with axios in React Native before. But then I got the following error. I'm sending cookies in the headers, but it doesn't solve the problem. Help me please. enter image description here -
Joining UserModel form and Model Form
I have created a custom UserModel using one-to-one field. I have provided signal to create the model once the user is created.What can I do to collect the rest of the information along with the usermodels fields. Here is my code: #models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField import datetime from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.auth.models import User from twilio.rest import Client # Create your models here. class Customer(models.Model): customer = models.OneToOneField(User, null=True,blank=True,on_delete=models.CASCADE) first_name=models.CharField(blank=True,max_length=100, null=True) last_name=models.CharField(blank=True,max_length=100,null=True) address = models.TextField(blank=True,null=True) contact_no = PhoneNumberField(blank=True,null=True) email = models.EmailField(blank=True,null=True) operator = models.ForeignKey(User,related_name='Operator_name', null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return str(self.customer.username) #views.py @login_required(login_url='login') @allowed_user(allowed_roles=['operator']) def registerPage(request): form = CreateCustomerForm() if request.method == 'POST' : form = CreateCustomerForm(request.POST) if form.is_valid(): form.save() return redirect('customer_detail') context = {'form':form} return render(request,'operator_app/register.html',context) #This below view was used to create the model before I attached the UserModel @login_required(login_url='login') @allowed_user(allowed_roles=['operator']) def customer_create(request): form= CustomerForm() if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): form.save() first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') messages.success(request, f'Account Created of { first_name } { last_name }!') return redirect('customer_detail') else: form = CustomerForm() context={'form':form} return render(request,'operator_app/customer_create.html',context) #forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import Customer, Payment … -
Django-python coding explanation
What is static method and how can we explain the below code ? @staticmethod def get_model(**kwargs): try: return Model.objects.get(**kwargs) except Model.DoesNotExist: return -
How can I fetch one column with conditons in Django
id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) limit = models.PositiveIntegerField(default='255') date = models.DateField() Hello . This is my model.I want to fetch the data for "limit" and "where id = 5" for example. How can I do that ? I want to use it as Integer. not Queryset. -
How to implement opsgenie in the logging system?
through opsgenie-sdk and opsgenie-logger, I have implemented at code level, sending errors to opsgenie, I wanted to ask you if there is the possibility to insert it in the internal logging system of django. -
How to add context data to Django CreateView when form is valid
Using Django, I have a page with a form that is rendered using CreateView. The success_url is the same url as the original form. When the form is submitted and is valid, I want to insert some data into the context. I'd like to know the most flexible and clear way to add this context data, because the example below (which works) feels sub-optimal for such a (presumably) common task. I'm looking for a more general solution that using SuccessMessageMixin. class DemoView(CreateView): template_name = "request-demo.html" form_class = DemoForm success_url = reverse_lazy("base:demo") def form_valid(self, form): create_and_send_confirmation_email(form) return self.render_to_response(self.get_context_data(success_message=True)) -
How to make a model parameter unique by a other parameter in Django?
I want my id field to be unique per each customer field. Just like the option unique_for_date from Django (https://docs.djangoproject.com/en/1.11/ref/models/fields/#unique) but in this case, not date but customer. class Sample(NGObject): id = models.CharField(max_length=128, null=True, blank=False) customer = models.ForeignKey(Customer, related_name="blood_samples", on_delete=models.SET(get_default_customer)) I believe this should be done, before the save() method? When a User writes the wrong ID (that already exists) I would also like to present the information in the Admin Form just like it would for normal unique error. -
Adding choice to a Django ModelForm
I have a basic Django ModelForm working. I am trying to add a Django choice (select/drop-down) to that ModelForm. The code I have has been cobbled together from various example on the web (see below) – as I try to learn Django. So far I cannot find the correct code to add the Django choice. What I have coded is below. I have tried various combinations of keywords and parameters in forms.py for example: from django.forms import ModelForm # from .models import P2Poll # categ_choice= [ ('AB', 'AB'), ('CD', 'CD'), ('EF', 'EF'), ('GH', 'GH'), ] # class AnyForm(ModelForm): class Meta: model = P2Poll fields = ['q_text', 'Choice1_text', 'Choice2_text','C1_Type','C2_Type'] # category = forms.ChoiceField(max_length=2, choices=categ_choice) # The code has been taken from the following (among others) django use model choices in modelform https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/ https://www.geeksforgeeks.org/meta-class-in-models-django/ http://www.learningaboutelectronics.com/Articles/How-to-create-a-drop-down-list-in-a-Django-form.php When trying the code variation above, I get the following error message: .. \forms.py", line 28, in Meta category = forms.ChoiceField(max_length=2, choices=categ_choice) NameError: name 'forms' is not defined I have tried a variety of other code attempts to add the choice/select to my Django form, for example: from django.forms import ModelForm, forms and I can’t get any to work – there are different error messages, but they … -
Max retries exceeded (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))
I'm getting an error max retries exceeded and 403 forbidden but when I run server on localhost it's working perfectly fine. I'm showing data from an API in django template I also tried to turn off validation and keep alive sessions but nothing intersting happened I'm getting same error my code: def index(request): try: url = "https://www.hetzner.com/a_hz_serverboerse/live_data.json" s = requests.session() s.keep_alive = False r = requests.post(url, verify=False, timeout=5) data = response.json()['server'] p = Paginator(data, 20) pn = request.GET.get('page') page_obj = p.get_page(pn) context = { 'data': data, 'page_obj': page_obj } return render(request, 'index.html', context) except requests.exceptions.ConnectionError as e: return HttpResponse({e}) -
Hosting two different django project in the same droplet with different subdomains (NGINX, Gunicorn, ubuntu)
As the title says I want to host two different django project in the same droplet (NGINX, Gunicorn, ubuntu) with different subdomains. One will be our main site example.com. which is up and running and working perfectly. We want to host the staging site staging.example.com in the same droplet. We have created new sockets and service files for the staging site and activated and enabled them but the issue is nginx still points to the files in main domain directory rather than the staging directory and hence we get this error below even though these domains have been added in the allowed hosts of settings.py of the staging site DisallowedHost at / Invalid HTTP_HOST header: 'staging.example.com'. You may need to add 'staging.example.com' to ALLOWED_HOSTS Here is our staging.guinicorn.service file [Unit] Description=staging.gunicorn daemon Requires=staging.gunicorn.socket After=network.target [Service] User=admin Group=www-data WorkingDirectory=/home/admin/example1staging ExecStart=/home/admin/example1staging/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/staging.gunicorn.sock djangoproject.wsgi:application [Install] WantedBy=multi-user.target Here is our staging.guicorn.socket file [Unit] Description=staging.gunicorn socket [Socket] ListenStream=/run/staging.gunicorn.sock [Install] WantedBy=sockets.target Lastly here is our nginx config server { listen 80; listen [::]:80; server_name example.com www.example.com; return 302 https://$server_name$request_uri; } server { # SSL configuration listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/cert.pem; ssl_certificate_key /etc/ssl/key.pem; ssl_client_certificate /etc/ssl/cloudflare.crt; ssl_verify_client on; … -
How to include Django CSRF token in JavaScript API fetch?
I created simple API in Django and I need to fetch it with JavaScript, I get following error: Forbidden (CSRF token missing.): URL(placeholder instead of real url) fetch(`/Post/${content[i].id}`, { method: "POST", }).then((data) => { console.log(data); }) How can I include token in API call? -
Error installing django-mssql, pyodbc in django
I am trying to install mssql-django package to my EC2(ubuntu) Server so that I connect my application to sql server But I got stuck while installing mssql-django with an error with pyodbc message is below pipenv.exceptions.InstallError]: warnings.warn( [pipenv.exceptions.InstallError]: running build [pipenv.exceptions.InstallError]: running build_ext [pipenv.exceptions.InstallError]: building 'pyodbc' extension [pipenv.exceptions.InstallError]: In file included from src/buffer.cpp:12:0: [pipenv.exceptions.InstallError]: src/pyodbc.h:45:10: fatal error: Python.h: No such file or directory [pipenv.exceptions.InstallError]: #include <Python.h> [pipenv.exceptions.InstallError]: ^~~~~~~~~~ [pipenv.exceptions.InstallError]: compilation terminated. [pipenv.exceptions.InstallError]: error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1 [pipenv.exceptions.InstallError]: [end of output] [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: note: This error originates from a subprocess, and is likely not a problem with pip. [pipenv.exceptions.InstallError]: error: legacy-install-failure [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: × Encountered error while trying to install package. [pipenv.exceptions.InstallError]: ╰─> pyodbc [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: note: This is an issue with the package mentioned above, not pip. [pipenv.exceptions.InstallError]: hint: See above for output from the failure. ERROR: Couldn't install package: pyodbc Package installation failed... ☤ ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/1 — 00:00:03 I am using python 3.8 in pipenv and I think I tried everything Including pip install pyodbc, sudo apt install unixodbc-dev. Please Help.. -
React is not showing posts of request.user in Django Rest Framework
I am building a Blog App in Django and React and I am trying to get posts only of request.user, and In Django Rest Framework Dashboard (api as json) posts are perfectly showing of request.user But when i try with axios.get() in React Frontend then it is showing nothing. views.py class BlogView(viewsets.ModelViewSet): serializer_class = BlogSerializer def get_queryset(self): queryset = Blog.objects.filter(user_id=self.request.user.id) return queryset serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = ('id','user'','title', 'description') React - App.js componentDidMount() { let data; axios.get('http://127.0.0.1:8000/api/blogs/`).then((res) => { data = res.data; this.setState({ blogs : data.map((blog) => { return Object.assign({}, blog, { title : blog.title, description : blog.description, }); }), }); }) .catch(err => {console.log(err)}); }; I have tried many times but accessing it using filter(user=self.request.user) but it didn't worked for me. When I refresh React Page then it is showing [16/Feb/2022 14:05:21] "GET /api/blogs/ HTTP/1.1" 200 2 in Django Server. Any help would be much Appreciated. Thank You in Advance. -
Django - display "work-in-progress" after submitting form until result is returned
I have a online pricing webpage where customer can input some data, then submit the form to get the price returned. How to display a "work-in-progress" kind of thing temporarily before the final result (e.g. price) is calculated/returned. below is the simplified code from my web: html (Note: I am using htmx to help partially update the page result) <html> <body> <form method="POST" hx-post="{% url 'post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> <script src="https://unpkg.com/htmx.org@1.6.1"></script> </body> </html> view.py def post_list(request): result = "" num1 = "" num2 = "" if request.method == "POST": num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1) + int(num2) if request.headers.get('Hx-Request') == 'true': # return only the result to be replaced return render(request, 'blog/post_list_snippet.html', {'num_1': num1,'num_2': num2,'result': result}) else: return render(request, 'blog/post_list.html', {'num_1': num1,'num_2': num2,'result': result}) -
How to declare global variable for all user in Django application?
I want a Queue implementation in my code so all users request is stored in that Queue. I tried implementing request.session['Queue'] but it not working every time its create the new one. My view def fetchVideosContent(request): acc = Account.objects.filter(assgined_to=request.user) tags = request.data['tags'] count = request.data['count'] GenrateLog(log=f'{request.user.username} Staring proccess ') if 'proxyQueue' not in request.session: <--- on every call its enter here GenrateLog(log=f'{request.user.username} Staring Queue') request.session['proxyQueue'] = [] <-- every time new list created else: GenrateLog(log=f'{request.user.username} Addedinf in Queue') <-- not coming here -
how to get data from database using django channels?
I'm trying to practice WebSocket implementation using django channels by querying the database and printing the data but I am unsuccessful. import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import Chart from chart.api.serializers import ChartSerializer class ChartConsumer(AsyncWebsocketConsumer): def get_chart(self): return database_sync_to_async(Chart.objects.all)() async def connect(self): data = await self.get_chart() print(data) # <-------- I want to get this data # for i in data: # chart_data = ChartSerializer(i).data # await self.send(json.dumps({'number': chart_data.number})) # print(chart_data) await self.accept() async def disconnect(self, code): pass -
React-router-dom v6 didn't show page when try to route
Hi guys so I'm trying to learn about react-router-dom newest version which is version 6. I tried to create a basic routing in my react-django app, but it didn't work if I create many Routes, for example when i change my route into 8000/product it will show page not found. Can anyone help me with it ? App.js: import React from "react"; import HomePage from "./components/HomePage"; import Product from "./components/Product"; import ProductDetail from "./components/ProductDetail" import { BrowserRouter as Router, Routes, Route, Outlet, } from "react-router-dom"; const App = () => { return ( <> <Router> <Routes> <Route path="/" element={<HomePage/>}/> <Route path="/product" element={<Product/>}/> <Route path="/productdetail" element={<ProductDetail/>}/> </Routes> </Router> <Outlet/> </> ) } export default App