Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get related objects for related objects of an object in Django in a single query when all linked using Generic Foreign Key
Assuming I have the following models and knowing that each Message can have multiple Records and each Record can have multiple Notes, how can I get a queryset of related Notes from a Message in a single query? class Note: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Record: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey() notes = GenericRelation(Note, related_query_name='records') class Message: records = GenericRelation(Record, related_query_name='messages') I know how to achieve this by using list comprehensions like shown below, however it is a bad approach since this will do multiple queries. if records := message.records.all(): notes = list(chain.from_iterable([record.notes.all() for record in records])) -
How to handle POST request from react to django?
How to handle a post request? I don't have any spec about that request. How do I can handle it proper that request and write in to my model? -
Django/AWS - An error occurred (403) when calling the HeadObject operation: Forbidden
I'm trying to set up my Django project to host static images on AWS S3 buckets, but when I try to upload an image via the Django admin panel I get the following error These are my settings in Django AWS_ACCESS_KEY_ID = 'some_key' AWS_SECRET_ACCESS_KEY = 'some_key_aswell' AWS_STORAGE_BUCKET_NAME = 'bucket_name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'us-east-2' Cors policy setup for the bucket [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] -
after deleting a superuser, all its entries are deleted django
there are also recent actions in the admin panel, for example, after creating an article, an inscription appears there, saying that this user created such an article, but after deleting this user, this last action is also deleted and I wish this last action was not deleted from the log how should i implement this? -
How to add images to python docxtpl from url
I have a docxtpl document, but I need to add images to the InlineImage from a url, not local disk. I'm using Django So this works (document is a DocxTemplate): InlineImage(document,'C:/Users/sande/Pictures/myimage.png') But how do i do this?: InlineImage(document,'https://files-cdn.myhost.net/3255/ddef9d07-0a6b-4f54-801a-c016e6d41885/myimage.png') the image_descriptior doesn't accept a url.: Exception has occurred: OSError [Errno 22] Invalid argument:'https://files-cdn.myhost.net/3255/ddef9d07-0a6b-4f54-801a-c016e6d41885/myimage.png' -
Use parameters in subfields with graphene-django without relay for pagination purpose
I'm using graphene with django and I'm struggling to do something that in my head should be very simple, but I don't find it documented anywhere in graphene docs or github nor did I see similar question here. The closest to it I found was: https://www.howtographql.com/graphql-python/8-pagination/ but as you can see I'd have to declare the parameters in the parent resolver which I don't want to. I have a query like this getUser(id: $userIdTarget) { id username trainings{ id name sessions{ id name } } } } I would like to implement a pagination in the sessions subfield. So this is what I would like: getUser(id: $userIdTarget) { id username trainings{ id name sessions(first:10){ id name } } } } and in the resolver I'd implement something like this: def resolve_sessions(root, info, first=None, skip=None): if skip: return gql_optimizer.query(Session.objects.all().order_by('-id')[skip:], info) elif first: return gql_optimizer.query(Session.objects.all().order_by('-id')[:first], info) else: return gql_optimizer.query(Session.objects.all().order_by('-id'), info) (gql_optimizer is just an optimization wrapper library I use) However this doesn't work as the field sessions correspond to a list of a model Session that is a fk to Training according to my django models, so this is automatically resolved by graphene because these types are DjangoObjectType , so I'm not … -
Django append products in categories with same names
and im tying to append products to categories with same name For example this is my models. models.py class Category(models.Model): headline = models.CharField(max_length=150) parent_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True, blank=True) class Product(models.Model): headline = models.CharField(max_length=150) category = models.ManyToManyField(Category, related_name = 'products') views.py #For Example I have Main Category Technic. that has 2 child categories (Mobile Phones and SmartPhones) and both have category Phone with same name See the Tree: #Technic -> Mobile Phones -> Phone AND Technic -> SmartPhones -> Phone Technic -> Mobile Phones -> Phone - Contains 4 products Technic -> SmartPhones -> Phone - Contains 0 products All im trying to do is to check if smallest(childest) category has same name take its produts and fetch to another Phone Category in this position #Desired Result -> Technic -> Mobile Phones -> Phone - Contains 4 products ( same products ) Technic -> SmartPhones -> Phone - Contains 4 products ( same products ) Because both last child cat names are the same. -
Migrating back from DateTimeField to DateField in Django
I have a Django Model with two DateTimeFields: class FacilityTender(models.Model): """ Class to store Facility Tender """ publisher = models.ForeignKey('company.Company', on_delete=models.CASCADE) publish_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() end_date = models.DateTimeField() ... I now have to change the DateTimeFields to DateFields. Doing so, the app can't be deployed since when quering the objects created before the migration don't fit to the new DateField. There is no error coming up when running the migration itself. It returns: invalid literal for int() with base 10: b'31 11:41:29' for this qs: running_tenders = FacilityTender.objects.filter(publisher__cashpool__name=user_cashpool.name) Full Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/facilities Django Version: 3.2.9 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'applications.bank', 'applications.cashpool', 'applications.company', 'applications.core', 'applications.dashboard', 'applications.universe', 'applications.user'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Template error: In template /Users/jonas/PycharmProjects/Finchin/applications/dashboard/templates/dashboard/dashboard_frame.html, error at line 0 invalid literal for int() with base 10: b'31 11:41:29' 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : {% load static %} 4 : 5 : <head> 6 : 7 : <!-- Meta --> 8 : <meta charset="UTF-8"> 9 : <meta name="viewport" content="width=device-width, initial-scale=1"> 10 : Traceback (most recent call last): File "/Users/jonas/PycharmProjects/Finchin/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) … -
How to dynamically remove forms from an unbound formset without JavaScript in Django
I have a solution, but it contains one problem. I know where the problem is happening in the code, but I can't solve it. Maybe someone has a better solution that doesn't contain any problems. Description of the problem: After deleting any form, the fields in the remaining forms are not pre-filled if the data is not valid. Procedure: The browser displays 5 forms. The first field of the first form contains invalid data. I activate the delete check-box in the last form and click on the "delete" button. The last form is deleted and the first field of the first form is not pre-filled. Cause Invalid data does not end up in cleaned_data after the is_valid () method, which is called in the not_deleted_forms () method of the TestFormSet class Code: app_formset.forms.forms from django import forms class TestForm(forms.Form): title = forms.CharField(label='Title', min_length=5) description = forms.CharField(label='Description', max_length=10) app_formset.forms.formsets from django.forms.formsets import BaseFormSet class TestFormSet(BaseFormSet): @property def not_deleted_forms(self): """Return a list of forms that have not been marked for deletion.""" self.is_valid() if not hasattr(self, '_not_deleted_form_indexes'): self._not_deleted_form_indexes = [] for i, form in enumerate(self.forms): if i >= self.initial_form_count() and not form.has_changed(): self._not_deleted_form_indexes.append(i) elif self._should_delete_form(form): continue else: self._not_deleted_form_indexes.append(i) return [self.forms[i] for i in … -
How can I use 'pdfkit' in djngo?
I want to generate pdf in my django project. I use pdfkit module to convert html page as a pdf file. I use this function but it has errors, like: OSError Exception Value: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it or you can pass path to it manually in method call, check README. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf def customer_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') customer = get_object_or_404(Person, pk=pk) enrolment = get_object_or_404(Enrollment,pk=pk) template_path = 'test.html' context = {'customer': customer, 'enrolment':enrolment} template = get_template(template_path) html = template.render(context) pdf = pdfkit.from_string(html, False) response = HttpResponse(pdf, content_type='application/pdf' ) response['Content-Disposition'] = 'filename= "report.pdf"' return response -
Connect Angular Frontend to Django View
I have a basic django app that simply uploads an excel file onto an oracle database. I created a python class (uploader) to carry out some the sanity checks on the file and upload to the database. I have managed to successfully create a UI using HTML in Django templates which works fine. However, I wanted to migrate the front end to an Angular front end. I have created the angular app but I am currently struggling to understand how to connect the front end to django. Having researched online, they advise using models, serializers but because I carry out the upload through a standalone python class, I am not sure how to connect the two using this method. I assume I have to use a HttpClient to somehow connect to this view? Any help will be greatly appreciated. Thanks upload/views.py def clickToUpload(request): if request.method == 'POST': if 'form' in request.POST: try: upload_instance = uploader(request.FILES['file'], request.POST['date']) _ = upload_instance.run_process('File', update_log=True) message= "Success" except Exception as e: upload_message = 'Error: ' + str(e) return render(request, 'Upload/upload.html', {'upload_message':upload_message}) -
ModelForm doesnt render input fields properly
I have the following ModelForm: class RaiseTender(forms.Form): """ A form to raise a new tender for new facilities """ country = forms.ModelChoiceField(queryset=OperatingCountries.objects.all(), required=True) publisher = forms.ModelChoiceField(queryset=Company.objects.exclude(name='exclude-all')) class Meta: model = FacilityTender fields = ['publisher', 'amount', 'currency', 'country', 'start_date', 'end_date'] # Model class FacilityTender(models.Model): """ Class to store Facility Tender """ publisher = models.ForeignKey('company.Company', on_delete=models.CASCADE) publish_date = models.DateTimeField(auto_now_add=True) amount = models.FloatField() currency = models.CharField(max_length=3) country = models.CharField(max_length=50) start_date = models.DateTimeField() end_date = models.DateTimeField() submissions = models.IntegerField() is_active = models.BooleanField(default=True) is_closed = models.BooleanField(default=False) is_successful = models.BooleanField(default=False) # Checks how long is left for the tender period, # Assumes a 7 day tender duration @property def time_remaining(self): return self.publish_date + timedelta(days=7) def __str__(self): return F"{self.publisher} tendered {self.amount} {self.currency}" Now in my my view I do the following: def raise_tender(request): if request.method == 'GET': # Get the user instance user = User.objects.get(username=request.user.username) # Query companies associated to the cash pool of the requesting user companies = Company.objects.filter(cashpool__company=user.company) # Override the RaiseTenderForm company field RaiseTender.base_fields['publisher'] = forms.ModelChoiceField( queryset=companies) # Return the form form = RaiseTender() # Process inputs on POST request else: .... But for whatever reason the form only renders the fields where I provide a queryset to pre-populate. It's not the case with … -
Get the instance of related model and save
I need to create and save with the related model. My model looks like Class Abs(models.Model): detail = models.ForeignKey(Detail, ........) class Detail(models.Model): user = models.ForeignKey(get_user_model(), ...) detail_parts = models.ForeignKey(Abs,....) What I want to achieve is to create a new A and retrieve its instance and create a new Detail with user and detail_parts (related to model Abs) inside view class AView(viewsets.ModelViewSet): def create(self, request, *args, ** kwargs): detail = request.data.get(detail) // a = A.objects.filter(detail=detail) // here it return integer(example 20) Detail.objects.create(user=user,detail_parts=a) // returns Detail.detail_parts must be a "Abs" instance Any ideas ? -
Why the session isn't delete after I log out?
Got stuck in a problem about session in Django3.2. After I added a login/register user to the project that I'm creating, the logout doesn't work. When I log out, the sessionid isn't delete, and if its not delete then the user can still have access after it is been log out. I used the request.session.flush() based on the answer I recived at my last question: Why the login_requried decorator doesn't work after I log out from the account? but its not working, the session is not deleted. For better understanding will show the code below: @login_required(login_url='login/') def logoutUser(request): logout(request) request.session.flush() return redirect('/') -
how to exclude admin user from my user list
how to exclude admin users from my user list the below image shows the problem I don't want to show the admin user in the friend list of a user. I don't want to show the main_admin user on this user list as it is my admin user of the site views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Profile from feed.models import Post from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.conf import settings from django.http import HttpResponseRedirect from .models import Profile, FriendRequest from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm import random User = get_user_model() @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) sent_to = [] friends = [] for user in users : friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends += friend my_friends = request.user.profile.friends.all() for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) random_list = random.sample(list(users), min(len(list(users)), 10)) for r in random_list: if r in friends: random_list.remove(r) friends += random_list for i in my_friends: if i in friends: friends.remove(i) for se in sent_friend_requests: sent_to.append(se.to_user) context = { 'users': friends, 'sent': sent_to } return render(request, "users/users_list.html", context) # … -
Django: Render API response to html, one page at a time
I have an API that returns a paginated response. My view (shown below) tries to get the response from this API and renders it to HTML search_result.html. However, I am only able to fetch the first page of the API response and not other pages. View.py query_url = "/api/transcript/search/?identifier_field=" + search_identifier + \ "&expand=transcript_release_set,genes,translations" response = requests.get(host_url + query_url) if response.status_code == 200: search_result = response.json() return render(request, 'search_result.html', context={'form': search_form, 'search_result': search_result, 'search_identifier': search_identifier}) The API response has been implemented through the below view: View2.py class TranscriptSearch(generics.ListAPIView): queryset = Transcript.objects.all() serializer_class = TranscriptSearchSerializer filter_backends = (TranscriptSearchFilterBackend, ) pagination_class = PageNumberPagination def get_queryset(self): queryset = Transcript.objects.order_by('pk') return queryset def get(self, request, *args, **kwargs): result = super(TranscriptSearch, self).get(request, *args, **kwargs) return result I do not want to render to HTML all API response pages at one go, that will slow down the loading of the HTML page. I want to load each API response page only when the user clicks a page number from HTML. So, how can I render to HTML each page of the API response one by one, without rendering all pages at once? -
Celery beat task is not executing when provided specific time
This question appears many times in stackoverflow, but I could not find correct answers (tried all the suggested ones, none of them worked). The code is as follows 'get-sensor-values': { 'task': 'weathers.tasks.get_fieldclimate_data_between_dates', 'schedule': crontab(hour='*/3'), }, 'Daily-Task-Start': { 'task': 'weathers.tasks.notify_task_start', 'schedule': crontab(hour=10, minute=54), }, The first one works, second one does not. -
Send a JSON through Django REST Framework
I am getting started with the Django rest framework and I encountered a problem that I am still not able to solve. Here is the problem: I want to create a tech store website. Using the API that the manufacturing company provides, I will upload the products on my website. The manufacturing company uses XML, and the result of the API is XML. Using python I converted the XML output from the API to JSON. Here is the code for that: import requests import xmltodict import json url = 'https://www.parterURLProductsInStock.asmx' headers = {'content-type': 'text/xml'} raw_data = """<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetCTProducts xmlns="http://www.partnerURL.com/B2B"> <username>username</username> <password>psw</password> </GetCTProducts> </soap:Body> </soap:Envelope>""" x = requests.post(url, data=raw_data, headers=headers) js = xmltodict.parse(x.text) print(json.dumps(js)) For my website, I want to use Django and React. So in order to get the products in the frontend, I need an API, and in most cases, Django REST Framework is used. I know that with the Django REST Framework we can convert classes from modules.py into JSON and send it to the front using serializers. But how can I send the data (JSON) that is stored in my js variable? If anyone can helo me that would be … -
Django models relations: connect field to instances of itself
I am creating a network devices tracker where I want interfaces to be connected to one another only on some criteria. I am however stack at trying to connect interfaces together. I think my models logic is not right as in InterfaceConnection I am connecting an interface to a Device, not another interface. from django.db import models from django.core.exceptions import ValidationError from .constants import ROLES, FORM_FACTORS class Device(models.Model): hostname = models.CharField(max_length=200, unique=True, blank=False, null=False) ip_address = models.GenericIPAddressField(blank=False, null=False) role = models.CharField(max_length=20, choices=ROLES, blank=False, null=False) def __str__(self) -> str: return f"Device #{self.id} - hostname {self.hostname}" class Interface(models.Model): device = models.ForeignKey(to=Device, to_field="hostname", on_delete=models.CASCADE, related_name="interface") name = models.CharField(max_length=200, blank=False, null=False) form_factor = models.CharField(max_length=10, choices=FORM_FACTORS, blank=False, null=False) def __str__(self) -> str: return f"Interface #{self.id} - {self.name}" class InterfaceConnection(models.Model): interface = models.ForeignKey(to=Interface, blank=True, null=True, on_delete=models.CASCADE, related_name="interface_connection") device = models.ForeignKey(to=Device, blank=False, null=False, on_delete=models.CASCADE, related_name="interface_connection") def clean(self) -> None: if self.interface and self.interface.form_factor == 'virtual': raise ValidationError({ "interface": "virtual interface cannot be connected to any other interface" }) return super().clean() class Meta: unique_together = ("interface", "device") def __str__(self) -> str: return f"Connection #{self.id} - interface {self.interface.name} - device {self.device.hostname}" How do I express this type of relationship? I appreciate any insights. -
I am unable to identify my error in writing unit test for Django rest_farmework
I am trying to write a unit test to check my view for password reset in Django rest_framework. I can't identify where is the error and why am I getting the error. I am a beginner in django rest_framework. I would appreciated your help. my View.py from user_authentication.models import User as Client from rest_framework.response import Response from rest_framework.views import APIView class Password_Reset(APIView): def post(self, request): username = request.data.get('username') if Client.objects.filter(username = username).exists(): new_password = request.data.get('new_password') confirm_password = request.data.get('confirm_password') if new_password == confirm_password: user = Client.objects.filter(username = username).first() user.set_password(new_password) user.save() return Response({"message": "your password has been changed"}, 201) else: return Response({"message": "This email address doesn't exist"}, 404) my model.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): created_at=models.DateTimeField(auto_now_add=True) email = models.EmailField(verbose_name="Email", max_length=60, unique=True) date_of_birth= models.DateField(verbose_name="Date of Birth", max_length=10) def __str__(self): return self.username my urls.py from django.urls import path from user_authentication.views import Login, Logout, Register, Password_Reset urlpatterns = [ path('login/', Login.as_view()), path('logout/', Logout.as_view()), path('register/', Register.as_view()), path('login/password_reset', Password_Reset.as_view()) ] my Unit Test for password reset from rest_framework.test import APITestCase from user_authentication.models import User from user_authentication.views import Password_Reset, Register, Login, Logout class ViewTest(APITestCase): def test_password_reset(self): url = 'login/password_reset' response = self.client.post(url, {'username': "developer", "new_password": "abc1234", "confirm_password": "abc1234"}) user = User.objects.get(username = 'developer') … -
Django ForeignKey, hide from user select options in dropdown menu
I have standard Django models with ForeignKey. Django docs: "ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet." and "If the model field has choices set, then the form field’s widget will be set to Select, with choices coming from the model field’s choices." Now I have dropdown menu with choices. I don't want dropdown menu where user can see options. I want CharField(textfield or similar) where user type, but still that must be one of the options from the database for that field. He must type a valid entry. I tried: class TransakcijeForm(forms.ModelForm): model = models.Transakcije fields = ..... labels = ..... widgets ={'subscriber':forms.TextInput()} but I receive the message: "Select a valid choice. That choice is not one of the available choices." (entry is correct and it works with dropdown menu) This is my first question here and I'm sorry if I miss the form. -
Django-filter Choice Filter does not recognize an existing field
I am trying to appply a ChoiceFilter however it as if the field I am referring to is not recongized wherehas it does exist : ModelViewsSet : class StartUpViewSet(NestedViewSetMixin, ModelViewSet): """ Class that provides List, Retrieve, Create, Update, Partial Update and Destroy actions for startups. It also include a filter by startup status """ model = Startup queryset = Startup.objects.all() serializer_class = StartupSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = 'status' FilterClass : class StartupFilter(filters.FilterSet): status = filters.ChoiceFilter(choices=START_UP_STATUS) class Meta: model = Startup fields = ['status'] And model : class Startup(models.Model): header = models.CharField("Header", max_length=255) title = models.CharField("Title", max_length=255) description = models.CharField("description", max_length=255) # TODO Change this to options instead of array tags = ArrayField(models.CharField(max_length=10, blank=True), size=5) # TODO Images to be stored in aws only url will be in DB card_image = models.ImageField(upload_to='media/images/cards') logo_image = models.ImageField(upload_to='media/images/logos') main_img = models.ImageField(upload_to='media/images/main', null=True) createdAt = models.DateTimeField("Created At", auto_now_add=True) status = models.IntegerField(choices=START_UP_STATUS, default=1) def __str__(self): return self.title -
I can't access to public IPv4 address not public IPv4 DNS
i opened all inbound rules, and outbound rules. i can access to public ipv4 DNS well. IPv4 Address IPv4 DNS What should i do.... -
Getting all LDAP users with django
I'm using django-auth-ldap and I'm trying to get all users from LDAP server, I didn't find a way to do so, the authenticating is working in the backend, here is my code @api_view(['GET']) def users(request): l = ldap.initialize(backend.AUTH_LDAP_SERVER_URI) l.simple_bind_s(backend.AUTH_LDAP_BIND_DN, backend.AUTH_LDAP_BIND_PASSWORD) users = LDAPBackend().ldap_to_django_username('*') #this line is returning None print (users) serializer = userSerializer(users, many=True) return Response(serializer.data) I know that line is incorrect LDAPBackend().ldap_to_django_username('*') but I really need to get all users with something like this : conn.search('ou=users, dc=example,dc=com', '(objectclass=person)', attributes=['uid', 'cn', 'givenName', 'sn', 'gidNumber']) (this is how I did with another library called ldap3) Thank you -
How to make changes to a Django website already deployed on heroku
Hello guys my name is Destiny and I really have this issue that I'm facing right now. I deployed a website on to heroku and I want to make changes to it, like add updates to the website but right now I don't know the right thing to do I don't know if I should re-deployed my new changes to heroku again, I don't just know what to do please if anybody has any idea on how I can do this any help would be greatly appreciated thanks a lot in advance