Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to fetch the column names(field names) along with the values in raw sql query
views.py def view(request): cursor = connection.cursor() with open('D:\Project-Management-Tools\Project-Management-Tools\query.sql','r') as inserts: query = inserts.read() cursor.execute(query) row = cursor.fetchall() return Response(row) I have tried a raw query by inserting a sql file in cursor function. However I am getting the values alone as a response and I need to get the fields name along with the values in the response. Kindly help me to solve this issue. -
update key of specific dict in dict of dicts
I'm creating a dictionary of dictionaries and then trying to update a specific key using for loop. however, all keys are getting updated. code is as follows: transactions = Transaction.objects.all() unique_sellers = ['A002638841D', 'A09876543456'] seller_summary={} summary = { 'total_loan_amount': 0, 'gross_incentive': 0, } for each in unique_sellers: seller_summary[each] = summary seller_summary[each]['total_loan_amount'] = transactions.filter(channel_seller__pin_no = each).aggregate(total_loan_amount=Sum('loan_amount'))['total_loan_amount'] print(seller_summary) total_loan_amount for A002638841D is 1500 total_loan_amount for A09876543456 is 2000 my expectations is output of print(seller_summary) should be {'A002638841D': {'total_loan_amount': 1500, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}} However, I'm getting output as follows my expectations is output of {'A002638841D': {'total_loan_amount': 2000, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}} total_loan_amount is both the dict is getting updated as 2000 instead of 1500 and 2000 respectively -
Failed to import a model into a view DJANGO
Newbie to Django here. I am trying to import a model into views to use it. However I am facing problems doing so. First of all, here is the structure of my folder : project structure webpage folder structure When I try to import one of my models into views with: from .models import model_i_want I get : ImportError: attempted relative import with no known parent package if I try from webpage.models import model_i_want I get : ModuleNotFoundError: No module named 'webpage' if I try to import models like this import .models I get this error setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My webapp is added in the settings, and everything was running smoothly while following the Django official tutorial. I know I should be reading the documentation and figure it out but I can't seem to understand all of it yet and I am still trying to get used to Django. Thank you and have a nice day! -
how to convert date format in __range look up - django
I'm trying to search between two dates using __range but it expects to write hours during the search and raise this error : ['“2022-02-22data” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] here is my models field created_at = models.DateTimeField(auto_now_add=True) and here is my views.py def my_views(request): start = request.GET.get('from') end = request.GET.get('to') if start and end: total_price = MyModel.objects.filter(created_at__range=(start,end)) else: total_price = MyModel.objects.all() <form action="" method="GET"> <div class="col-12 p-1 mt-1 mx-auto text-center text-light pInside row"> <p class="col-12 col-sm-6 mx-auto text-left row"> from <input type="date" class="form-control col-9 mr-1" name="from" id="from"> </p> <p class="col-12 col-sm-6 mx-auto text-right row"> to <input type="date" name="to" class="form-control col-9 mr-1" id="to"> </p> <button class="btn btn-success col-8 col-sm-5 col-md-3 mx-auto">search</button> </div> </form> i dont want to force the database to only get year, month and day, i have to change the created_at to strftime("%Y-%m-%d") in the filter, but i dont know how to achieve that?! thank you in advance .. -
while creating pdf for repaortlab layout error
raise LayoutError(ident) reportlab.platypus.doctemplate.LayoutError: Flowable <Table@0x7FA13491B898 1 rows x 1 cols(tallest row 900)> with cell(0,0) containing '<Table@0x7FA1349110B8 1 rows x 1 cols(tallest row 894)> with cell(0,0) containing\n'<Table@0x7FA1349894E0 1 rows x 1 cols(tallest row 24)> with cell(0,0) containing\n"<Table@0x7FA134989438 1 rows x 1 cols(tallest row 18)> with cell(0,0) containing\\n\'Vulnerability ( Virustotal Domain Report )\'"''(583.2755905511812 x 900), tallest cell 900.0 points, too large on page 6 in frame 'normal'(583.2755905511812 x 794.8897637795277*) of template 'Later' I make a PDF(A4) size for it and got the error, while Ienter code here make A3 for it the problem is solved, i want the solution for A4 size. if type(data) == dict: all_table = [] for key, value in data.items() : temp = [] temp_table = [] temp.append(key) tool_table_header = Table([temp],colWidths='*') tool_table_header.setStyle(tools_table_header_Style) temp_table.append(tool_table_header) if key != 'Builtwith': t_h = [] t_b = [] for k,v in value.items(): t_h.append(k) t_b.append(v) t_body = [] for index, item in enumerate(t_h): if item != 'status': arr1 = [] arr2 = [] if type(t_b[index]) is list: temp_txt = '' for txt in t_b[index]: temp_txt += txt + ', ' arr1.append(item + ':') text = t_b[index] wraped_text = "\n".join(wrap(str(temp_txt[:-3]), 60)) # 60 is line width arr1.append(wraped_text) else: **arr2.append(arr1) n_table =Table(arr2,[200,370]) n_table.setStyle(Style4) t_body.append(n_table)** tool_header = … -
Django: How to apply Count on the results of a `distinct` QuerySet?
I have the following models: class Exercise(models.Model): name = models.CharField(max_length=300) class UserWorkout(models.Model): user = models.ForeignKey(User) class WorkoutSet(models.Model): exercise = models.ForeignKey(Exercise) user_workout = models.ForeignKey(UserWorkout, related_name="sets") date_time = models.DateTimeField(default=timezone.now) These are simplified models for a workout app, where a user starts a UserWorkout with a set of Exercise objects, then for each exercise they create a few WorkoutSet objects to record how much weight/time etc. What I want to answer: Given a particular user, how many times each exercise has been performed by the user? I want to count all related WorkoutSet objects in 1 UserWorkout as 1. This is what I have now: # 1. Get all Exercise objects performed by the user using WorkoutSet: qs = Exercise.objects.filter(workoutset__user_workout__user=user) # 2. Select the ID and Name only and annotate with the workout ID qs = qs.values('id', 'name').annotate(workout_id=F('workoutset__user_workout__id')) # 3. Get the distinct of both exercise ID and Workout ID qs = qs.distinct('id', 'workout_id') The query set now has the following (correct) data, which is very close to what I want: In [44]: for x in qs: ...: print(x) ...: {'id': 3, 'workout_id': UUID('755925da-9a43-490c-9ffa-3222acd1dcfa'), 'name': 'Ab Rollout'} {'id': 3, 'workout_id': UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956'), 'name': 'Ab Rollout'} {'id': 3, 'workout_id': UUID('c23c80ea-4408-45d8-bf05-b2d699bee11f'), 'name': 'Ab Rollout'} {'id': 3, … -
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' # }, } }