Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TypeError("sync_to_async can only be applied to sync functions.")
I am trying to making my class based view as async class based views. When I add sync_to_async to my api calls inside the class based view. I get an error TypeError: sync_to_async can only be applied to sync functions. I don't know and can't get how to make my class based view as async class based views. Here is my code: class PaymentSerailizer(serializers.ModelSerializer): class Meta: model = Payment fields = ( "quantity" ) @classonlymethod def as_view(cls, **initkwargs): view = super().as_view(**initkwargs) view._is_coroutine = asyncio.coroutines._is_coroutine return view def create(self, validated_data): stripe.api_key = settings.STRIPE_API_KEY object = sync_to_async(Payment.objects.get(company=self.context["request"].company)) sub_obj = sync_to_async(stripe.Subscription.retrieve(object.sub_id)) product = sync_to_async(stripe.Product.retrieve(sub_obj.get("items"))) The error I get are on each sync_to_async calls. I am not sure why I am getting this error. -
How to get data where ImageField in not null in django?
context_processor.py file def context_processor(request): context={} context['services'] = Services.objects.filter(bg_image__isnull=False) return context models.py class Services(models.Model): title = models.CharField(max_length=250) bg_image = models.ImageField(upload_to='services/', null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return self.title I have 7 record where 5 of them has bg_image rest of 2 bg_image are null. when I query the above code show 7 record has bg_image. who can I query property to get only those records where bg_image is not null? For queryset when I use within bracket active=True it works fine. -
every thing saving twice in django database using postgresql
Each record showing twice with same index.. when ever I tried to open any it give error File "/home/devops/cch_icd_env/lib/python3.8/site-packages/cacheops/query.py", line 352, in get return qs._no_monkey.get(qs, *args, **kwargs) File "/home/devops/cch_icd_env/lib/python3.8/site-packages/django/db/models/query.py", line 433, in get raise self.model.MultipleObjectsReturned( cch_icd.applications.xml_api_models.models.tag_detail.RequestTagDetail.MultipleObjectsReturned: get() returned more than one RequestTagDetail -- it returned 2! ERROR *** 16:48:13 *** django.request *** => Internal Server Error: /dashboard/xml_api_models/requesttagdetail/3007/change/ -
How forms.ModelForm get actual model in forms.py?
This is my models.py class Student(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50, blank=True) ids = models.CharField(max_length=20) def __str__(self): return self.ids class Teacher(models.Model): name = models.CharField(max_length=50) subject = models.CharField(max_length=50) department = models.CharField(max_length=50) def __str__(self): return self.name This is my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Student, Teacher class Rform(UserCreationForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] class Tform(forms.ModelForm): class Meta: model = Teacher fields = '__all__' class Istudent(forms.ModelForm): class Meta: model = Student fields = '__all__' In this forms.py every class inheritance forms.ModelForm we are not declare model name in each class but every class show rightly model field in every form how? -
State of mptt query varies while debugging depending on breakpoints
I am using a model called Tree based on MPTTModel. In the view for Tree I wrote a function to move Objects around in tree. This is a strongly simplified version of the function: @transaction.atomic def move(self, request, source, target, *args): source_child_descendants = source.get_descendants(include_self=True) ancestors = source.get_ancestors() if target == 'none': return self.move_root(source) else: source.move_to(target) source.inherit_permission(descendants=source_child_descendants) return result The weird thing is, that depending on where I set breakpoints the value of source_child_descendants changes. If I set a breakpoint anywhere between the initialization of source_child_descendants and source.move_to(target), the value stays as intended. When not doing so it changes. So it behaves differently when observed. -
Django Rest Framework Stateful Token Auth
What is the best approach to implement stateful token authorization in django rest framework? I want to use this approach to prevent multiple login for any user. -
Django filtering if an object has the specified value or is either isnull
I have a view that returns all the users that are either working in or are students in the school that the request.user owns, in my model's I have two fields works and learns that are foreignkey fields referencing the school object, when filtering the users to match the school that the request.user owns, I have to filter like something like so: class AllUserList(generics.ListAPIView): permission_classes = [IsSchoolOwner, ] # queryset = User.objects.exclude(type__isnull=True) serializer_class = ListUsersSerializer def get_queryset(self): request = self.request.user if request.type == User.TYPES.OWNER: queryset = User.objects.filter(is_active=True, type__isnull=False, works__in=request.owns.all(), learns__in=request.owns.all()) return queryset there is an issue here as users that are working in the school will have the learns fields as null and the students will have the works field as null so how can I find if either of the fields matches and if they do make it ignores the other field. -
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; …