Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Urlconf does not appear to have any patterns in it
I am getting this error but I cannot figure it out. In views.py I have: ...code... def get_success_url(self): booking = self.object return reverse("complete_booking", booking.id) urls.py: from django.urls import path from . import views urlpatterns = [ path( 'confirm/', views.ConfirmTripView.as_view(), name="confirm_trip"), path( '<pk>/passengers/add', views.InputPassengersView.as_view(), name="create_passengers"), path( '<pk>/checkout/', views.CompleteBookingView.as_view(), name="complete_booking"), ] What confuses me is I have almost identical for the 'create_passengers' view (booking.id passed as argument) and it works fine. The traceback says: Traceback Switch to copy-and-paste view "The included URLconf '{name}' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." patterns 71 self <URLResolver 71 (None:None) '^/'> The above exception ('int' object is not iterable) was the direct cause of the following exception: Could I get some help solving this? -
refresh table without refreshing page using ajax Django
i am using ajax for updating page without refreshing in Django i want to update table but i am not using api in my views.py can i want refresh only the table script $.ajax({ type:'POST',// type of the form data: $('#tableid').serialize(), // all the form name success: function (data) { return data // i don't want all return data i want only table data it should refresh } }); -
ImportError: cannot import name range in Django but working in python shell
I am using Django 1.8.6 with python2.7 In django when I am using the below code, i am getting import error. In [1]: import six In [2]: six.__version__ Out[2]: '1.15.0' In [3]: six.__file__ Out[3]: '/srv/www/python_env/local/lib/python2.7/site-packages/six.pyc' In [4]: from six.moves import range --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-4-91a3b790ef9a> in <module>() ----> 1 from six.moves import range ImportError: cannot import name range In [5]: But When I am running the same code in python shell using same environment it is running successfully. In [1]: import six In [2]: six.__version__ Out[2]: '1.15.0' In [3]: six.__file__ Out[3]: '/srv/www/python_env/local/lib/python2.7/site-packages/six.pyc' In [4]: from six.moves import range In [5]: -
How to handle Multiple Requests from Django App?
I have a requirement, where only one instance of the Django application is supposed to be running on a remote server. The user will make a request to the service and the application will process batch data and return back output. In this particular scenario, I have been asked to handle multiple requests in a queue from inside the Django application which is slightly odd. If I have to move forward with this approach, what would be the best way to implement the queue. Also if there is an option to use some kind of a queue outside the application, what would be the best approach for it? Thanks in advance -
Azure web app deployed to tmp folder instead of wwwroot
I have been deploying my Django Python Web app on Azure App Service for a few hundred times now. Recently, i made a small change in the html file and push it but the deployment went differently. Instead of deploying the app in home/site/wwwroot/, Oryx deployed it to a tmp folder. (See the screenshot) I'm confused over why this happened. I didn't change ANY settings or configuration and my web app ended up in a tmp folder. Anyone knows what happened here and how to fix this? -
django rendering pdf file that is stored in database to the template
how to render pdf file that is stored in the database in the templates Django cv = models.FileField(blank=True, null=True,validators=[validate_file_extension]) docs = models.FileField(blank=True, null=True,validators=[validate_file_extension]) -
Django : initialize database without migrations
Sorry, I'm pretty novice on Django. I have some little notice already, but completly lack of experience. So the questions sound silly, but I could not find it exactly in this general form. So... Let's say, I have some Django project already done by someone. Now I have two situations : I have the latest version of project code. But I have nothing about database : neither database, nor migrations. To give some example, the code was on some Git, but the database and migrations files were on some server and this server is lost. I'd like to understand if I could still initialize the project from zero ? Get the new server with empty database. I clone git code of project. Launch manage.py makemigrations manage.py migrate and I'll get new database initialized by our models files ? Is it correct ? Are there some pitfalls about it ? the second situation is similar, but not exactly. Now I have some database-dump and also some migrations. But probably not all them. So I do not know how much my code is different from dump and migrations. I saw already the questions about similar situations. It seems that globally the solution …