Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After performing arithmetic operations within a django model, how can I update the value of an integer in my model using the new value I obtained?
The code I have below was derived from this Question class CryptoData(models.Model): currency = models.CharField(max_length=20, choices=currency_choices, default='BTC') amount = models.IntegerField() price_with_amount = 1 def calculate_price(self): if self.currency == "BTC": currency_price = get_crypto_price("bitcoin") elif self.currency == "ETH": currency_price = get_crypto_price("ethereum") elif self.currency == "UNI": currency_price = get_crypto_price("uniswap") elif self.currency == "ADA": currency_price = get_crypto_price("cardano") elif self.currency == "BAT": currency_price = get_crypto_price("basic attention token") price_with_amount = currency_price * self.amount return price_with_amount def save(self,*args,**kwargs): self.price_with_amount = self.calculate_price() super().save(*args, **kwargs) class Meta: verbose_name_plural = "Crypto Data" def __str__(self): return f'{self.currency}-{self.amount}-{self.price_with_amount}' Basically, I want to multiply the user input, amount, by the price I obtain using my get_crypto_price function (I have confirmed that the get_crypto_price function works). After saving self.price_with_amount, I want to return it in my str method then pass it to my views.py to be used in my HTML. When I give price_with_amount a value of 1 for example, as I did in my code, it gets passed and works fine in my HTML. What I'm trying to do is change the value of price_with_amount to the obtained values in the method calculate_price. How can this be done while keeping the methods I currently have? Thanks :) -
The 'plan_image' attribute has no file associated with it
I want to serialize Construction object in EventSerializer (method get_construction) But i have sophisticated relation between Event and Construction Wheh I perform request http://127.0.0.1:8000/api/events/ I have an error The 'plan_image' attribute has no file associated with it. How can I fix this error? I a using model_to_dict from django.forms.models and I think that problem deals with this method models.py class Construction(models.Model): """ Объект строительства""" developer = models.ForeignKey( Developer, related_name="constructions", on_delete=models.CASCADE ) name = models.CharField(max_length=100) plan_image = models.ImageField(upload_to=name_image, blank=True, null=True) address = models.CharField(max_length=100) coordinates = models.PointField(blank=True) deadline = models.DateTimeField(default=timezone.now, ) workers_number = models.IntegerField(default=0) machines_number = models.IntegerField(default=0) def __str__(self): return self.name class Zone(models.Model): construction = models.ForeignKey( Construction, related_name="zones", on_delete=models.CASCADE ) time = models.DateTimeField(default=timezone.now) points = models.JSONField(default=dict) class Camera(models.Model): building = models.ForeignKey( Construction, related_name="cameras", on_delete=models.CASCADE ) name = models.CharField(max_length=100) url = models.CharField(max_length=100) proc_id = models.IntegerField(blank=True, null=True) path_frames = models.CharField(max_length=100, blank=True, null=True) zone_id_x = models.IntegerField(default=-1) # -1 means that zone is not set zone_id_y = models.IntegerField(default=-1) def __str__(self): return self.name def set_proc_id(self): """ Set process id for a new camera""" self.proc_id = 12 self.save() def set_path_frame(self): """ Set path to folders with photos""" self.path_frames = f"/photos/camera/{self.id}/" self.save() class Frame(models.Model): """ Фото с камеры """ camera_id = models.ForeignKey( Camera, related_name="frames", on_delete=models.CASCADE ) timestamp = models.DateTimeField(default=timezone.now) … -
How to fix the migrations error "column does not exist" with Django?
Something went wrong when I added a new field call distance in my app trading under the model order, and since then Django constantly returns an error when I try to create a new field: django.db.utils.ProgrammingError: column "distance" of relation "trading_order" does not exist What I did: delete the .py files in the migrations folder delete the .pyc files in the pycache folder running python manage.py makemigrations then python manage.py migrate --fake Unfortunnatly it did not fix the issue so I would appreciate some help to put my hands into the database tables as I'm not familiar with PostgreSQL. In similar issues it seems that the solutions (here and here) where to manually delete django_migrations from the psql shell, but in my case it says DELETE 0 so I don't understand. postgres@ubuntu-2cpu-4gb-de-fra1:~$ psql -d djangodb djangodb=# DELETE FROM django_migrations WHERE app='my_app'; DELETE 0 My question is how can I solve this problem ? It would be fine to drop the order model but I would like to keep the rest of the tables. -
How to add manytomanyfield attributs with form instead select option field in Django?
info: I have two models customer and items model. customer has ManyToManyField items attribute. my Createview is working fine multiple items save in database while am creating new customer i am able to select multiple items in form. but Problem: I want to add item form attribute with customer form. I need when i create new customer Save a new item with the new customer... it is possible without using Django formset? Model.py class Item(models.Model): name = models.CharField(max_length=255) datetime = models.DateTimeField(auto_now_add=True) amount = models.FloatField(default=0) remaining = models.FloatField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=11) item = models.ManyToManyField(Items) -
Django view bypass render request
I have a table with data and a button in which the user can delete the whole object, I implemented a template where the user is supossed to be redirected so he can choose between confirm the delete or cancel it. But when I click the delete button it instantly delete the object, any idea on how to tell the view to first go to that template and then, if it's the case, delete the object? Here is the template:"borrar_oficio.html" I want to be redirected after clicking the delete button: {% extends 'base.html' %} {% block content %} <p>Are you sure you want to delete {{ item }}?</p> <form action="{% url 'oficios:borrar' item.id %}" method="POST"> {% csrf_token %} <a href="{% url 'oficios:list' %}">Cancelar</a> <input type="submit" name="Confirmar"> </form> {% endblock content %} Here is the piece of the template where the button is: <form action="{% url 'oficios:borrar' oficio.folio %}" method='POST'> {% csrf_token %} <button type="submit" class="btn btn-danger btn-lg" data-toggle="tooltip" data-placement="top" title="Eliminar"><i class="fas fa-trash-alt"></i></button> </form> Here is the method that deletes the object in views.py @login_required(login_url="/accounts/login/") def borrar_oficio(request, pk): oficio = Oficio.objects.get(folio=pk) if request.method == "POST": oficio.delete() return redirect('oficios:list') context = {'item': oficio} return render(request, "borrar_oficio.html", context) And my urls.py of that … -
Django-gsheets authentication generates JSOn error
I'm trying to build a webapp with Django and I want to use Google Sheets as my data base.I used the Django-gsheets project to do so, but when it's time to authenticate, even though I got a JSON key (and it worked fine outside django with python), I can't find the suggested directory (/gsheets/authorize). So I linked the Django settings.py and urls.py to the JSON file as suggested, but I still get the following error. found 2 syncable models Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/gsheets/management/commands/syncgsheets.py", line 13, in handle model.sync_sheet() File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/gsheets/mixins.py", line 75, in sync_sheet cls.pull_sheet() File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/gsheets/mixins.py", line 63, in pull_sheet return interface.pull_sheet() File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/gsheets/gsheets.py", line 293, in pull_sheet field_indexes = {self.column_index(f): f for f in self.sheet_headers if f in sheet_fields or sheet_fields == 'all'} File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/gsheets/gsheets.py", line 87, in sheet_headers noop = self.sheet_data File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/gsheets/gsheets.py", line 75, in sheet_data api_res = self.api.spreadsheets().values().get(spreadsheetId=self.spreadsheet_id, range=self.sheet_range).execute() File "/home/joaovianini/PES2/sistema-de-divulga-o-de-ics/server/django-todo-react/backend/myenv/lib/python3.8/site-packages/gsheets/gsheets.py", line 67, in api self._api … -
Is it possible to edit the django user creation form and if so could I use some php
So my problem is that I have been trying to make a website where you signup with email and are sent a verification email to confirm your email. The only decent tutorial for making this is all in php, and I was wondering if I could put it into my django site. -
POST object via Form-Data ( in Django)
Trying to post the data via multipart (form data) in django backend from react js. let form_data = new FormData(); let doc = [{ "form" : 1, "city": "Bangalore"}, { "form" : 2, "city": "Delhi"}] form_data.append("CRegNo", "Nectar00001"); form_data.append("CName", "Nectar"); form_data.append("cityName", doc); form_data.append("userID", 1); axios.post("http://127.0.0.1:8000/api/table/", form_data, head) but in Django it interprets the cityName like this ['[object Object]'] Am I doing something wrong ? -
Efficient way of checking if record exists in database within a loop?
I'm looping over a list of dictionaries that looks like this: {"code:" "ST", "date": "2021-06-30", "open": 500, "close": 510, "volume": 2000} And I got a table in my DB where code is a foreign key to another table: class HistoricStockData(models.Model): stock = models.ForeignKey(Stock, on_delete=models.DO_NOTHING) date = models.DateField() open_value = models.DecimalField(max_digits=8, decimal_places=3) close_value = models.DecimalField(max_digits=8, decimal_places=3) volume = models.IntegerField() class Meta: db_table = "historic_stockdata" verbose_name_plural = "Historic Stock Data" I am then trying to insert these HistoricStockData instances to the db stocks = [] for value in data: # data is the big json file that I'm parsing stock_name = value["code"] date = value["date"] open_price = value["open"] close_price = value["close"] volume = value["volume"] stock_info = { "stock": Stock.objects.get(stock=stock_name), # only append if I get a match here "date": date, "open_value": open_price, "close_value": close_price, "volume": volume } stocks.append(stock_info) My question is, how can I only append each individual stock_info to stocks if I get a match on Stock.objects.get(stock=stock_name) Doing a try/catch block with a Stock.DoesNotExist clause seems to be very inefficient if the list is big - resulting in a lot of db queries Is this the best way? try: stock_info = { "stock": Stock.objects.get(stock=stock_name), "date": date, "open_value": open_price, "close_value": close_price, "volume": … -
How to effectively manage cache (Redis) with Django Rest Framework?
We have been working with Django and Django RestFramework for quite a time now and facing a lot of challenging to manage cache in Redis, our models look like (1) School (Details of School) (2) Teacher (FK School, with all details of teacher) (3) Student (FK Teacher, with all details of Teacher) Our users would be operating CRUD operation on School, like /get_all_info should return a JSON object like, { "name": "something" "teachers": [ { "name": "teacher1 name", "students": [ { "name" : "student1 name" }, ... all students of that teacher ] }, ... all teacher of that school ] } Also, the whole system is very dynamic, each component keeps on changing. Around 90% of requests are of the type stated above. We were thinking of adding post-save signals to delete full cache each time for the school like a student is updated in post-save first we will find his-her school then delete cache for that school. Is there is some more elegant/better approach? Is there any python library that can handle all this? -
Get amount of all used ingredients in ordered dishes (Django ORM) to make a shopping list
I have dishes (recipes), ingredients in them, price for ingredient, date for serving the dish, orders of this dish on this date (full, double, half). So I need to combine shopping list for ingredients in format: potato 5 pcs lemon 3 pcs Tables: class IngredientType(models.Model): name = models.CharField(max_length=100, verbose_name="Тип ингредиента") picture = models.ImageField(verbose_name="Изображение типа ингредиента") def __str__(self): return f"Тип ингредиента: {self.name}" class Supplier(models.Model): name = models.CharField(max_length=100, verbose_name="Имя поставщика") picture = models.ImageField(verbose_name="Изображение поставщика") description = models.TextField(verbose_name="Описание поставщика") phone = models.CharField(max_length=100, verbose_name="Телефон поставщика") site = models.CharField(max_length=100, verbose_name="Сайт поставщика") address = models.CharField(max_length=200, verbose_name="Адрес поставщика") def __str__(self): return f"Поставщик {self.name}" class Ingredient(models.Model): """Ingredient model""" name = models.CharField(max_length=255, verbose_name="Имя ингредиента", unique=True) measure = models.CharField(max_length=30, verbose_name="Размерность") price = models.DecimalField( decimal_places=2, verbose_name="Цена ингредиента", max_digits=10, default=0, ) type = models.ForeignKey( IngredientType, on_delete=models.SET_DEFAULT, default=None, verbose_name="Тип ингредиента", related_name="ingredients", ) supplier = models.ForeignKey( Supplier, on_delete=models.SET_DEFAULT, default=None, verbose_name="Поставщик", related_name="ingredients", ) def __str__(self): return f"Ингредиент: {self.name} ({self.measure})" class DishType(models.Model): name = models.CharField(max_length=100, verbose_name="Тип блюда") picture = models.ImageField(verbose_name="Изображение типа блюда") def __str__(self): return f"Тип блюда {self.name}" class Dish(models.Model): name = models.CharField( default="New Dish", verbose_name="Имя блюда", max_length=100 ) picture = models.ImageField(verbose_name="Изображение блюда") description = models.TextField(verbose_name="Описание блюда") price = models.DecimalField( decimal_places=2, verbose_name="Цена блюда", max_digits=10 ) date_created = models.DateTimeField(auto_now_add=True) type = models.ForeignKey( DishType, on_delete=models.SET_DEFAULT, default=None, verbose_name="Тип блюда", … -
How to select,insert,update,delete data in MySQL database from an HTML form using Django table
explain how to select,insert,update,delete data in MySQL database from an HTML form using Django table thanks in advance -
Class 'DecimalField' does not define '__sub__', so the '-' operator cannot be used on its instances
I am programming a property in Django which is supposed to gather its value from subtracting two models.DecimalField. Yet Pycharm is telling me that (see title). How could it be that two decimals cannot be operated? Example code _profit = models.DecimalField(max_digits=10, decimal_places=2) amount_in_crypto = models.DecimalField(_('amount in Crypto'), max_digits=10, decimal_places=7) crypto_market_price = models.DecimalField(_('Crypto market price'), max_digits=10, decimal_places=2) crypto_sell_price = models.DecimalField(_('Crypto sell price'), max_digits=10, decimal_places=2) @property def profit(self): return (self.crypto_sell_price - self.crypto_market_price) * self.amount_in_crypto profit.fget.short_description = _('profit') Warning: I have inspected Django DecimalField's code and indeed it does not define __sub__ and it inherits from field (which wouldn't make any sense to implement that method), so warning seems correct but question is: Why doesn't Django implement mathematical operations in DecimalField? Is there a reason? Am I missing sth? -
call function of views.py from django template (onclick)
I want to call method "SendOTP" which is written in views.py from django template onclick. I just want to call function , i don't want any change template or url. Other user input form value must be remain after calling function <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="number" name='mobile' placeholder="mobile"> <input type="button" class='btn btn-primary' onclick="SendOTP()" value="Get otp"></input> <button type="submit" class='btn btn-primary' disabled>Sign Up</button> </form> -
Django, send_mail, gets not enough values to unpack
ValueError at /accounts/password_reset/ not enough values to unpack (expected 2, got 1) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/password_reset/ Django Version: 3.1 Exception Type: ValueError Exception Value: not enough values to unpack (expected 2, got 1) Exception Location: d:\Python\Code\dictionary.env\lib\site-packages\django\core\mail\message.py, line 96, in sanitize_address Python Executable: d:\Python\Code\dictionary.env\Scripts\python.exe Python Version: 3.9.1 class CustomResetPasswordView(PasswordResetView): def post(self, request, *args, **kwargs): email = request.POST.get('email') try: _user = User.objects.filter(email=email).first() if not _user: raise Exception('Invalid email address!') else: context = { 'email' : _user.email, 'domain' : get_current_site(request).domain, 'uid' : urlsafe_base64_encode(force_bytes(_user.pk)), 'user' : _user, 'token' : default_token_generator.make_token(_user), 'protocol': 'https' if request.is_secure() else 'http', } _superuser = User.objects.filter(is_superuser=True).values_list('email').first() send_mail( subject='Password Reset Request', message=context, from_email=_superuser, recipient_list=[_user.email] ) except Exception as e: raise settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'mail.smtp2go.com' EMAIL_HOST_USER = 'confidential' EMAIL_HOST_PASSWORD = 'confidential' -
Connecting a custom logger written using the pythonjsonlogger
I wrote the following logger. How can I connect it to Django for different levels? import inspect import logging from datetime import datetime from pythonjsonlogger import jsonlogger class Logger: def __init__(self, name: str): self.logger = logging.getLogger(name) self.logger.setLevel(logging.INFO) console = logging.StreamHandler() log = logging.FileHandler(filename="logs.log") formatter = jsonlogger.JsonFormatter() log.setFormatter(formatter) log.setLevel(logging.INFO) console.setLevel(logging.ERROR) if self.logger.hasHandlers(): self.logger.handlers.clear() self.logger.addHandler(log) self.logger.addHandler(console) def get_log_data(self): curframe = inspect.currentframe() self.calframe = inspect.getouterframes(curframe, 2) previous_frame = curframe.f_back self.lines = inspect.getframeinfo(previous_frame)[3] self.class_name = previous_frame.f_locals["self"].__class__.__name__ time = datetime.now() self.log_time = time.strftime("%a, %d %b %Y %H:%M:%S%z") def log_error(self, message: str, traceback: str, parent_id: str): self.get_log_data() self.logger.error( message, extra={ "datetime": self.log_time, "level": "ERROR", "class_name": self.class_name, "fnc_name": self.calframe[1][3], "parent_id": parent_id, "stack": traceback, "fnc_call": " -> ".join(self.lines), }, ) def log_info(self, message: str, parent_id: str = None): self.get_log_data() self.logger.info( message, extra={ "datetime": self.log_time, "level": "INFO", "class_name": self.class_name, "fnc_name": self.calframe[1][3], "fnc_call": " -> ".join(self.lines), "parent_id": parent_id, }, ) -
BootstrapError Form
I'm getting this error in my template: Exception Value: Parameter "form" should contain a valid Django Form. My forms.py: from django import forms from .models import CostumerProfile class CostumerForm(forms.ModelForm): class Meta: model = CostumerProfile fields = ('name', 'email', 'phone', 'business') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'business': forms.Select(attrs={'class': 'form-control'}), } In my views.py I did this: from django.http.response import HttpResponseRedirect from django.urls import reverse from django.shortcuts import render from .forms import CostumerForm def index(request): return render(request, 'landingpage/index.html') def about(request): return render(request, 'landingpage/about.html') def new_contact(request): if request.method == 'POST': form = CostumerForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('landingpage:thanks')) else: form = CostumerForm() return render(request, 'landingpage/index.html', {'form': form}) def thanks(request): return render(request, 'landingpage/thanks.html') My index.html form section: <!-- Contact Section--> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Contact Section Form--> <div class="form-floating mb-3"> <div class="row justify-content-center"> <div class="col-lg-8 col-xl-7"> <form action="{% url 'landingpage:index' %}" method="post" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button class="btn btn-primary btn-xl enabled" id="submitButton" type="submit">Send</button> {% endbuttons %} </form> </div> </div> </div> </div> </section> Any … -
Django Admin LTE WebApp: How do I fix random decimal separators in firefox browser, while chrome works perfectly?
I have the problem that the separators of decimal numbers on my Python Django website in Chrome work wonderfully and are consistent. When I open the website with Firefox, the separators change from "," to "." in completely random places. chrome view firefox view As far as I know, the problem only occurs in Firefox. Any tips would be appreciated! models.py class PVSystem(Component): capacity = models.FloatField(null=True) efficiency = models.FloatField(null=True) spec_opex = models.FloatField(null=True) feed_in_tariff = models.FloatField(null=True) forms.py: class PVSystemForm(ModelForm): prefix = 'PV' total_capex = FloatField(label=_('Preis'), widget=NumberInput(attrs={'min': '0', 'class': 'form-control'})) total_opex = FloatField(label=_('Betriebskosten'), widget=NumberInput(attrs={'min': '0', 'class': 'form-control'})) area = FloatField(label=_('Fläche'), widget=NumberInput(attrs={'min': '0', 'class': 'form-control'})) -
How do I read a request.FILES into DataSource in Geodjango
So, the goal is to create a webpage to load a .shp file into and get a summary of some calculations as a JsonResponse. I have prepared the calculations and everything and it works nicely when I add a manual path to the file in question. However, the goal is for someone else to be able to upload the data and get back the response so I can't hardcode my path. The overall approach: Read in a through forms.FileField() and request.FILES['file_name']. After this, I need to transfer this request.FILES object to DataSource in order to read it in. I would rather not upload the file on pc if possible but work directly from the memory. forms.py from django import forms from django.core.files.storage import FileSystemStorage class UploadFileForm(forms.Form): # title = forms.CharField(max_length=50) file = forms.FileField() views.py import json import os from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.template import loader from django.contrib import messages from django.views.generic import TemplateView from django.http import JsonResponse from django.conf import settings from .forms import UploadFileForm from . import models from django.shortcuts import redirect from gisapp.functions.functions import handle_uploaded_file, handle_uploaded_file_two from django.contrib.gis.gdal import DataSource from django.core.files.uploadedfile import UploadedFile, TemporaryUploadedFile import geopandas as gpd import fiona … -
How to Implement multiple kinds of users in Django?
I am new to Django so please bear with me if my questions seem too basic. So, I want to create a web app for a kind of a store in which I have three different kinds of users. Admin(Not Superuser) who can: create, view, update, delete account for a Seller(agent) issue them inventory Seller who can: sell an inventory item to a Customer(customers cannot themselves purchase it, only the seller can do it by filling in a form) a Customer account should automatically be created upon submission of the form by Seller or if the Customer already has an account, the purchase should be added to their account Customer can login and view their account What would be the best way to go about it? Using auth Groups, Profile models or anything else? Any help would be wonderful. If something is not very clear in the question, I can provide more details. Thanks. -
Getting 404 error continuously after starting Django
I have just started to learn Django framework version 3.2.4 I did some online lessons for last two days but suddenly started getting 404 error. Reverted many things from settings.py and urls.py but no luck. Not Found: /__original-stack-frame Not Found: /__original-stack-frame [01/Jul/2021 00:25:13] "GET /__original-stack-frame?moduleId=undefined&lineNumber=undefined&columnNumber=undefined HTTP/1.1" 404 12101 [01/Jul/2021 00:25:13] "GET /__original-stack-frame?moduleId=undefined&lineNumber=undefined&columnNumber=undefined HTTP/1.1" 404 12101 Above loops continuously and I am not able to figure out the issue. My urls.py contains urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), path('__debug__/', include(debug_toolbar.urls)), ] And settings.py contains INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'playground' ] Can someone help? -
How to append a link button to a django admin view
How do I add a custom button in an Import view of the Django Admin? We need to include a template file so that users can upload data easily. I don't know if it can be done from the class or if it has to be included somewhere else. I couldn't find this view, apparently it's automatically generated by the admin. -
How do I update a variable set by 'with' in Django Template
Following is the code where I need to update a variable. {% with a=1 %} {% for x in object_list %} {% if 'clone' in x.game and a is 1 %} <div class="alert alert-primary"> <h2 class="p-3">{{ x.title }}</h2> </div> {{ a=2 }} {% endif %} {% endfor %} {% endwith %} {{ a=2 }} does not set a to 2, throws the following error TemplateSyntaxError at / Could not parse the remainder: '=2' from 'a=2' -
Customize PasswordResetConfirmView
I'm trying to set a user is_active state to True when the user have clicked on the reset-password link I've emailed them. However, I don't understand how to get access to the PasswordResetConfirmView, the code below don't do any prints when I go to the related URL. Any ideas on how I should do this? from django.contrib.auth import views as auth_views class PasswordResetConfirmView(auth_views.PasswordResetConfirmView): print("Request view") def get(self, request, *args, **kwargs): print(request) print(request.user) return super().get(request, *args, **kwargs) -
How to set a ManyToMany field to an existing object in a Django migration?
I'm trying to migrate a 1-to-many field to an existing many-to-many field. I'll explain. If I understood what was happening exactly, this question would be shorter. However, I'll try to give all the detail in hopes someone will spot the issue. For migrating a 1-to-many to a new many-to-many, I read this blog post (also like this question), which worked. To summarize: They started with a 1-to-many model (pizza has one topping): from django.db import models class Topping(models.Model): name = models.CharField(max_length=20) class Pizza(models.Model): name = models.CharField(max_length=20) topping = models.ForeignKey(Topping) and showed the migrations to get from one topping to multiple toppings per pizza. In the second of three migrations they add a topping to the new many-to-many toppings field in a forward method of a migration which looks like this: def forward(apps, schema_editor): Pizza = apps.get_model("pizza", "Pizza") for pizza in Pizza.objects.all(): pizza.toppings.add(pizza.topping) However, now I'm trying to migrate a different model to use the existing toppings. add isn't right, because I don't want to create new relationships, I want to use existing ones. This is stretching the pizza example, but suppose I have a note for some pizzas about their topping (I dunno, calories?). That worked when there was one …