Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store list of JSON data in a Django model?
What is the best way to store a list of JSON dictionaries in a Django model field? I am creating a transaction application for shops and I am trying to store the items of each order in a field without relying on relational models. Each item in this list will have a name, quantity and unit_price. For example: [ { "name": "Product #1", "quantity": 1, "unit_price": 25.0 }, { "name": "Product #2", "quantity": 1, "unit_price": 50.0 } ] I am using a PostgreSQL database, but I've heard it's bad practice to use database-specific fields, such as ArrayField. What would be the best way to go about this and that would also keep the DRF serialization as simple as possible? -
Get list of Array requested by ajax in a django view
let's take this ajax request in a django template: list_of_array = [{name1,value1},{name2,value2},{name3,value3}] $.ajax({ type: 'GET', url: myview_url, data: { my_list: list_of_array, }, dataType: 'json', success: function (response) { do something } }, error: function (error_data) { console.log("error") console.log(error_data) } }) Then, in the view under myview_url, I try to do something with 'my_list' in data. Like so: def myView(request): list = request.GET.getlist('my_list[]') do something... ... response_data = { "list": list, } return JsonResponse(response_data) but list return an empty list. If my_list doesn't contain associative array, like if it is: my_list = [1,2,3] I can get its content in my view. So, how to get the content of list that contains Array in my django view ? Thank you -
Getting CSRF token missing when submitting form data in django
I am getting CSRF token missing error everytime while submitting the form mentioned below. What might be the problem? Below is the code for my views.py file : *all imports are here # Create your views here. def takeExam(request, pk): mock = MockTest.objects.get(id=pk) context = { 'mock':mock, } return render(request, "exam/take-exam.html", context) @login_required(login_url='login') def startExam(request,pk): mock=MockTest.objects.get(id=pk) questions=Question.objects.all().filter(test=mock) if request.method=='POST': pass response= render(request,'exam/start_exam.html',{'mock':mock,'questions':questions}) response.set_cookie('mock_id',mock.id) return response @login_required(login_url='login') def calculateMarks(request): if request.COOKIES.get('mock_id') is not None: mock_id = request.COOKIES.get('mock_id') mock=MockTest.objects.get(id=mock_id) total_marks=0 questions=Question.objects.all().filter(course=mock) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks std = student.CustomUser.objects.get(user_id=request.user.id) result = Result() result.marks=total_marks result.exam=mock result.student=std result.save() return HttpResponseRedirect('view-result') @login_required(login_url='login') def resultViews(request): mocks=MockTest.objects.all() return render(request,'exam/view_result.html',{'mocks':mocks}) @login_required(login_url='studentlogin') def checkMark(request,pk): mock=MockTest.objects.get(id=pk) std = student.CustomUser.objects.get(user_id=request.user.id) results= Result.objects.all().filter(exam=mock).filter(student=std) return render(request,'exam/check_marks.html',{'results':results}) @login_required(login_url='studentlogin') def studentMark(request): mocks=MockTest.objects.all() return render(request,'exam/student_marks.html',{'courses':mocks}) My html file: {% extends 'main.html' %} {% block content %} {%load static%} <div class="jumbotron my-2 py-4" onmousedown="return false" onselectstart="return False" > <h1 style="text-align: center">{{mock.name}}</h1> <form class="form my-2" autocomplete="off" onsubmit="saveAns()" action="{% url 'calculate-marks' %}" method="POST" > {% csrf_token %} {% for q in questions%} {% if q.question %} <div class="text-danger my-3 font-weight-bold"> {{ forloop.counter }}. {% endif %} {% if q.imgQuestion %} <img src="{{q.imgQuestion.url}}" alt="imgQuestion" /> {% … -
If you see valid patterns in the file then the issue is probably caused by a circular import in django
I am getting this error "If you see valid patterns in the file then the issue is probably caused by a circular import in". I saw other stack flow questions and I know the error is coming from views.py but I cannot seem to figure out where the error is views.py/myapp from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1>Hey,Welcome</h1>') urls.py/myapp from django.urls import path from myapp import views urlpattern = [ path('',views.index, name='index') ] urls.py/myproject from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('myapp.urls')) ] -
SQLAlchemy - Passing a DDL generated Primary Key to Child Model through Relationship
I currently have a parent/child relationship defined between the Invoice/Item table. When running the following code: with Session(engine) as session: invoice = Invoice(INV_STORE=99, items=[Item(LINE_ITEM=1, BARCODE=1234567), Item(LINE_ITEM=2, BARCODE=1234567)]) session.add(invoice) session.commit() I get the following error: [SQL Server]Cannot insert the value NULL into column '...' [SQL: INSERT INTO [ITEM] ([INV_STORE], [LINE_ITEM], [BARCODE]) VALUES (?, ?, ?)] [parameters: (99, 1, 1234567)] My invoice object creates perfectly, it seems the DDL generated column values are not automatically populating the child object, only the store value I passed to the Invoice object (note the lack of INV_NUM in the insert statement). Is there something simple I am missing? Unfortunately, the legacy database we are using requires the table relationship to be configured as such, and there is no auto-increment in place for the Invoice.INV_NUM field. Here's my model configuration: class Invoice(Base): __tablename__ = 'INVOICE' INV_STORE = Column(Integer, name='INV_STORE', primary_key=True, default=1) INV_NUM = Column(Integer, name='INV_NUM', default=text(f"(SELECT MAX(INV_NUM) + 1 FROM INVOICE WHERE INV_STORE = {INV_STORE})"), primary_key=True)) ... items = relationship('Item', backref='Invoice', primaryjoin='Invoice.INV_STORE == Item.INV_STORE and Invoice.INV_NUM == Item.INV_NUM') And the Child, Item: class Item(Base): __tablename__ = 'ITEM' INV_STORE = Column(SmallInteger, ForeignKey('INVOICE.INV_STORE'), primary_key=True) INV_NUM = Column(Integer, ForeignKey('INVOICE.INV_NUM'), primary_key=True) LINE_ITEM = Column(Integer, name='LINE_ITEM', primary_key=True) ... -
Django Rest Framework - Serializer doesn't work
I am trying to create a blog API that would consist of user posts and comment instances. I am using Django & Django Rest Framework to build the API that would return data in JSON format. Below is an example of the JSON data being returned: "id": 2, "user": 1, "user_photo": "http://127.0.0.1:8000/media/users/Forest_Me.jpg", "is_owner": true, "description": "Hey there, this is my post and I like it", "images": [ { "id": 3, "post": 2, "image": "http://127.0.0.1:8000/media/posts/foo.jpg", "comment": "This is image #1" }, { "id": 4, "post": 2, "image": "http://127.0.0.1:8000/media/posts/bar.jpg", "comment": "This is image #2" } ], "created": "2022-03-23T16:58:44.800255+03:00", "likes": [ 1 ], "comment_count": 1, "comments": [ { "id": 3, "post": 2, "text": "This is a comment on my post", "user": 1, "likes": [], "created": "2022-03-23T17:00:27.074362+03:00", "images": [ 3, <----- should be URL to the image, not just id 4 <----- should be URL to the image, not just id ] } ] } My problem is that while the Post images are returned in the JSON correctly, my PostComment images are returned just as an array of id, without the URLs. I indicated with arrows in the code where I'm trying to get an array of objects (id & URLs). I suspect … -
Why can't I "git push heroku master"?
So I'm currently trying to deploy my django app to heroku, and I'm getting an error. On my app I serve both static and media files from an AWS S3 bucket, and locally everything is working fine, but when I try to deploy to heroku I get this error: These are my settings.py: PRODUCTION = True if PRODUCTION: # AWS S3 SETTINGS AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = 'public-read' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_HEADERS = { 'Access-Control-Allow-Origin': '*', } AWS_QUERYSTRING_AUTH = False AWS_LOCATION = 'static' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'joaoLina.storage_backend.MediaStorage' MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, 'media') else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I read that sometimes this problem happens because STATIC_ROOT is not set, but that is not the case. And I know I could just do: $ heroku config:set DISABLE_COLLECTSTATIC=1 but this way the problem will still be there. I did locally: python3 manage.py collectstatic python3 manage.py test and everything went just fine with 0 … -
what is fields and field_classes in django UserCreationForm?
im new to learning django and i wanted to make signup form in django but i see this part of code and i didnt understand it what are these code doing and why we use them class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ("username",) field_classes = {'username': UsernameField} can somebody explain what are ```fields = ("username",) field_classes = {'username': UsernameField}``` and why we use them? -
Where do I place functions for setting foreign key values in Django?
I have two functions that I would like to add to my Django project, get_netloc which would run on the the Document.source_url and return a value to input into the set_source function. The set_sorce also take a list of tuples, from the SOURCE_CHOICES in the Source model. This set_source would act like a @property setter in a class, which I have a hunch is what I need to do. I am just not sure where these functions belong and how to implement them correctly. I am even wondering if they need to be in the forms, though the documents can also come from S3 via a lambda function. Here is the code I have: from django.db import models from urllib.parse import urlparse def get_netloc(url): try: return urlparse(url).netloc except: return 'other' def set_source(netloc, list_tuples): for i in list_tuples: return netloc if netloc in i else 'other' class Source(models.Model): OTHER = 'other' STACK = 'www.stackoverflow.com' TWITTER = 'www.twitter.com' REDDIT = 'www.reddit.com' SOURCE_CHOICES = [ (OTHER, 'Other'), (STACK, 'StackOverflow'), (TWITTER, 'Twitter'), (REDDIT, 'Reddit'), ] name = models.CharField('Source Name', max_length=18, choices=SOURCE_CHOICES, default=OTHER) def __str__(self): return self.name class Document(models.Model): name = models.CharField('Name', max_length=200) full_text = models.TextField('Text', blank=True, default='') source_url = models.URLField(blank=True) source = models.ForeignKey(Source, null=True, … -
How to make turn server fast
I am working on my personal project from 2 month and i am trying to build a Video confrencing web application using django and webRTC. I am facing the esshu i.e i am using stun/turn server for connnection for diffrent network but turn server is too slow and its not good for user experience i am using some public turn server. And if i only using stun server then it also work for some specific network. Servers that i am using is let iceConfiguration = { "iceServers": [ // { url :'stun4.l.google.com:19302'}, // { url: 'stunserver.org:3478'}, { url: 'stun:stun.l.google.com:19302' }, { url: 'stun:stun1.l.google.com:19302' }, { url: 'stun:stun2.l.google.com:19302' }, { url: 'stun:stun3.l.google.com:19302' }, { url: 'turn:numb.viagenie.ca', credential: 'muazkh', username: 'webrtc@live.com' }, { url: 'turn:relay.backups.cz', credential: 'webrtc', username: 'webrtc' }, { url: 'turn:relay.backups.cz?transport=tcp', credential: 'webrtc', username: 'webrtc' }, { url: 'turn:192.158.29.39:3478?transport=udp', credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=', username: '28224511:1379330808' }, { url: 'turn:192.158.29.39:3478?transport=tcp', credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=', username: '28224511:1379330808' }, { url: 'turn:turn.bistri.com:80', credential: 'homeo', username: 'homeo' }, { url: 'turn:turn.anyfirewall.com:443?transport=tcp', credential: 'webrtc', username: 'webrtc' } ] }; And my whole code is here https://github.com/nikhilkotiya/Microsoft-Teams/tree/newbranch Please help me out for this problem. Thanks in advance. -
Django created staticfiles folder rather than static folder
I do not know why Django created a folder named staticfiles rather than static as expected. That might be the reason why I got an error after running python manage.py collectstatic: The system cannot find the path specified: 'D:...\\static' My settings file included: from pathlib import Path import os import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I had already tried to change 'staticfiles' to 'static' in STATIC_ROOT, but no success. Could anyone please explain why and how to create a folder name "static"? Thank you very much in advance! -
How to get rid of django comments and kj buckets while upgrading from django 1.5 to django 4
I have a Django project of 1.6 which i need to upgrade it to django 4 and python 3 while doing this i have some modules error like Django comments and kj bucket how can i get the rid of this I search on internet but i even cant any find relating kj bucket all i am getting the result for s3 bucket which is not kj bucket and the result for django comments i am getting results are applicable only for Django 2.8 means i cant use them now how can i resolve this please help. also these modules not even install able now -
While editing an existing Django model, my .save() method creates the correct object, but it doesn't seem to persist through the database
I have a project where I want to give users the ability to update some of the fields on an existing Case they have. I have set up the form and it appears to work. However, when I go to save the new, updated date, the .save() method doesn't work as expected. I do the x = case.save() command, and when I print out "x", I see the expected data that I input in the form. However, immediately after the if statement, it does not persist. The database does not update. Thoughts? relevant methods in views.py: @login_required(login_url='/accounts/login') def stopThrough(request): if request.method == 'POST': c = IDForm(request.POST) if c.is_valid(): val = c.cleaned_data['id'] urlStr = ("/polls/case/edit/" + val) return redirect(urlStr) cForm = IDForm return render(request, 'caseEdit.html', {'start': True, 'cForm' : cForm }) @login_required(login_url='/accounts/login') def caseEdit(request, id): if request.method == 'POST': check = CaseForm(request.POST) print(check) if check.is_valid(): wtf = check.save() return redirect("/polls/case/edit/0") c = Case.objects.get(victimID=id) cForm = CaseForm(instance=c) return render(request, 'caseEdit.html', {'start': False, 'cForm' : cForm }) Case model class Case(models.Model): created_date = models.DateField(auto_now_add=True) creator = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='creator', null=True) victimID = models.CharField(max_length=100) #service list functions client_intake = models.BooleanField() client_orientation = models.BooleanField() criminal_justice_system_based_advocacy = models.BooleanField() crisis_intervention_or_24_hour_hotline = models.BooleanField() dental = models.BooleanField() education = … -
How to display a datatable fom mongodb data using django
I am trying to get an interface with a datatable view using django, showing data that I scraped before and stored in MongoDB. I am pretty new in it and I don't know how to deal with the stuff and what to write in views.py forms.py and urls.py. I would appreciate any help from you and Thanks in advance. This is my python code : from selenium import webdriver from pymongo import MongoClient from time import sleep from lxml import html import pandas as pd import cssselect import pymongo import json import csv def scrap(subject): driver = webdriver.Edge(executable_path=r"C:\Users\aicha\Desktop\mycode\aliexpress\msedgedriver") url = 'https://www.aliexpress.com/wholesale?trafficChannel=main&d=y&CatId=0&SearchText=bluetooth+earphones&ltype=wholesale&SortType=default&page={}' baseurl = 'https://www.aliexpress.com' client = MongoClient("mongodb://localhost:27017/") with open ("file1.csv", "w", encoding="utf-8", newline = '') as csvfile: wr = csv.writer(csvfile) wr.writerow(["Title","Price", "Currency", "Stars", "Number of orders", "Shipping Cost", "Supplier", "Product Links" ]) for page_nb in range(1, 4): print('---', page_nb, '---') driver.get(url.format(page_nb)) sleep(2) current_offset = 0 while True: driver.execute_script("window.scrollBy(0, window.innerHeight);") sleep(.5) # JavaScript has time to add elements new_offset = driver.execute_script("return window.pageYOffset;") print(new_offset,current_offset) if new_offset <= current_offset: break current_offset = new_offset sleep(3) tree = html.fromstring(driver.page_source) results = [] for product in tree.xpath('//div[@class="JIIxO"]//a'): title = product.xpath('.//h1/text()') if title: title = title[0] price = product.cssselect('div.mGXnE._37W_B span') price = [x.text for x in price] … -
Why does Django Admin model page raise FieldDoesNotExist exception after a successful migration?
Scratching my head on this one. I've simply added a new field to a model. class Image(BaseModel): url = models.URLField(max_length=1000, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() # new field added below class Type(models.TextChoices): HEADER = 'HEADER', _('Header') type = models.CharField( max_length=20, choices=Type.choices, null=True, blank=True ) class Meta: db_table = 'Image' Then I ran python manage.py makemigrations followed by python manage.py migrate. This was successful and I can see the new field on the table in my database. The info from the django_migrations table looks correct. Here is my migration file: # Generated by Django 3.0.5 on 2022-03-23 12:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('example', '0082_auto_20220322_1937'), ] operations = [ migrations.AddField( model_name='image', name='type', field=models.CharField(blank=True, choices=[('HEADER', 'Header')], max_length=20, null=True), ), ] The problem I'm facing is when I visit that model page in the django admin, I get an internal server error with the following: Traceback (most recent call last): example_app | File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/utils.py", line 262, in lookup_field example_app | f = _get_non_gfk_field(opts, name) example_app | File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/utils.py", line 297, in _get_non_gfk_field example_app | raise FieldDoesNotExist() example_app | django.core.exceptions.FieldDoesNotExist example_app | example_app | During handling of the above exception, another exception … -
Redis is not Importing correctly in Django (with out Redis-cache configuration working perfectly)
Problem is that i'm not able to get the Redis-cache setting configuration right his is the Error im getting, Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ranajoy\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() `File "C:\Users\Ranajoy\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs)_** File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\checks\caches.py", line 65, in check_file_based_cache_is_absolute cache = caches[alias] File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\connection.py", line 62, in __getitem__ conn = self.create_connection(alias) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\cache__init_.py", line 52, in create_connection return backend_cls(location, params) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django_redis\cache.py", line 53, in __init__ self._client_cls = import_string(self._client_cls)_ File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import import_module(module_path) File "C:\Users\Ranajoy\AppData\Local\Programs\Python\Python310\lib\importlib__init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in call_with_frames_removed_ File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django_redis\client__init_.py", line 1, in ** from .default import DefaultClient File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django_redis\client\default.py", line 12, in from redis import … -
how to add the UPI or online payment feature in django project?
I am trying to create a website which has the online payment option like google pay, phone pay, paytm, netbanking and card. but I do not know how to do it. so, please tell me that how to do it, and give me an example code. thank you -
Python Post Form to external API
I need to get user form field in order to post to an external API, my question is how to pass form fields with Json payload. url = "" payload={} headers = {} response = requests.request("GET", url, headers=headers, data=payload) -
Make django application healthy on AWS instance
I am a beginner and I want to know how to find loose entry points in the pre existed application that can help to make aws server healthy. -
HOW TO EXTRACT THE FIRST FLOAT FROM A STRING IN DJANGO
I have a string containing a string and word, I want to extract the first float the string. myString = 12.5% per month myFloat= [float(s) for s in re.findall(r'\b\d+\b', myString )][0] I want to have 12.5 as myFloat. Thank you -
How to Kill all Celery background proces
Killing all celery processes involves 'grep'ing on 'ps' command and run kill command on all PID. Greping on ps command results in showing up self process info of grep command. In order to skip that PID, 'grep -v grep' command is piplined which executes 'not' condition on 'grep' search key. The 'awk' command is used to filter only 2nd and 'tr' command translates result of 'awk' command output from rows to columns. Piplining 'kill' command did not work and so the entire process has been set as command substitution, i.e., '$()'. The redirection at the end is not mandatory. Its only to supress the enitre output into background. kill -9 $(ps aux | grep celery | grep -v grep | awk '{print $2}' | tr '\n' ' ') > /dev/null 2>&1 -
Get and use the value from foreign key field without any conversions (Django)
I tried to get the value from the foreign key field "tax" in "priceWithTax()", then finally, I could get the value with this code below: taxObject = self.tax This is the full code: "models.py": from django.db import models from decimal import Decimal class Tax(models.Model): tax = models.DecimalField( max_digits=3, decimal_places=0, validators=[ MaxValueValidator(100), MinValueValidator(0) ], ) class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=5, decimal_places=2) TAX_ID = 1 tax = models.ForeignKey( Tax, on_delete=models.PROTECT, default=TAX_ID, ) @property def priceWithTax(self): # Here taxObject = self.tax tax = Decimal(str(self.tax)) return round(self.price * ((tax + 100) / 100), 2) But to use the value, I needed to convert it to "String" type first and then "Decimal type" next which became a little bit long code as shown below: taxObject = self.tax tax = Decimal(str(self.tax)) # Here So, are there any ways to use the value from the foreign key field "tax" in "priceWithTax()" without any conversions? -
needs to have a value for field "id" before this many-to-many relationship can be used
I have this error (needs to have a value for field "id" before this many-to-many relationship can be used.). I don't know how to fix it. I use Many-to-Many relationship for coauthor field which related with CustomUser. Also each coauthor have Profile. So I want that I can use coauthor by link in template to profile. Models.py class ArticleExample(models.Model): author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True ) coauthor = models.ManyToManyField( get_user_model(), blank=True, related_name="coauthor") title = models.CharField(max_length=150) text = models.CharField(max_length=150) views.py class ArticleExampleCreateView(CreateView): form_class = ArticleExampleForm model = ArticleExample template_name = 'example/articlecreateveiw.html' def form_valid(self, form): form.instance.author = self.request.user return super(ArticleExampleCreateView, self).form_valid(form) def post(self, request, * args, **kwargs): form = self.get_form() if form.is_valid(): obj = form.save(commit=False) obj.author = self.request.user obj.save() form.save_m2m() return redirect('/') return self.render_to_response({'form': form}) Also it's my customuser and profile models class CustomUser(AbstractUser): date_birthday = models.DateTimeField( default=timezone.now, blank=True, null=True) class Profile(models.Model): slug = models.SlugField(unique=True) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) bio = models.TextField(null=False, blank=True) -
What is difference between Array and List in Python?
I'm new in Python. But I'm little confused about array and string. Some questions that i want to ask are. major difference which is best and why which one developers use mostly in projects. -
Celery tasks stopped running in Django app deployed using Heroku
We have a Django website deployed on Heroku (free plan) with a specific app for web crawlers that uses Celery and Redis. This app has celery tasks that add entries in our Postgres DB. Everything worked fine until a couple days ago when we updated some models and migrations from another unrelated app and suddenly all tasks stopped running (periodic tasks are registered, but don't run). The whole site is connected to Sentry and we didn't receive any error flags. We haven't changed anything in important files (such as settings, production config, requirements, tasks or procfile). Everything works fine locally. We have tried several things like excluding all registered tasks from the Django admin and putting them again. Testing different times. Rolling back to a few weeks ago, before our migrations, to see if the tasks ran... But nothing seems to work and we are feeling a little desperate since without the workers we are being forced to manually scrape several websites. We believe that the problem lies in the initalization of celery beat, and a log is provided here. Django admin: django admin for periodic tasks Procfile: release: python manage.py migrate web: newrelic-admin run-program gunicorn config.wsgi:application worker: newrelic-admin run-program …