Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset querying with OR function
I want to make a query (qs) and then another query on the queryset (qs2). In the second query, I want to put an or function, but it can't seem to work (maybe because I don't perform it on 'objects'?) If I only put one filter (membership) on the second query, it works fine. qs = ExpFiles.objects.filter((Q(member_id=id_input) & Q(card_type=card_input))).values(*filter_list).order_by('date_of_measurement') qs2 = qs.filter(Q(membership= membership_input) | Q(note=note_input)).values(*filter_list).order_by('date_of_measurement') -
bypassing the related field manager / referring alternate manager
My model (Lets say class "A") has two managers - the default one (objects), which hides some objects (applies a filter, let's say by a field hidden = models.BooleanField) and the second one, which shows only objects filtered by the default one (so applies opposite filter). So they are mutually exclusive. I did this on purpose, because i don't want to involve these filtered objects anyhow in the admin interface. So far, so good, it works. The problem i have is with related fields. I have a second model where i refer the first one (with these two managers) as ManyToMany field. class B(models.Model): object_a = models.ManyToMany() Now, in the logic i create some objects of the instance A with hidden = True (thus, invisible for the default objects manager of the class A). And i assign these objects to the instance of class B. instance_b.object_a.add(instance_a.hidden_object_a) Now, i thought it does not work, because instance_b.object_a.all() returns empty query result. But then i realised, that the default manager is also applied, so the query is filtered. And in fact, there are hidden objects assigned to the instance_b.object_a, they just cannot be returned by such a reference. How can i refer them … -
Employee model Linked to Django User
I have the Django User model and I created Employee model as below class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employees') title = models.CharField(_('Title'), max_length=6, default='Mr', choices=TITLE, blank=False, null=True) firstname = models.CharField(_('Firstname'), max_length=125, null=False, blank=False) In my sidebar.html I can access the username as {{ request.user }} but I want to show the title and firstname from the Employee model on the sidebar.html -
I want to access the ForeignKey and bring querysets in django-admin
I want to access the ForeignKey and bring querysets. Below pic is that I approached the instance and brought only the object. But I want to bring a query set. def card_income (self, instance): how can I get this part into querysets, not object? This function is an object, so obj.It can be approached like obj.account_amount. But I want to bring querysets. help bro!!! #admin.py @admin.register(DailySettlement) class DailySettlementAdmin(admin.ModelAdmin): list_display = ( "card_income", ) list_filter = (('accountbook', admin.RelatedOnlyFieldListFilter), ) def card_income(self, instance): obj=instance.accountbook print("000", obj) package_amount=obj.account_amount print("111", package_amount) return package_amount card_income.short_description = '카드 수익' # models.py class AccountBook(TimeStampedModel): account_amount = models.PositiveIntegerField(validators=[MinValueValidator(0)], null=False, verbose_name="금액") class DailySettlement(models.Model): accountbook = models.ForeignKey(AccountBook, on_delete=models.CASCADE, null=False, verbose_name="회계정산 외래키") settlement_card_income = models.IntegerField(null=False, verbose_name="일일정산 카드 수익") -
How do I replace values from one queryset with values from another queryset?
I have 2 models: UserRecipe user recipe UserSwappedRecipe user original_recipe replacement_recipe What I want to do is replace any recipe that may be defined in the Recipe Model with the replacement_recipe in the SwappedRecipe table WITHOUT converting it to a list or doing anything weird: user_recipes = UserRecipe.objects.filter(user=user) swapped = UserSwappedRecipe.objects.filter(user=user) # now we do some magic to replace any recipes in user_recipes with the swapped_recipes in swapped which I have no idea how to do. I need the replacement to be done within the user_recipes queryset so that my graphql resolvers etc keep working. My real database is significantly more complicated so I have tried to simplify the problem as much as possible. If anyone has any ideas that would be much appreciated. Thank you :-) -
How to remove strings from a json file
enter image description here I am trying to convert it into a json file but the thing is that the single quotations marks are in between the two brackets instead of being outside them so I cannot use JSON.parse() to convert it to a json so I don't know how to get rid of those single quotations at the start and end of the data. -
ListAPIView with the querset User.objects.all() makes 7 queries with only two users in the test database?
I was creating an endpoint using drf to list users. While testing the code, I realized that it calls 7 queries. models.py:(I think using django's User model will achieve the same result) class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_("The Email must be set")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Superuser must have is_staff=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must have is_superuser=True.")) return self.create_user(email, password, **extra_fields) class BaseUser(AbstractUser): email = models.EmailField(_("email address"), unique=True) id_number = models.CharField(max_length=MID_LENGTH) username = None USERNAME_FIELD = "email" REQUIRED_FIELDS = [email] objects = CustomUserManager() def __str__(self) -> str: return self.email serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = models.BaseUser fields = "__all__" api.py: class ListUserView(ListAPIView): permission_classes = [IsAdminUser] queryset = models.BaseUser.objects.all().order_by("id") serializer_class = serializers.UserSerializer test.py: from . import models from django.urls import reverse from django_seed import … -
I am getting Multiple Query set Errors in Django
I am working on an app that keep records of businesses and their employers Here is my model.py for Employment and Business class Employment(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey(Business, on_delete=models.CASCADE) role = models.CharField( max_length=128, choices=EMPLOYEE_ROLE_CHOICES, default="EMPLOYEE") deduction_amount = models.IntegerField(default=0, blank=True) email = models.CharField(max_length=1028) active = models.BooleanField(default=True) account_balance = models.PositiveIntegerField(default=0) and Business class Business(BaseModel): name = models.CharField(max_length=255) tax_id = models.CharField(max_length=255, blank=True, default="") contact_email = models.CharField(max_length=255) contact_first_name = models.CharField(max_length=255) contact_last_name = models.CharField(max_length=255) contact_phone = models.CharField(max_length=255, blank=True, default="") description = models.TextField(blank=True, default="") address = models.ForeignKey( Address, null=True, blank=True, on_delete=models.CASCADE) image = models.ForeignKey("main.Image", null=True, blank=True, on_delete=models.CASCADE) json_data = JSONField(blank=True, default=dict) I want to get ids of all the employees with specific business id like this employees =Employment.objects.filter(business=business, active=True) but when I try to get id employees.id I get error In [44]: employees =Employment.objects.filter(business=b, active=True) In [45]: employees.id <ipython-input-45-5232553f9273> in <module> ----> 1 employees.id AttributeError: 'QuerySet' object has no attribute 'id' if I use get instead of filter suggested by this link I still get error MultipleObjectsReturned: get() returned more than one Employment -- it returned 5! What should I do? Tried everything on stackoverflow -
Upgrade Django version from 2 to latest
I have a Django website on version 2 and now want to upgrade it to the latest version. First of all, I guess we need to upgrade PYTHON v2 to the latest than Django any suggestions or links -
Jar service needs restart to work again if data insertion in MC access db raises an error
I'm running a spring boot application (APIs with html) as a jar service. I have the following code, where I add data to MS Access database. private JdbcTemplate template; /* my extra code*/ try { insert = template.update("INSERT INTO tblE125Details (ForeasCode, EYear, ArProtokolou, InvNo, SName, Fname, DOB, sex, IDno, entipo, EKAANo," + "EKAAIssueDate, EKAAExpireDate, PaymentAmount, PaymentCurrency, HospFrom, HospTo)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", institutionID.substring(0,2), ProvidedBenefits_BenefitsPeriod_startDate.substring(0,4), globalCLAReferenceCreditorLiaisonBody, individualCLANumberCreditorLiaisonBody,familyName, forename, dateBirth, sexDescription, pINPersonInCompetentMemberState,db_entipo, eHICNumber, db_EKAAIssueDate, db_EKAAExpireDate, TotalIndividualAmountBenefits_amount, TotalIndividualAmountBenefits_currency, ProvidedBenefits_BenefitsPeriod_startDate, ProvidedBenefits_BenefitsPeriod_endDate); } catch (InvalidResultSetAccessException e) { throw new RuntimeException(e); } catch (DataAccessException e) { throw new RuntimeException(e); } However, when an error occurs, I need to restart the jar file. Is there any solution to force my service to run, even though an error occurred previously? This is an error I had and my service need to restart in order to work: 2022-02-22 09:34:21.673 ERROR 12536 --- [http-nio-8091-exec-4] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/eessi] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO tblE125Details (ForeasCode, EYear, ArProtokolou, InvNo, SName, Fname, DOB, sex, IDno, entipo, EKAANo,EKAAIssueDate, EKAAExpireDate, PaymentAmount, PaymentCurrency, HospFrom, HospTo) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)]; UCAExc:::4.0.4 data exception: string data, right truncation; table: TBLE125DETAILS column: INVNO; nested … -
Is there any way to access verification code before sending email in AWS Cognito in Python - PyCognito?
get-user-attribute-verification-code I've called above method and print its output. It's like this: {'CodeDeliveryDetails': {'Destination': 'f***@m***', 'DeliveryMedium': 'EMAIL', 'AttributeName': 'email'}, 'ResponseMetadata': {'RequestId': 'randomId', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Tue, 22 Feb 2022 07:09:18 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '100', 'connection': 'keep-alive', 'x-amzn-requestid': 'randomId'}, 'RetryAttempts': 0}} There's no parameter like CODE. My scenario: -> I'm writing a test case where you register a user in aws cognito and then hit a send-verify-email API. So, this method get-user-attribute-verification-code will send the code in the email, but is there any way I can read that code and store that in session for my test cases so that I can use that code in next Verify Email API call. -
How to add custom CSS to ckeditor in Django?
I'm currently building a Django Forums web application and I'm using CKEditor to allow users post rich text content on my website. I have a Topic model and a Django custom TopicForm that looks like this: class TopicForm(ModelForm): class Meta: model = Topic exclude = ['creator', 'category', 'pinned'] widgets = { 'title': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Name' }), } labels = { 'title': 'Title', # 'content': 'Content', } On the website, my form looks like this: I saw that I'm able to stylize my inputs very easy (not as easy as in HTML raw forms but still works). The problem is, I'm not able to properly stylize my CKEditor. I'm using two Bootstrap css files: one for the dark theme and one for the light theme. They are imported based on a session variable (the user chooses the preferred theme). What I want to do is to assign the Bootstrap class form-control to the CKEditor, so it can be either dark/light, depending on the user's active theme. Unfortunately, I didn't find any ways to do this, neither on Stack or on other sources. Do you have any idea on how I can implement this? -
different http requests in one django view class
i wrote an API with 4 HTTP requests(PUT,POST,GET,DELETE).I need to assign them in the urls.py file but I don't know how to assign them. now it works but instead of having 4 functions URLs in swagger, I have 16. how can I fix it?(except the separation the functions) path( "responsible-person/list/", CourseAPI.as_view(), name="course-list", ), path( "course/<int:pk>/delete/", CourseAPI.as_view(), name="delete-course", ), path( "course/<int:pk>/edit/", CourseAPI.as_view(), name="update-course", ), path( "course/add/", CourseAPI.as_view(), name="add-course", ), -
How can i customize the message django version 4.0
I want to getrid from that hello from example.com and thanks for using example.com instade of i want to show the real site name in the live server but cannot understand where is that site name is i tried to change the base message with the site name given manually but won't working > Hello from example.com! You are receiving this e-mail because you or someone else has requested a password for your user account. with email 123efghid@gmail.com. in our database. This mail can be safely ignored if you did not request a password reset. If it was you, you can sign up for an account using the link below. https://www.example.com/accounts/signup/ Thank you for using example.com! example.com -
The html page template still leaving some white spaces on the right and below
base.html <body style="margin:0;"> {% include "navbar.html" %} {% if messages %} {% for message in messages %} <div class="container-fluid p-0"> <div class="alert alert-{{ message.tags }} alert-dismissible" role="alert" > <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="True">&times;</span> </button> {{ message }} </div> </div> {% endfor %} {% endif %} {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> </body> index.html {% extends "base.html" %} {% load static %} {% block content %} <div class="container-fluid" style="position:relative;margin:0;"> <img src="{% static 'images/bg_delivery.png' %}" style="margin-left:-15px;margin-right:-15px;width:100%;"> <div style="position:absolute;top:50px;left:200px;font-family:Times, 'Times New Roman', Georgia, serif;font-size:20pt;"> 從你最喜愛的餐廳、商店訂購美食及生活百貨,並由我們為你直送府上! </div> <div style="padding:10px;position:absolute;top:250px;left:450px;display:inline;text-align:left;border: 5px solid gray;"> <input style="border-radius: 10px;box-sizing:border-box;width: 300px;height:50px;" type="text" name="favorite" size="50" placeholder="您的地址"> <button style="width: 50px;height:50px;" class="btn btn-primary"><i class="fa fa-search"></i></button> <button style="width: 150px;height:50px;" class="btn btn-secondary">送遞</button> 或 <button style="width: 150px;height:50px;" class="btn btn-secondary">外賣自取</button> </div> <div style="position:absolute;bottom:350px;right:200px;font-family:Times, 'Times New Roman', Georgia, serif;font-size:20pt;"> 你只需下單,其他的就交給我們! </div> </div> {% endblock %} The HTML page still leaving some excess spaces on the right and below of the background picture in index.html even though I had added the styles like margin: 0 and class:container-fluid. As I am working in Django project and I extends the base.html in index.html so any ways to eliminate the excess white spaces in the HTML … -
Django abstract user extension
using django abstract user i ran makemigrations and migrate then tried to access my admin it is showin no such table app_user error I deleted all my migrations except init -
No such file or directory Django admin panel
I run this command but I face this. I have created manage.py but it still does not work python manage.py createsuperuser python: can't open file 'C:\\Windows\\system32\\manage.py': [Errno 2] No such file or directory -
How to post form data in drf
class Centers(models.Model): users = models.ManyToManyField("authentication.User", related_name="center_users",blank=True, verbose_name="Center Executives" ) ratelist = models.ManyToManyField(RateList, related_name="center_ratelist",blank=True, verbose_name="Center Ratelist") users and ratelist are coming from form data. It is easy to post users=[1,2], ratelist = [2,3]. But if it is coming in string. How to accept and post that data. -
Establishing Connection between Sql Server 2012 and django
I am trying to connect Sql Server 2012 with django version . I am always getting error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' database configurations are 'default': { 'ENGINE': 'mssql', 'NAME': 'Database Name', 'HOST': 'Host Address', 'USER': 'User', 'PASSWORD': 'PtDWdT45$7', 'PORT': '41433', # 'Trusted_Connections': True, "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server"}, # 'OPTIONS': { # 'provider': 'SQLOLEDB', # 'use_legacy_date_fields': 'True' # }, } } -
How to relate two models (send json) to backend | DjangoRest | ReactJS
The question might not be clear from the title. I want to relate two models. I have created the backend and everything is working fine on the frontend (React) and backend (Django) but I want to connect two models Tags and Startups. I am creating the Startup and I want to relate tags that are already created to the startup. I do not understand how can I acheive that. I can do this using django admin. My admin view of creating a startup looks like this - I can relate tags using the list you see in the Tags: field. I want the same layout in the frontend to relate my models. I have created this - I have all my tags in the dropdown list shown in the picture. I am sending this data object to my DjangoRest Api - { "name": "NameS", "description": "DescS", "contact": "contact@gmail.com", "tags": [ { "name": "First Tag" }, { "name": "Third Tag" } ] } This is creating a new startup but without any related tags - Here is my startup api view - I want to acheive the task my django admin is doing using react. -
Left Join in Django
I have the following models: class Patient(models.Model): patient_first_name = models.CharField(max_length=50) patient_last_name = models.CharField(max_length=50) patient_name = models.CharField(max_length=100) patient_email = models.EmailField(max_length=100) gender = models.CharField(max_length=50) class PatientMedicalRecord(models.Model): patient = models.ForeignKey(PatientTable) mrn = models.CharField(max_length=50, unique=True) patient_height = models.IntegerField(blank=True, null=True) patient_weight = models.IntegerField(blank=True, null=True) age_risk = models.BooleanField(default=False) I want to query on patient table for getting all the patient. also i need MRN column value from PatientMedicalRecord table which contain record for particular patient if exists. How can i do this with djnago ORM? -
Django Queryset annotate based on unique value
I am trying to write a queryset operation that transforms the first table into the second table as efficiently as possible This is the criteria: For each name, how many unique schools are affiliated with it? Also, the exact names and schools are unknown beforehand. Name School John USC John USC John UCLA Adam UCSD Adam USC Name num_unique_schools John 2 Adam 2 -
rename the get_field_display in django serializer
i am trying to use the get_field_display function in Django in my serializer but I want to rename it to something else(consider it worker_role). what should I do? class AdminUnsubscriberListSerializer(serializers.ModelSerializer): worker_role= "get_role_display" . . . -
Why doesn't my html file get my javascript file. load static
here is my settings.py: STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIR = [STATIC_DIR] here is the end of my html page: {% load static %} <script src="{% static '/js/script.js' %}" type="text/javascript"></script> </html> {% endblock %} I have a folder static and inside it, there are two more folders one is js and the other is css. But when I try to load it, it always says "GET /static/js/script.js HTTP/1.1" 404 1795 I have tried many things but it does not work. Someone please help. -
loop or any other function in django for below mentioned project
Models: class ddlname(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField(default='00:00') endate=models.DateField() status=models.ForeignKey(status,on_delete=models.CASCADE,default='Yet To Assign') def __str__(self): return self.name Forms: from dataclasses import fields from django import forms from .models import ddlname class nameform(forms.ModelForm): class Meta: model=ddlname fields='__all__' Views: def home(request): if request.method=='GET': form=nameform() return render(request,'home.html',{'form':form}) else: form=nameform(request.POST) if form.is_valid(): form.save() return redirect('/details') def details(request): context={'details':ddlname.objects.all().order_by('stdate','sttime')} return render(request,'details.html',context) home template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="#" method="post"> {% csrf_token %} {{form}} <button type="submit">submit</button> </form> </body> </html> details template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <table> <thead> <tr> <td>Name</td> <td>St Date</td> <td>St Time</td> <td>Status</td> </tr> </thead> <tbody> {% for d in details %} <tr> <td>{{d.name}}</td> <td>{{d.stdate}}</td> <td>{{d.sttime}}</td> <td>{{d.endate}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> Requirement: from home template form, I will input stdate as 22-02-2022 and endate as 25-02-2022 along with name(test) sttime(00:00). I should get the output as: test 22-02-2022 00:00 22-02-2022, test 23-02-2022 00:00 23-02-2022, test 24-02-2022 00:00 24-02-2022, test 25-02-2022 00:00 25-02-2022, and get save to DB. The above mentioned code gives the output as test 22-02-2022 00:00 25-02-2022, request anyone to help me on this issues …