Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How can I add a class to a particular inline row based on the date recorded in a field of the row?
I have an inline model DayOff where I would like to gray out the entire row if the date entered on the DayOff object is a past date. Any idea how to add a class or styling to an entire row, based on the date field recorded in it? -
Running Django makemigrations Docker container
I have two Docker containers, one for MySQL and one for Django. I modify a model that requires a migration, and therefore the need to run makemigrations: what do I do such that I end up with a 000X_stuff.py file on my local drive that, when I fire up the Django container and it runs the migration action, the migration occurs? The only option that comes to mind is to run docker exec -it CONTAINER_NAME python ./manage.py makemigrations APP_NAME. Two problems with this: It only works the first time. Successive reruns of makemigrations claim there are no changes. The only way to overcome this is to drop the table and the appropriate row in the migrations table. If any Python migration files are generated, they are generated within the container. I would have to copy them manually from container to host if I want to commit them. -
Django wsgi.py can't initialize the settings module: "ModuleNotFoundError: No module named 'config'"
My Django dev environment runs fine with the native server, but when I try to execute wsgi.py, either locally or on the production server, I get the extremely popular ModuleNotFoundError: No module named 'config' error. The traceback suggests that the failure happens when django/core/wsgi.py attempts to execute django.setup(set_prefix=False) and that method needs to call settings.[ANYTHING], in this case configure_logging(settings.LOGGING_CONFIG, settings.LOGGING). Calling the settings.LOGGING_CONFIG variable tells django.conf.settings to initialize, but in this context it fails: Traceback (most recent call last): File "./config/wsgi.py", line 35, in <module> application = get_wsgi_application() File "C:\...\anaconda\envs\venvname\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\...\anaconda\envs\venvname\lib\site-packages\django\__init__.py", line 18, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\...\anaconda\envs\venvname\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\...\anaconda\envs\venvname\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\...\anaconda\envs\venvname\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\...\anaconda\envs\venvname\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in … -
Django : can't login in django administration
First of all, I've created a User model, which inherits from AbstractUser. I use another model which is called CustomUserManager (which inherits from UserManager). In CustomUserManager, i rewrote the create_user method, and the create_superuser method. When i create a simple active user, it works fine (i can connect the user). When i create a superuser, it works fine ("Superuser created successfully") BUT when i go to the django administration pannel, and i enter the correct information of the superuser, it doesn't work and display the following message : "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. " Here's my models.py : class CustomUserManager(UserManager): def _create_user(self,email,password,first_name,last_name,**extra_fields): email = self.normalize_email(email) user = User(email=email) user.is_active=True user.password = make_password(password) user.save(using=self._db) return user def create_user(self,email,password,first_name,last_name,**extra_fields): return self._create_user(email,password,first_name,last_name,**extra_fields) def create_superuser(self,email,password,first_name,last_name,**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,first_name, last_name, **extra_fields) class User(AbstractUser): username = None email = models.EmailField(unique=True, blank=False) first_name = models.CharField(blank=False,max_length=50) last_name = models.CharField(blank=False,max_length=50) REQUIRED_FIELDS=["first_name","last_name"] USERNAME_FIELD = 'email' objects = CustomUserManager() -
ValueError at /testimonials/ The view resort.views.ReviewsView didn't return an HttpResponse object. It returned None instead
"""Renders web pages for the reviews and reviews form.""" from django.shortcuts import render, redirect, get_object_or_404 from .models import * from django.views import View from .forms import * from django.views.generic import ListView, DetailView from django.http import HttpResponseRedirect, HttpResponse from django.core.mail import send_mail, BadHeaderError from django.contrib import messages class ReviewsView(ListView, View): template_name = "resort/testimonial.html" model = Review form = ReviewForm def post(self, request, *args, **kwargs): """Renders the form and creates an instance.""" form = ReviewForm(request.POST) if form.is_valid(): review = Review.clean_fields() form.instance.name = request.name form.instance.review = review form.save_m2m() return redirect('reviews') def get_context_data(self, **kwargs): """load data into thecontext dictionary to be rendered on the page.""" context = super().get_context_data(**kwargs) context.update({ 'form': self.form, }) return context