Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MYSQL equivalent query in Django Average and Group By
Please help me to write the same query in Django using ORM SELECT DATE(`created_at`) DateOnly, AVG(`amout`) AS val_1 FROM `account` GROUP BY DateOnly -
How to change div data-src to image_tag in django?
I need this expression but using static tag otherwise the images are not being displayed in project. I tried something like this. but it is not working for div tag. I can't find anything on google.. thankyou. -
import name patterns issue with django
After digging I cannot manage to understand what happened with our server. I got this error when loading the web. It was working and anyone touch anything. I have changed the ownership of the application.txt because this error. [Wed Dec 16 04:38:12.059839 2020] [wsgi:error] [pid 12343:tid 140072894818048] [remote xx.xx.xxx.xx:xxxxx] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/opt/yhmp-app/YHMP/eamena/logs/application.txt' After this it is showing up the next error in the browser: and all this is coming form the error.log when trying to access: ed Dec 16 13:05:46.856703 2020] [authz_core:debug] [pid 14049:tid 140483607127808] mod_authz_core.c(809): [client] AH01626: authorization result of Require all granted: granted [Wed Dec 16 13:05:46.856746 2020] [authz_core:debug] [pid 14049:tid 140483607127808] mod_authz_core.c(809): [client ] AH01626: authorization result of <RequireAny>: granted [Wed Dec 16 13:05:46.856782 2020] [authz_core:debug] [pid 14049:tid 140483607127808] mod_authz_core.c(809): [client :56384] AH01626: authorization result of Require all granted: granted [Wed Dec 16 13:05:46.856787 2020] [authz_core:debug] [pid 14049:tid 140483607127808] mod_authz_core.c(809): [client :56384] AH01626: authorization result of <RequireAny>: granted [Wed Dec 16 07:05:46.857793 2020] [wsgi:error] [pid 14047:tid 140483690739456] Internal Server Error: / [Wed Dec 16 07:05:46.857809 2020] [wsgi:error] [pid 14047:tid 140483690739456] Traceback (most recent call last): [Wed Dec 16 07:05:46.857814 2020] [wsgi:error] [pid 14047:tid 140483690739456] File "/opt/yhmp-app/env/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in … -
Django won't migrate because one model used to be a subclass
I'm using Django 3.0.4 with MySQL 5.7 on Ubuntu 18.04. I have a model Apples. I created a second model BadApples as a subclass of it: # models.py class Apples(models.Model): # fields class BadApples(Apples): pass I ran the migration, which completed successfully. Then, I decided that the 'subclass' approach wasn't working and that BadApples should be its own model. I rewrote the models like this: # models.py class Apples(models.Model): # fields class BadApples(models.Model): # fields When I tried to run the migration, I ran into the following error: MySQLdb._exceptions.OperationalError: (1090, "You can't delete all columns with ALTER TABLE; use DROP TABLE instead") As best I can tell, migrating BadApples from one form to the other involves changing all of its columns. Instead of dropping the table and recreating it, Django uses ALTER TABLE commands only, which throws the MySQL error when it attempts to remove the last column of the original BadApples. This seems related to this bug, purportedly fixed over two years ago, but evidently not fully. To work around this bug, my idea was to remove BadApples from models.py and all references to BadApples from the rest of the code (in this case, views.py and admin.py). Then I'd … -
Get top n records for each group with Django queryset
I have a model like the following Table, create table `mytable` ( `person` varchar(10), `groupname` int, `age` int ); And I want to get the 2 oldest people from each group. The original SQL question and answers are here StackOverflow and One of the solutions that work is SELECT person, groupname, age FROM ( SELECT person, groupname, age, @rn := IF(@prev = groupname, @rn + 1, 1) AS rn, @prev := groupname FROM mytable JOIN (SELECT @prev := NULL, @rn := 0) AS vars ORDER BY groupname, age DESC, person ) AS T1 WHERE rn <= 2 You can check the SQL output here as well SQLFIDLE I just want to know how can I implement this query in Django's views as queryset. -
Scheduling API: This involves a single endpoint, which accepts Date-Time and a URL as a parameter
When the API is called, a task will be scheduled. A GET request (no parameters needed) should be sent on the URL specified (second parameter), when the current Date-Time matches the one specified in the Date-Time parameter (first parameter). The GETrequest on the URL parameter will only return a status code, and no response body please tell me this what i have to do in this task. -
validate django formsets single felid
I need to validate if the start year is less than the end year using the form clean function but it is not working in Django this is the formset formset ExperienceModelFormFormset = inlineformset_factory( PersonalInfo,Experience, fields = ('Company', 'Position', 'YearofExp','Start', 'End'), extra=0, min_num= 1, validate_min=True, widgets = { 'Company': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'company Name', 'required':'False', 'oninput':'process(this)', 'onKeyPress':'return ValidateAlpha(event)', } ), 'Position': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Position', 'oninput':'process(this)', 'required':'False', } ), 'YearofExp': forms.Select( attrs={ 'class': 'form-control', 'placeholder': 'Year of experiance', 'required':'False', } ), 'Start': forms.DateInput( attrs={ 'class': 'form-control', 'placeholder': 'Your email', 'type': 'DATE', 'required':'False', } ), 'End': forms.DateInput( attrs={ 'class': 'form-control', 'placeholder': 'DATE', 'type': 'date', 'required':'False', } ), } ) ) -
How to disable users from admin panel and django?
I know they provide add, update, delete and view. But I want the users' data to not get deleted and disable user so they cannot use website until enabled again. -
Why my command prompt inside of my visual studio code is not working
I'm recently learning django, and I learned that I need to use pipenv to not install django globally. So I firstly installed pipenv, and I made a cmd(command prompt) inside of my visual studio code(I'm working in visual studio code and I'm windows user). When I hit pipenv --three at cmd inside of the vscode to make a virtual environment, and cmd inside of the vscode said command not found. In contrast, when I hit pipenv --three at cmd outside of the vscode, it seemed it worked properly. Why is it happening? Also, I hit pipenv shell and installed django, but when I hit django-admin to check if django installed properly, it also didn't work like pipenv --three command hit inside of the vscode cmd. Ask me if you didn't understand my situation, and thanks in advance! -
django forms make error appear beside field
At my forms.py I have the following form where I want to check the input of the user against a trx_id at my database, the problem now is that the validation error does not get displayed beside the field, instead it always appears on top of the form, please see below: class TicketForm(forms.ModelForm): ... self.fields['trx_id'].label = mark_safe('Transaction ID (Optional):') def clean(self): form_trx_id = self.cleaned_data.get('trx_id') trx_id = Transaction.objects.filter(trx_id=form_trx_id).exists() if form_trx_id: if not trx_id: raise forms.ValidationError( self.error_messages['trx_id_mismatch'], code='trx_id_mismatch', ) How can I make the validation error appaer beside the field? -
How can I set a Django model property to always be returned?
I have a User model which inherits from the Abstract User Model from django.contrib.auth. For minimal example this could be it: class User(AbstractUser): middle_name = models.CharField(max_length=150, blank=True, null=True) title = models.CharField(max_length=150, blank=True, null=True) @property def full_name(self): full = '' if self.title: full += self.title + ' ' if self.first_name: full += self.first_name + ' ' if self.middle_name: full += self.middle_name + ' ' if self.last_name: full += self.last_name + ' ' return full.strip() When creating a user serialiser with the ModelSerializer like this class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' the full_name property doesn't show up. I could solve this by explicitly adding the field via a SerializerMethodField but as we have a a lot of different serialisers for the user and abstract models above, I would like to always have it returned as if it was a field. Do I need to add a field to the model? Or is there a way I didn't see yet? -
Error trying to switch between different charts
I am developing an application which shows the data created in a chartjs graph, what I am doing it does well, since all the data is displayed in the way I want, but I have a problem and that is that now I am trying to do that according to the type of graph that a user wants this to be changed, the problem is that the graph is changed but in case of having multiple graphs only the first graph is changed, the others continue with the graph by default, this is my template: <select name="chartType" id="chartType" onchange="updateChart()" data-role="select"> <option value="pie">pie</option> <option value="bar">Bar</option> </select> <canvas id="{{ project.slug }}" width="400" height="400"></canvas> This is my script: var faltante = 100 - {{ project.porcent }}; var data = { labels: ['{{ project.name }}', 'Falta'], datasets: [{ data: [{{ project.porcent }}, faltante], backgroundColor: ['#252850', '#f44611'] }], }; var ctx = document.getElementById('{{ project.slug }}').getContext('2d'); var myChart = new Chart(ctx, { type: 'pie', data: data }); function updateChart() { myChart.destroy(); myChart = new Chart(ctx, { type: document.getElementById("chartType").value, data: data }); } -
Capturing oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error when user is not assigned to a role for the application
I have a Django app running via Gunicorn and an Nginx proxy that uses Azure AD authentication (based on the following tutorial: https://docs.microsoft.com/en-us/graph/tutorials/python?tutorial-step=3). At the moment when a user logs in to the app via Azure AD and isn't assigned to a role, Django shows a generic 500 error page. I want to display something a little more meaningful to the user, but I don't know where exactly I need to capture the oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error and display it. I can see the Django logs show: "oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error (interaction_required) AADSTS50105: The signed in user '{EmailHidden}' is not assigned to a role for the application '[App ID]'(App Name).” Would it be within the callback view that I have to check for this error somehow? I was rather hoping Azure would show the error message by default, but that doesn't seem to the case. -
How to filter the items through Django models
I want to get the total number of tables own by each users on my application. using Tables.objects.all().count returns all total number of tables but I will like to get the number of tables own by each user. models.py class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=30, blank=True, null=True) class Bar(models.Model): user_id = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Tables(models.Model): table_no = models.CharField(max_length=14, unique=False) bar = models.ForeignKey(to=Bar, on_delete=models.CASCADE) -
Group data by month, if the month is in a date range of two fields in Django
I have a contract model containing a start and end datetime field. I want to show in a graph how many contracts are active per month (the month is between start and end time). How can I get this information without multiple database requests per month? -
Django admin view bugs
I got some weird bugs going on my admin view, For example I click users: And this what I get (The user results in the same page, not a separate page like a casual admin view): the rows also starched out for some reason. Any ideas what can cause this? -
python api verified number usinf firebase
I will create python api using Django now I trying to verify phone number using firebase authentication end send SMS to user but I don't know how I will do -
Django models: default datetime is not translated into SQL CURRENT_TIMESTAMP
I am using Django models to create a PostgreSQL-DB. I have a DateTimeField where I would like to set the current timestamp as default value. I am aware of multiple sources suggesting how to do this. However, when I inspect my DB outside of Django, the default timestamp doesn't show up. Approaches I have tried: 1. created_at = models.DateTimeField(auto_now_add=True) from django.db.models.functions import Now ... created_at = models.DateTimeField(default=Now()) from django.utils.timezone import now ... created_at = models.DateTimeField(default=now) What I would expect is for the PostgreSQL database to show: TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP What It shows is timestamp with time zone not null but no default value. Any ideas on how to do that would be greatly appreciated. -
Input DateTime picker on inlineformset_factory on Django
Hi I am planning to use date time picker with the use of inlineformset_factory. But I don't know what to do. -
Remove .xls extension on excel file created with xlsxwriter on django
I wrote a really simple django project to test xlsxwriter. I can open the excel file, but when I name the file 'filename.xlsx', the file is downloaded as 'filename.xlsx.xls'. How can I fix this? from django.shortcuts import render from django.http import HttpResponse from .excel import get_excel def home_view(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=filename.xlsx' excel_data = get_excel() response.write(excel_data) return response -
Why is the border-left border-right not working for Bootstrap 5 Django?
So I have the following code: {% load static %} <!DOCTYPE html> <html> <head> <title>Verification Code Email</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <style> .insta-icon{width:50%; float:right;} </style> </head> <body> <div class="container"> <div class="row"> <div class="col-1 offset-1 border-right"> # This one right here <img class="insta-icon"src="{% static '/images/instagram_icon.png' %}"> </div> <div class="col-10"> b</div> </div> </div> <div class="container"> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> </body> </html> Now when I do just border, the border is shown, and when I do border-bottom or border-top, the borders are shown. However, when I use border-left or border-right, the border outlines aren't shown. Also, I tried using a styles by adding an insta-nav class to the div class and override the styles by adding border:1px, but the border isn't added. Why would the reasons for these two be so?? Any help would be appreciated -
Merging Django querysets of differing sizes causing date missmatch in graph view with date value
I've got 2 querysets, each filtertering by transactionType over the same date range, only problem is, the queryset are returning differnet sizes as some of the dates dont match with the applied filter, so instead of it returning 0 it returns 'empty' ( or so i believe ) current_date = datetime.today() months_ago = 6 six_month_previous_date = current_date - timedelta(days=(months_ago * 365 / 12)) aggregatedSales = Transactionlog.objects.using('database').filter(transactiondate__gte=six_month_previous_date).filter( transactiontype=1).values('transactiondate').annotate(sales_by_month=Count('transactiondate')) aggregatedRefunds = Transactionlog.objects.using('database').filter( transactiondate__gte=six_month_previous_date).exclude(transactiontype=1).values('transactiondate').annotate( ref_by_month=Count('transactiondate')) transaction_Values_list = list(chain(aggregatedRefunds, aggregatedSales )) transaction_Values_rules = defaultdict(dict) for dic in transaction_Values_list: transaction_Values_rules[dic['transactiondate']].update(dic) My Issue being that when these 2 querysets are diplayed in a graph the differing length cause a miss match in the dates - im using Chart.js to render the charts on my template using the follwing - (function ($) { $(document).ready(function(){ var fixedLineChart = $('#fixed-line-chart'); var fixedLineChartJS = new Chart(fixedLineChart, { type: 'line', data: { labels: [{% for dates in aggregated %}'{{ dates.transactiondate|date:'Y-m-d H:i:s' }}',{% endfor %}], datasets: [{ label: 'Sales', data: [{% for sales in aggregated %}'{{ sales.sales_by_month }},{% endfor %}], borderColor: chartColorGreen, backgroundColor: rgbToRgba(chartColorGreen, '.25'), pointBackgroundColor: chartColorGreen, pointBorderColor: rgbToRgba(chartColorGreen, '.25'), lineTension: 0, fill: 'origin', },{ label: 'Refunds', data: [{% for ref in aggregated %}'{{ ref.ref_by_month }},{% endfor %}], borderColor: chartColorPink, backgroundColor: rgbToRgba(chartColorPink, … -
How do i make Django accept my date formats
How can i make my model date field accept the 'dd/mm/yyyy' date format? I have seen the solutions using django forms but i am not using django forms. Please help. -
VerificationSMSCode() got an unexpected keyword argument 'phone'
Hello everyone! I'm working on a big project with Django Rest and I'm totally stuck with this one. The project is something like Social network and I don't know why but everything seems to be correct, but every time I do "POST" method in the browser while debugging I see this error. I can provide you more information if you need it. urls.py from rest_framework import routers from auth2.api.views import SendCodeView, VerifyCodeView router = routers.DefaultRouter() urlpatterns = [] router.register(r'code_send', SendCodeView, basename='code_send') urlpatterns += router.urls views.py from django.contrib.auth import get_user_model from django.utils import timezone from rest_framework.authentication import get_authorization_header from rest_framework import generics, status, views from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from auth2.api.serializers import SendCodeSerializer, VerifyCodeSerializer from auth2.models import VerificationSMSCode from core.api.serializers import UserSerializer User = get_user_model() logger = logging.getLogger('logzio') class SendCodeView(ModelViewSet): queryset = VerificationSMSCode.objects.all() serializer_class = SendCodeSerializer permission_classes = (AllowAny, ) def post(self, request, **kwargs): print('DEBUG ' + request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) logger.info(f'send code log', extra=request.data) VerificationSMSCode.create(serializer.user) return Response(status=status.HTTP_204_NO_CONTENT) models.py from django.db import models from django.utils.translation import gettext_lazy as _ from auth2.utils import get_random_code from core.models import User class VerificationSMSCode(models.Model): STATUS_PENDING = 'pending' STATUS_DELIVERED = 'delivered' STATUS_ON_THE_WAY = 'on_the_way' user = models.ForeignKey('core.User', related_name='verification_sms_codes', … -
How to Combine Django Dynamic PDF Template view along with a PDF File as an attachment in the pdf
I am using Django 3.0 and in my two function the first one will generate the bill dynamically rendering an object into an HTML page and the other function will just response with a FileResponse. I am trying to combine trying to these two PDF's into one PDF in the view function that will responses with both the PDF Bill Template and the attachment. def MyPDF(request, id): bill = get_object_or_404(bill, id=id) response = HttpResponse(content_type="application/pdf") response['Content-Disposition'] = "inline; filename={name}.pdf".format(name=slugify(bill.title).upper()) html = render_to_string("PDFBill.html", {'object': bill, }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response def BillAttachment(request, id ): object = get_object_or_404(bill, id=id) response = HttpResponse(content_type="application/pdf") response.content = object.file.read() response["Content-Disposition"] = "inline; filename={0}.pdf".format(object.title) return response