Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is request available inside django to_representation serializer method?
I am trying to perform a request check inside the to_representation serializer method in django but the self.context is always empty. Any ideas why? class TwitterAccountsListsSerializer(serializers.ModelSerializer): class Meta: model = TwitterAccountsList fields = ["id", "name", "created_at", "is_private", "accounts"] extra_kwargs = { "accounts": {"write_only": True}, } def to_representation(self, instance): import pdb; pdb.set_trace() # self.context is always an empty dict here {} return super().to_representation(instance) -
How to uninstall apscheduler from Django project?
I have apscheduler configured with a single task in a Django project. The task was just to test apscheduler capabilities. Now I need to uninstall it completely. How do I do that? I guess pip uninstall apscheduler is not enough? -
Need Help in adding an email notification in Django
I am trying a timesheet project. I am using Django rest-framework and using Postgres as my database. My client requested me this ( If a user already existed in the database or a new user is creating their account an email should be triggered when the post option was submitted in rest API ). Below I'll include my codes models.py from django.http import HttpResponse, HttpResponseRedirect, response from django.db import models from django.db.models.deletion import CASCADE from django.utils import timezone from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from django.core.mail import send_mail from django.db.models import signals import datetime from django.core.mail import EmailMessage class User(models.Model): CHOICES= ( ('manager','Manager'), ('hr', 'HR'), ('hr manager','HR Manager'), ('trainee','Trainee') ) firstname = models.CharField(max_length=210) lastname = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) password=models.CharField(max_length=100,default=None) joiningDate=models.DateTimeField(max_length=8) userrole=models.CharField(max_length=20,choices=CHOICES,null=True) def __str__(self): return self.firstname class Project(models.Model): name = models.CharField(max_length=20) description=models.TextField() type=models.TextField() startDate = models.DateTimeField(max_length=10) endDate=models.DateTimeField(max_length=10) user=models.ManyToManyField(User) def __str__(self): return self.name class Timesheet(models.Model): project=models.ManyToManyField(Project) Submitted_by=models.ForeignKey(default=None,related_name="SubmittedBy",to='User',on_delete=models.CASCADE) status=models.CharField(max_length=200) ApprovedBy=models.ForeignKey(default=None,related_name="ApprovedBy",to='User',on_delete=models.CASCADE) Date=models.DateField() Hours=models.TimeField(null=True) def __str__(self): return self.id class Client(models.Model): clientname=models.CharField(max_length=20) comapny=models.CharField(max_length=200) location=models.CharField(max_length=200) email=models.EmailField(max_length=25,default=None) def __str__(self): return self.clientname serializers.py from django.db.models import fields from rest_framework import serializers from.models import User,Project,Timesheet,Client class UserSerializers(serializers.ModelSerializer): class Meta: model= User fields ='__all__' password = serializers.CharField(max_length=128, write_only=True, required=True) class ProjectSerializers(serializers.ModelSerializer): class Meta: model= Project … -
Django-JqueryUI Date Picker remove specific Dates which is passed as Django context
I have a django project which passes dates as dictionary to my template,Previuosly i used select to pick date but that doesnt look good and I decided to replace it with a datepicker which has dates only present in that disctionary.I tried several ways but could not wrap around it.Please help html: <div id="datepicker"></div> script: $(function() { $( "#datepicker" ).datepicker(); }); views.py: available_dates={'2022-01-25': 'Tue', '2022-01-26': 'Wed', '2022-01-27': 'Thu'} return render(request,'datepicker.html',{'dates':availabe_dates}) And I was using ajax with my select to retrive my data back to backend: <select onchange="return sendData(this.value)" and here's my ajax code: function sendData(date){ $.ajax({ type : "POST", url: "", data: { date : date, csrfmiddlewaretoken:'{{ csrf_token }}', }, And now i want to replace select with datePicker with all this functialities,But i dont know how to begin,So please Help -
Unable to dockerize django
I am new to Docker, I have tried several video samples on youtube, yet I am unable to dockerize django app using anaconda Here is my Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app Here is docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 Here is requirements.txt asgiref 3.4.1 pyhd3eb1b0_0 ca-certificates 2021.10.26 haa95532_2 certifi 2021.10.8 py39haa95532_2 django 3.2.5 pyhd3eb1b0_0 krb5 1.19.2 h5b6d351_0 libpq 12.9 hb652d5d_1 openssl 1.1.1m h2bbff1b_0 pip 21.3.1 pypi_0 pypi psycopg2 2.8.6 py39hcd4344a_1 python 3.9.7 h6244533_1 pytz 2021.3 pyhd3eb1b0_0 setuptools 58.0.4 py39haa95532_0 sqlite 3.37.0 h2bbff1b_0 sqlparse 0.4.1 py_0 typing_extensions 3.10.0.2 pyh06a4308_0 tzdata 2021e hda174b7_0 vc 14.2 h21ff451_1 vs2015_runtime 14.27.29016 h5e58377_2 wheel 0.37.1 pyhd3eb1b0_0 wincertstore 0.2 py39haa95532_2 zlib 1.2.11 h8cc25b3_4 After running "docker-compose build" I get this error message => ERROR [5/6] RUN pip install -r requirements.txt 3.1s ------ > [5/6] RUN pip install -r requirements.txt: #10 2.240 ERROR: Invalid requirement: 'asgiref 3.4.1 pyhd3eb1b0_0' (from line 4 of requirements.txt) #10 2.933 WARNING: You are using pip version 21.2.4; however, version 21.3.1 is available. #10 2.933 You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command. … -
Django template is not deleting the record correctly
This is my template code <tbody> {% for item in items %} <tr class="text-black"> <td>{{ item.name }}</td> <td>{{ item.description }}</td> <td> <a href="{% url 'menu-options-update' item.id %}" class="btn btn-sm btn-user edit" > <!-- <i class="far fa-edit"></i> --> <i class="fas fa-pencil-alt"></i ></a> <a data-toggle="modal" class="btn btn-sm btn-user delete btn--show-modal" href="#myModal" data-confirm="Are you sure to delete this item?" ><i class="fas fa-trash"></i ></a> </td> <div class="modal1 hidden"> <button class="btn--close-modal">&times;</button> <h2 class="modal__header">Do you want to delete this record?</h2> <div class="deletModalBtnContainer"> <a href="{% url 'menu-options-delete' item.id %}" class="delete-final btn" >Delete</a > <a href="#" class="cencel-modal btn btn-cancels-close-modal" >Cencel</a > </div> </div> </tr> {% endfor %} </tbody> And this is my view item = MenuOptions.objects.get(id=id) item.delete() This code is always picking the 1st id in the table data, not the one on which I have clicked. Let's suppose my table has 5 rows and I want to delete the 4th row but after I click on the delete button it is deleting the 1st row. -
In stripe checkout page display Country or region fields how to remove it
image I am used stripe payment getaway for payment, In stripe checkout page display Country or region field and some country select then Postal code field appear both fields are required so how to remove this fields. Here is my code: checkout_session = stripe.checkout.Session.create( line_items=[ { "price_data": { "currency": "usd", "product_data": { "name": "order", }, "unit_amount_decimal": 5 * 100, }, "quantity": 1, }, ], customer_email="test@gmail.com", mode="payment", success_url=success_url, cancel_url=cancel_url, -
Pushing to Heroku Failed
I am trying to deploy my app to Heroku for the first time and I am running into the following error when trying to push using git: I've also tried git push heroku HEAD:main and git push heroku master with the same results. Is this a branch issue? What else could drive this? C:\Users\New User\Downloads\django-modal-ajax-crud-main\django-modal-ajax-crud-main>git push heroku main Enumerating objects: 185, done. Counting objects: 100% (185/185), done. Delta compression using up to 4 threads Compressing objects: 100% (169/169), done. Writing objects: 100% (185/185), 72.21 MiB | 1.29 MiB/s, done. Total 185 (delta 33), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Requested runtime ("python-3.8.7") is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: ed5e29f5eae1f6c87fe608824165f38e3146d5af remote: ! remote: ! We have detected that you have triggered a … -
Django, webpack and NPM. Packaging seems to work, but can't access the code
Related questions appear not to be applicable in my case. As I do not understand where the issues lies, perhaps I am just not finding the solution. I have some experience with Django, but this is my first time working with webpack and NPM. My intended behavior is simple. I want to be able include the following JS code in my existing Django project and access/use scene. import * as THREE from 'three'; const scene = new THREE.Scene(); I have never worked with package (file?) managers, but I recognize that the import statement requires some kind of framework, like node or npm. I found a guide that explained how I could integrate Django with Webpack so I could make use of npm. Detailed code is below, but in short: I have a JavaScript file that contains the following code: console.log("Before import.."); import * as THREE from 'three'; const scene = new THREE.Scene(); console.log("After import.."); This file is located within my django static folder. In the Django .html that I am accessing I have included the following code {% load render_bundle from webpack_loader %} {% render_bundle 'main' 'js' 'DEFAULT' %} Here 'DEFAULT' refers to the following in myProject\settings.py: WEBPACK_LOADER = { … -
Django - Using Cast to query if CharField values are gte when not all values are string representations of ints
I have a DataField model in django that I use to store values for various field types. It looks like this: class DataField(models.Model): class FieldTypes(models.TextChoices): TEXT = 'Text', 'Text' QUANTITATIVE = 'Quantitative', 'Quantitative' SELECTION = 'Selection', 'Selection' name = models.CharField(max_length=50) field_type = models.CharField(max_length=150, choices=FieldTypes.choices) value = models.CharField(max_length=150) I want to be able to do a multi-query returning certain DataField types with certain values that are gte a given number, for example: DataField.objects.filter((Q("value__gte"= 1000) & Q(name= 'credit'))| (Q("value"= "Smith") & Q(name='Last Name'))) The problem is that the value field is a CharField, so I can't do gte filters. The field needs to be a CharField because I also store other word string values, like names. I've tried using Cast to create a value_int field for the query, but since not all values for DataField.value can be converted to an int I get a syntax error: queryset = DataField.objects.annotate( value_int=Cast('value', output_field=IntegerField()),).all() django.db.utils.DataError: invalid input syntax for type integer: "Smith" Is there a way I can add some logic to Cast so that if the value is not a valid integer it just goes to null? -
Relation with django
I have a question, I have 2 tables in my project (Customer, Machine) and I want to display the name of the customer in the MACHINE table. I have the relationship but I have not been able to create the Join. Could you help me validating this topic -
How do I import Chart.js Helper Functions in Django?
I am using chart.js with django and am receiving an error because I have not imported the chart.js helper functions getRelativePosition and getValueForPixel initialize:178 Uncaught TypeError: Cannot read properties of undefined (reading 'getValueForPixel') at tn.onClick (initialize:178:56) at tn.handleEvent (Chart.min.js:7:111837) at tn.eventHandler (Chart.min.js:7:111253) at n (Chart.min.js:7:110528) at HTMLCanvasElement.Se.<computed> (Chart.min.js:7:87040) The chart.js documentation says to import with the code below, but I don't believe this can be done in Django import { getRelativePosition } from 'chart.js/helpers'; https://www.chartjs.org/docs/master/getting-started/integration.html -
Python remove shapes from a pdf
In my setup, I have a student submit a pdf, and the teacher can annotate the pdf using the adobe embed api. This really nice since the teacher can create and delete comments. However, take the example case where a student writes their answers on a paper then scans them to a pdf. They then draw on the pdf with a pdf editor like Microsoft edge. after they submit and the teacher is editing, it is possible for the teacher to delete what the student has drawn because the embed API treats it as a shape. I don't want this to be possible. My backend is Django, so maybe there is some way for python to open a pdf file and "flatten" the shapes. Thanks -
Dynamic action URL in Django Template
I have a form in Django and would like to add the correct id at the end of the URL. I am not sure how to add the ID at the end dynamically however. Here's some example code. {% for dealer_payment_account in dealer.dealerpaymentaccount_set.all %} <p>Account: {{ dealer_payment_account.last_4_digits }}</p> <form id="verifyDealerBankAccountForm" action="/verify-dealer-payment-account/{{ dealer_payment_account.id }}" method="POST"> <div class="form-row"> <label>Payment</label> <input type="text" name="amount"> </div> <button type="submit">Submit</button> </form> {% endfor %} Specifically I am wondering how to format this: action="/verify-dealer-payment-account/{{ dealer_payment_account.id }}" so that I can add the dealer_payment_accound.id to the end of each form. -
'django_extensions' 'show_urls' closes within a blink of a second
I use Django extensions as shown here: Django : How can I see a list of urlpatterns? to get a list of exposed urls. I'm on win 10. Cmd.exe opens and closes immediatly. With a highspeed cam i could figure out that whats written in the cmd.exe makes senes. How can I prevent cmd.exe from closing by auto. -
how can i invalidate page cache in django
How can I invalidate page cache in django. I am trying to cache a page displays a list that is unique for each user using django-rest-framework. I can not figure out how to invalidate the page cache when the another object is added, updated, deleted from the model. I am open to using an external package or signals. I don't know what the key is for @page_cache to invalidate the cache I have tried to use django-fancy-cache but I just get an error unsupported operand type(s) for +: 'float' and 'function' my cache settings CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } -
Pushing Django app to Docker Container failing
I've been trying to push my django app to a Docker container but i keep getting the error below and i dont quite understand what it all means. executor failed running [/bin/sh -c bash -c "diff -u0 <(sed -e 's, *#.*,,' -e '/^$/'d /tmp/app/requirements.txt | sort -f) <(pip3 freeze | sort -f)"]: exit code: 1 ERROR: Service 'website' failed to build : Build failed Thanks -
Test case for using ForeignKey in multiple databases in Django
In Django, if I specify the key of another scheme's Model as the ForeignKey, I can usually get the object of the ForeignKey automatically. However, why do I get the following error only in testcase? I can find id, but can't get object. Environment is Django3.0 Postgresql12. django/db/models/query.py", line 417, in get self.model._meta.object_name I tried some solutions. But, I'm still facing the error... from django.test import TestCase TestCase.databases = {'default', 'another_db'} databases = '__all__' multi_db = True -
Preload FK relation in different column Django
I have Django models that looks like this class Customer(models.Model): name = models.CharField(_("Name")) class Feature(models.Model): label = models.CharField(_("Name")) class AddOn(models.Model): customer = models.ForeignKey(Customer) feature = models.ForeignKey(Feature) Given that I have an instance of Customer e.g customer = Customer.objects.get(pk=1) How do I get all the labels in feature in one query to avoid N+1 query? For now what I've done is: [addon.feature.label for addon in self.addon_set.all()] But I think for each addon.feature will create a query that is not very optimized if there is a lot of addon -
smart way to "break" for loops when iterating
I want to iterate over a list of items and put them in a table, but I want the table to break after x items. I am using bootstrap5 to format my table. I want to display the following dict as table: {'store_6': [ProductData(id=1516004, stat=0), ProductData(id=1516028, stat=2)]} {'store_3': [ProductData(id=590418, stat=5), ProductData(id=590422, stat=1), ProductData(id=590423, stat=1), ProductData(id=590424, stat=2), ProductData(id=590425, stat=0), ProductData(id=590427, stat=4), ProductData(id=590432, stat=0)), ProductData(id=1590418, stat=0), ProductData(id=1590422, stat=0), ProductData(id=1590423, stat=0), ProductData(id=1590424, stat=0), ProductData(id=1590425, stat=0), ProductData(id=1590427, stat=2), ProductData(id=1590432, stat=0)), ProductData(id=1690418, stat=0), ProductData(id=1690422, stat=0), ProductData(id=1690423, stat=1), ProductData(id=1690424, stat=3), ProductData(id=1560425, stat=0), ProductData(id=1690427, stat=5), ProductData(id=1690432, stat=0))]} I want to have a table like this: where every row starts with the store name and then uses one column for every product. If a store has more than 10 products, the first column is blank. There cannot be more than 32 products. I have a working solution, but it looks ... quirksy: {% for store_number, products in all_store_data.items %} {% for device in products %} {% if forloop.first %} <tr> <td class="col-sm-2">{{ store_number }}</td> {% endif %} {% if forloop.counter == 11 or forloop.counter == 21 or forloop.counter == 31 %} <tr> <td class="col-sm-2"></td> {% endif %} <td class="col-sm-1"> {{ device.id }} </td> {% if forloop.last %} {% … -
I tried to install django using pip install django but still i am getting this error any comments
from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\emin\Desktop\fliteplan\gen_angular\arinc_424_19_db\multi\src\manage.py", line 22, in main() File "C:\Users\emin\Desktop\fliteplan\gen_angular\arinc_424_19_db\multi\src\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Sorl-Thumbnail not appearing
Firstly i'm very much a beginner and learning Django, but I just cannot get Sorl-Thumbnail to work in the Gallery aspects of a photography site I am developing. The site is in development and DEBUG = True, all installs went well including dependencies as far as I can see. 'sorl.thumbnail', is added to apps and migrations have gone through. I am using is to generate thumbnail within a template for loop to generate my galleries. But I get broken thumbnails for each image objects. On inspecting i get a tag img tag <img src="/media/cache/5c/58/5c58ba75425e372e94b739e292690b85.jpg"> All other images work in Admin, and on the rest of the site. I've checked MEDIA_URL but this seems ok. I cannot see a cache folder within my media folder though, does sorl generate one? I've changed my model so it is using the Sorl-Thumnail imagefield, but this didn'd achieve anything, I have THUMBNAIL_DEBUG = True in setting but this is not giving me anything in terminal. {% for img in album.images %} {% thumbnail img "100x100" crop="center" as im %} <img src="{{ im.url }}"> {% empty %} -
What is the correct method to link a homepage to multiple views in a django app
As the titles, I'm looking for the correct way to "link" views to a homepage, so whenever I press one of the buttons in the homepage, it will redirect me to a view related to a form. Right now my django app is composed by multiple views where each one of them are forms that have their own .html but I'm having a hard time to understand or find a way to make a homepage where I have links to specific views and whenever I press the submit button inside the respective form, it would redirect me to the homepage. I was thinking that the correct way to do it was making a new view that will take the role of my "homepage" but I don't know if its possible to have multiple views related to the same view Note: I understand that coding an example for this would take a while, I am just making this question so I can get a better idea and start looking in right the direction -
Django - Testing a view name retrieved from a url parameter ie. ref=home
Simply put, I am trying to test a view name, captured from a URL parameter, within one of my view functions to see if it is valid. If not, to redirect to another page. For example, take this url... www.site.com/users/?ref=view_name Then in my view ref = request.GET.get('ref', None) return redirect(ref) if ref else redirect('users') The problem is, of course, that if a user alters the ref parameter, it will kick back a 404. I was hoping to be able to test if ref=home is a valid view and return it, if not then redirect to another view. I have been messing with Django's resolve and reverse but I am not getting the results I was looking for. I also tried to use a try/finally in all sorts of ways mixed in with resolve and reverse. Yeah, dumb...I know. try: if ref: return redirect(resolve(ref)) finally: return redirect('user') I have searched for almost two hours to try to fund a succinct way to do this. Any help would be appreciated! -
Kendo Grid Datasource binding from Django Views
I am new in Django and I am trying to bind queryset from my Django model to Kendo Grid datasource. Kendo Grid displays but data is not loaded. return render is getting data as dictionary so I tried to use JsonResponse but it just renders Json string in a blank page. How I can succesfully load the grid with JSON data ? Here is what I have done so far: models.py class FromClientTransmittal (models.Model): transmittal_no = models.CharField(max_length=255) document_no = models.CharField(max_length=255) rev = models.CharField(max_length=20) subject = models.TextField() client_response = models.CharField(max_length=20) def __str__(self): return self.document_no project urls.py urlpatterns = [path('components/',include('components.urls',namespace='components')),] app urls.py from django.urls import path from components import views app_name ='components' urlpatterns = [ # Transmittals path('tables/from-client-transmittal',views.FromClientTransmittalView.as_view(),name='from-client-transmittal'),] views.py class FromClientTransmittalView(LoginRequiredMixin,View): def get(self,request): transmittals_qs = FromClientTransmittal.objects.all().values("transmittal_no","document_no","rev","client_response") transmittals = list(transmittals_qs) data={} data['title'] = "From Client Transmittals" data['pageview'] = "Transmittals" data['transmittals'] = transmittals return render(request,'components/tables/from-client-transmittal.html', data) template (html) {% extends 'partials/base.html' %} {% load static %} {% block kendojs %} <script src="https://kendo.cdn.telerik.com/2022.1.119/js/jquery.min.js"></script> <script src="https://kendo.cdn.telerik.com/2022.1.119/js/kendo.all.min.js"></script> {% endblock kendojs %} {% block extra_css %} <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet" /> <link href="https://cdn.kendostatic.com/2022.1.119/styles/kendo.common.min.css" rel="stylesheet" /> <link href="https://kendo.cdn.telerik.com/2022.1.119/styles/kendo.default.min.css" rel="stylesheet" /> <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.1.119/styles/kendo.default.mobile.min.css" /> {% endblock extra_css %} {% block content %} <div id="fbt-grid"></div> <script> $(document).ready(function () { var dataSourceArguments …