Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django POST multipart/form-data unexpectedly parsing field as array
I am testing an endpoint in the following manner: from rest_framework.test import APIClient from django.urls import reverse import json client = APIClient() response = client.post(list_url, {'name': 'Zagyg Co'}) I find that the model object is being created with a name of [Zagyg Co] instead of Zagyg Co. Inspecting the request object reveals the following: self._request.META['CONTENT_TYPE'] #=> 'multipart/form-data; boundary=BoUnDaRyStRiNg; charset=utf-8' self._request.body #=> b'--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="name"\r\n\r\nZagyg Co\r\n--BoUnDaRyStRiNg--\r\n' self._request.POST #=> <QueryDict: {'name': ['Zagyg Co']}> Using JSON like so: response = client.post( list_url, json.dumps({'name': 'Zagyg Co'}), content_type='application/json', ) sets the name correctly. Why is this so? -
user authentication manually in Django
If certain conditions met I want to manually authenticate user, tried the following way but it is again redirecting to the login page. def owner_login(request): token = request.GET.get('token', '') user_token = User.objects.filter(username='xxxx').first().token if token and token == user_token: user = authenticate(username='xxxx', password='yyyyyy') if user: login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('client_admin_home') else: return HttpResponse('not authorized') return render(request, 'owner_login.html', {}) Any help is much appreciated, thank you -
The page at https://lyrics-chords.herokuapp.com/ was not allowed to display insecure content from http://localhost:8000/auth/user
I've just finished creating a Django-React app and have pushed the changes to Heroku. The frontend (JS and CSS) appear on the website no problem, but requests to the backend result in the following error: [blocked] The page at https://lyrics-chords.herokuapp.com/ was not allowed to display insecure content from http://localhost:8000/auth/user I've consulted the Internet but no one seems to be getting the same error message. Consulting a friend, it seems as if I have to https secure my backend, and futher researching the subject, it seems that there is no free way to upload a SSL/TSL certificate (reference: heroku: set SSL certificates on Free Plan?). Is there a solution to this? -
How do I resolve a Django database conflict
Can't figure what's wrong?? settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. [30/Jun/2021 17:31:00] "GET / HTTP/1.1" 500 194335 -
Django Admin behaves weirdly
I have this Django app running perfectly but sometimes Django Admin works oddly, because If I click on any model, instead of taking me to the list of registries in that model, It takes me to the same model list but with a weird css. Here is the picture of the normal model list Here is the picture after clicking any model I can't add information to models or anything. -
Django form.is_valid() issue
The idea is a user will create a post on this page and fill out the title and content. Once they submit this form, a Post instance will be created with the inputs of the user for title and content. This instance will also have the id of the user associated to it. I've done a print test which yields the outputs I'm looking for but it appears that the form is not valid. Any thoughts? #views.py class LocationDetail(View): def post(self, request, locationname): current_user = request.user user_profile = Profile.objects.get(user_id = current_user) form = PostCreate() found_location = Location.objects.get(name = locationname) context = {"found_location": found_location, "form": form} if request.method == "POST": post_author = user_profile.user_id post_title = request.POST['title'] post_content = request.POST['content'] print(post_author) print(post_title) print(post_content) if form.is_valid(): Post.objects.create( title = post_title, content = post_content, author_id = post_author, ) form.save() return render(request,'location-detail.html', context) #forms.py + models.py class PostCreate(ModelForm): class Meta: model = Post fields = ['title', 'content'] class Profile(Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length = 30) profile_location = models.CharField(max_length = 80, blank=True, null=True) join_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Post(Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length = 30) content = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author} - … -
django views for uploading image file to api with auth token key and model id " pls help"
i need to fix the views uploading image to "api url" with "auth token" and "model ID" --- " it will return the prediction label and probability below code views pls help me def home(request): prediction = {} if 'prediction' in request.GET: prediction = request.GET['prediction'] url = 'https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/' % prediction data = {'file': open('C:\\Users\\sanjay\\Desktop\\nanonets\\herpes-test.jpg','rb'), 'modelId': ('', 'a01c8d5f-4daf-40b4-958e-dcc09fb14c20')} response = requests.post(url, auth=requests.auth.HTTPBasicAuth('-4k7A3R', ''), files=data) user = response.json() return render(request, 'pages/home.html', {'prediction': prediction} """DIS IS HOW THE API LOOKS""" {"message":"Success","result":[{"message":"Success","prediction":[{"label":"herpes","probability":0.9999999},{"label":"scabies","probability":7.587139e-8}],"file":"herpes-test.jpg","page":0}],"signed_urls":{"uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg":{"original":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?expires=1625106512\u0026or=0\u0026s=4c7813061401e0aa726bf21cc522e7d4","original_compressed":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-407d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=0\u0026s=0518d01e4c79a0e0024bf5af45263102","thumbnail":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4d7af-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026w=2470\u0026s=936a8b57d9be6956aba0dd4c66de2222","acw_rotate_90":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=270\u0026s=6ca0360c5bbef4268ff4fb82038d9de4","acw_rotate_180":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=180\u0026s=1d37c1a4b0988e2563d4c87dc0a4633d","acw_rotate_270":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=90\u0026s=0bfac9da3377b3dff431eadaea3b0c4a","original_with_long_expiry":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?expires=1640644112\u0026or=0\u0026s=cc8227ba0a24e9ac4fb327d99e26a7c0"}}} -
Django InlineFormset: Size based on number of models
I am creating a gradebook app. With the following models: class Student(models.Model): student_id = models.IntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Component(models.Model): CATEGORY_CHOICES = [ ('QZ', 'Quiz'), ('AS', 'Assignment'), ('TS', 'Test'), ] name = models.CharField(max_length=50) category = models.CharField( max_length = 2, choices = CATEGORY_CHOICES, default='AS', ) due_date = models.DateField() grade_total = models.PositiveIntegerField() class Score(models.Model): value = models.PositiveIntegerField() component = models.ForeignKey(Component, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) How can I populate a formset based on the number of students with a Component instanced? See: Concept -
Django's TemplateResponse looking in the wrong directory for templates
File Tree (Rough Example) project/ project/ . . project_admin/ admin.py . my_app/ templates/ my_app/ html files . . . templates/ admin/ admin_profile.html logout.html . . . project_admin/admin.py from django.contrib import admin from django.template.response import TemplateResponse from django.urls import path class BookrAdmin(admin.AdminSite): logout_template = 'admin/logout.html' def profile_view(self, request): request.current_app = self.name context = self.each_context(request) return TemplateResponse(request, 'admin/admin_profile', context) def get_urls(self): urls = super().get_urls() url_patterns = [path("admin_profile", self.profile_view)] return urls + url_patterns project/settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent . . TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] . . So I'm following a tutorial about adding views to the admin site, but I am stuck here. I've copied the example code from the tutorial github page, and I'm still stuck. Looking at my project_admin/admin.py file, the logout template goes to the correct file templates/admin/logout.html. However, inspecting the code further in returning the TemplateResponse, my code tries to pull admin/admin/admin_profile.html out of my_app/templates/.... I've looked through my BASE_DIR. That looks good to me. I've tried changing TEMPLATES DIRS to 'DIRS': [BASE_DIR, 'templates']. That didn't work. I've tried even tried changin BASE_DIR to BASE_DIR … -
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, }, )