Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Serializer Validator not working with allow_blank and read_only arguments
i have a serializer which has some_field = CharField(allow_null=False, allow_blank=False, read_only=True) The problem is that i do not get any errors if i try to serialize Serializer(data={'some_field': '').is_valid(raise_exception=True) or Null. What am i doing wrong? -
can i have two exact same models poiting to the same table on django?
trying to split a piece (called A) of a django monolith (called B) apart, i decided to add a new module to my monolith and move there all code related to A. In the future, this module would be extracted to a whole new system. both A and B uses class City(models.Model), so while i deal moving services and helpers, i wanted to have, inside A, a read-only city model to isolate A from anything related to B's city. while having B/some_path/city.py, i created a new model as A/another_path/city.py with this addition: class Meta: managed = False db_table = 'city' trying to check if everything was working, i noticed ./manage.py migrate would give me several errors like ?: (models.E030) index name 'city_column_name_index' is not unique among models: A.City, B.city. where city_column_name_index was declared inside a migration: migrations.AddIndex( model_name='city', index=models.Index(fields=['column_name'], name='city_column_name_index'), ), how should i have a copy of city model to use inside A without messing with B? -
Django GrahpQL ACL?
Is there a Django GraphQL ACL? Like you can't access the Query/Mutation if the user has no permission. For Example, the login user has a only permission on products Query/Mutation but no permission on human resources Query/Mutation. How can I return a error message like "Permission Denied!"? -
Create view to save data in django m2m parent and intermediate (through) table using a form and formset
I want to replicate the admin functionality shown in the screenshot below on the client side. This is app is meant to cost a recipe based on the ingredients and quantity. Find below some snippets of my code admin.py class RecipeIngredientInline(admin.TabularInline): model = RecipeIngredient extra=0 class RecipeAdmin(admin.ModelAdmin): inlines = [RecipeIngredientInline] admin.site.register(Recipe, RecipeAdmin) models.py class Ingredient(models.Model): ingredient_name = models.CharField(max_length=255) unit_of_measure = models.CharField(max_length=255) price = models.DecimalField(max_digits=20, decimal_places=2) units_size_in_package = models.DecimalField(max_digits=20, decimal_places=2) cost_per_unit = models.DecimalField(max_digits=20, decimal_places=2) supplier = models.CharField(max_length=255, null=True, blank=True) create_date = models.DateTimeField(auto_now_add=True, blank=True) edit_date = models.DateTimeField(auto_now=True, blank=True) class Recipe(models.Model): recipe_name = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True) product_category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, blank=True, null=True) ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient') is_vatable = models.BooleanField(default=False) VAT_percentage = models.PositiveIntegerField(blank=True, null=True) VAT = models.FloatField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True, blank=True) edit_date = models.DateTimeField(auto_now=True, blank=True) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, blank=True, null=True, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, blank=True, null=True, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=20, decimal_places=2) cost = models.FloatField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True, blank=True) edit_date = models.DateTimeField(auto_now=True, blank=True) forms.py class RecipeForm(forms.ModelForm): product_category = forms.ModelChoiceField(queryset=ProductCategory.objects.all()) class Meta: model = Recipe fields = ['recipe_name', 'description', 'photo', 'product_category', 'ingredients', 'is_vatable', 'VAT_percentage' ] widgets = { 'description': forms.Textarea( attrs={ 'rows': 4, } ), 'VAT_percentage': forms.NumberInput( attrs={ 'class': 'form-control', } ), } ) class … -
Internal server error 500 while sending data from react to Django rest framework
I am making a crop prediction system where user will send some data to backend and crop_prediction function will predict a crop and send it to frontend to display it. I checked my views.py function it is working properly on Django rest framework. But when sending data it is giving internal server error. Please suggest any modification in my code. My frontend code to send data async function userDataHandler(userData) { const response = await fetch("http://localhost:8000/Efarma/", { method: "POST", body: JSON.stringify(userData), headers: { "Content-Type": "application/json", }, }); const data = await response.json(); } Django views code:- from django.shortcuts import render from firebase import firebase import numpy as np # from rest_framework.parsers import JSONParses from django.views.decorators.csrf import csrf_exempt import pickle from efarma import config from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer from rest_framework import permissions from rest_framework.decorators import api_view, permission_classes def weather_fetch(city_name): """ Fetch and returns the temperature and humidity of a city :params: city_name :return: temperature, humidity """ api_key = config.weather_api_key base_url = "http://api.openweathermap.org/data/2.5/weather?" complete_url = base_url + "appid=" + api_key + "&q=" + city_name response = requests.get(complete_url) x = response.json() if x["cod"] != "404": y = x["main"] temperature = … -
Pytest coverage with django generates wrong result when run in parallel
When I run my testsuite with parallel executions I receive different results compared to run only one test runner. I tried two approaches and both did not provide proper results. These commands did either only produce one partial result or less than we had runners. I've tried with coverage and pytest combined: COVERAGE_PROCESS_START=./my_app coverage --parallel-mode --concurrency=multiprocessing run -m pytest -m "not e2e" -n 4 Also with pytest and pytest-cov: pytest -m "not e2e" -n 4 --cov=my_app The second one also had the issue that some templatetags were not seen as registered even though others in the same directory were registered. After running these I executed coverage combine and coverage report. When run in parallel the results are always incomplete compared to running it with only one test runner, which works perfectly fine: coverage run -m pytest -m "not e2e" This is my coveragerc: [run] include = my_app/* omit = *migrations*, *tests* plugins = django_coverage_plugin [report] show_missing = true Does some know how to get proper coverage results when running pytest in parallel? -
how to add an image through {{i.image}} to template in django?
In this template i want to put something like {{i.image}} instead of "{% static '3307209.jpg'%}" {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> </head> <body> {% for i in pr%} <div class='card'> <div class="number">{{i.number}}</div> <img src="{% static '3307209.jpg'%}"> <span class="prname">{{i.name}}</span> <p id="id">{{i.description}}</p> <button><span class="price"> ${{i.price}}</span> <img id='add'src="{% static 'add.png'%}"> Add to cart</button> </div> {%endfor%} </body> </html> So i have an image field in my models and my views are ready. to change an image inside my template from admin page i tried this but did not work: <img src={{i.image}}> How can i add an image to template from database? -
Custom function in Django's model
I have model and i want to add my custom function, and when i create object this function call automatically. this is my model and test function. it's only for testing i want when i create Like object after call test function class LikeManager(models.Manager): def create(self, *args, **kwargs): decrease = kwargs.pop("decrease") new_like = self.model(**kwargs) new_like.save(decrease=decrease) return new_like class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user")) question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question")) objects = LikeManager() #this function @property def test(self): print("Testing") return 1 def save(self, decrease, *args, **kwargs): if not self.pk: if decrease: self.question.save() else: self.question.point += 1 self.question.save() return super(Like, self).save(*args, **kwargs) -
How to save multiple objects at once to Django database
I'm trying to get form data using a POST request and save the form data to my database which was created using a django model named InfoModel. I'm getting the data from the POST request, but I don't know how to save all of it at once so that it all saves to the same row in the db. The way I'm doing it now, each object from the form saves to a different row of the database which is obviously not useful at all. I expect the answer is simple, but I haven't seen this in the docs. views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import InfoForm from .models import InfoModel # Create your views here. def home(request): if request.method == 'POST': #if POST request, validate the data form = InfoForm(request.POST) if form.is_valid(): #if the form is valid, collect the data, submit to db, and thank the user valid = True form_data = request.POST f = InfoModel(fname = form_data['fname']) f.save() l = InfoModel(lname = form_data['lname']) l.save() e = InfoModel(email = form_data['email']) e.save() p = InfoModel(phone = form_data['phone']) p.save() return render(request, 'form_db/home.html', {'form':form, 'valid':valid}) else: #if the form is invalid, populate the form with the entered … -
Django ManyToMany validation in model layer
I have model with manytomany field and the task is to make an validation in model layer. I did research and in every other cases they recommended to create validation in Form layer. But problem with this, is when i will create object in djangoadmin or with seeder, saved data can cause problems. So i decided to make validation in model layer. Here is my model: class Position(models.Model): pos_id = models.BigAutoField(primary_key = True) pos_name = models.CharField(max_length=80) level = models.IntegerField(default=1) def __str__(self) -> str: return self.pos_name class Meta: verbose_name = 'Position' verbose_name_plural = 'Positions' class Boss(models.Model): boss_id = models.BigAutoField(primary_key=True) boss_position = models.ForeignKey(Position, null=True, on_delete = CASCADE) subordinates = models.ManyToManyField(Position,related_name='bosses') def __str__(self) -> str: return self.boss_position.pos_name @property def position(self): return self.boss_position def clean(self) -> None: subordinates_list = self.subordinates.objects.all() if self.boss_position in subordinates_list: raise ValidationError(_('Boss cant be boss in his subordinate list')) class Meta: verbose_name = 'Boss' verbose_name_plural = 'Bosses' thanks in advance for your reply -
Why am I being referred to by http://127.0.0.1:8000/admin/login/?next=/admin/
I tried to go to the django admin panel, but when I enter a request for 127.0.0.1:8000/admin I am referred to http://127.0.0.1:8000/admin/login/?next=/admin/ and the screen is displayed this: "A server error occurred. Please contact the administrator." This is my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apple.apps.AppleConfig' ] TEMPLATES = [ { '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', ], }, 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, }, ] urls.py in project folder from django.contrib import admin from django.urls import path, include from apple.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', include("apple.urls")), ] P.S. I've done everything that's written in the documents of the django admin site, but it still doesn't work. -
How to hide fields that belong to the model I'm inheriting from in django admin panel
I have these 2 models in my models.py class Student(AbstractBaseUser): date_of_birth = models.DateField(null=True) phone_number = PhoneNumberField(null=True) class Teacher(Student): bio = models.TextField(null=True) image = CompressedImageField(null=True, blank=True, default="default.png") student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) Now in admin panel when i go to edit the Teacher instance I display only bio image and student. The issue is that also display those fields when I try to edit Teacher instance but entering from Student model. So is there a way for that? P.S the models and fields may not make sense because they are examples. -
how to persist sqlite3 DB data in heroku django application
This app is a django web site. I inserted a record using django admin function from admin web page. After inserting, I closed the admin web page, and I could see the record shown on the normal web page. But after one hour later, the record disappeared (I could not see in my normal web page and admin web page when I browsed again.). I upgraded this app(c9-django-mblog-ho) and another app(django-mblog-ho) from heroku-16 to heroku-20 yesterday(2022-4-19 08:00 UTC+8 Asia Taipei time). Both app have the same problem. I did not have the problem on heroku-16 stack. Please help me to solve the problem: Keep sqlite3 DB data persistent! Thank you very much! -
TypeError: module() takes at most 2 arguments (3 given) Django manage.py runserver
I tried running manage.py runserver manage.py makemigrations and manage.py migrate but they all give me a TypeError The error is Traceback (most recent call last): File "/Users/William/Documents/Start over/Simple/perputer/manage.py", line 22, in <module> main() File "/Users/William/Documents/Start over/Simple/perputer/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/William/Documents/Start over/Simple/env/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/William/Documents/Start over/Simple/perputer/words/models.py", line 4, in <module> class Word(models): TypeError: module() takes at most 2 arguments (3 given) I haven't changed my manage.py and my models.py that's causing the error: from django.db import models # Create your models here. class Word(models): <-- error word = models.CharField(max_length = 26) meaning = models.TextField(help_text = "A definition for the word attached to it.") language = models.CharField(max_length = "20", … -
How can i array to grid table in Django HTML?
I can send my model to the html page and bring it to the array structure, but I cannot integrate this array into the grid table. Does anyone know how I can do this? views.py def tests(request): resultQueryet = ResultsModel.objects.all() requests = serialize('json', resultQueryet) context = { "requests" : requests } return render(request, 'admin/tests.html', context=context) html {% block content %} <div class="card-body"> <div id="table-card" class="table-card"></div> </div> {% endblock %} {% block extra_js %} <script> var model = {{requests|safe}}; console.log(model) document.getElementById("table-card") && new gridjs.Grid({ columns: ["Name", "Surname", "Date", "Amount", "Result", "Details"], sort: !0, pagination: { limit: 5 }, data: [ [ {% for x in model %} {{x.name}}, {{x.surname}}, {{x.date}}, {{x.amount}}, {{x.result}}, {{x.details}}, {% endfor %} ], ], }).render(document.getElementById("table-card")) </script> <script src="{% static 'libs/prismjs/prism.js'%}"></script> <script src="{% static 'libs/gridjs/dist/gridjs.umd.js'%}"></script> <script src="{% static 'js/pages/gridjs.init.js'%}"></script> {% endblock extra_js %} I can view the model as array on the console screen, but I cannot print it to the table via a for loop. -
how to gather logs in django with aws autoscaling (ecs or beanstalk or simple autoscaling)
Im wondering if there is a feature in aws to gather logs of application such as django when autoscaling is enabled? Do I need to do it manually with bashscript and a storage or is it available in aws monitoring tools? Thanks a lot. Best, -
How to Configure a column not to visible by default in django admin
I want to hide one column and make the column visdible but if user want the user view the column, i tried this way but did not worked forr me. admin.py class ProductAdmin(TimestampedModelAdminMixin, ConfigurableColumnsMixin, admin.ModelAdmin): list_display = [ "id", "comment", "active", ] I tried with this way but did not worked. def get_form(self, request, obj=None, **kwargs): form = super(ProductAdmin, self).get_form(request, obj, **kwargs) del form.base_fields["comment"] return form -
Uploading a csv file and assigne it to the user - django
I want to create a project an I need to upload an csv file to an user, but from some reason, it's not loading correctly (is uploading for the first created user, and I try do to this from others accounts). In my view, I have something like this: def FileViewUpload(request): form = CsvFileForm(request.POST, request.FILES) print(request.user) userId = request.user.id print(userId) print(request.user.email) if form.is_valid(): form.save() form = CsvFileForm() obj= CsvFileModel.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: date = row[0] user = AccountUser.objects.get(contact_user = userId) print(user) ContactUser.objects.create( date=date, message= row[1] user=user, ) obj.activated=True obj.save() return render(request, 'uploadFile.html', { 'importFile': form }) For this lines: print(request.user) print(userId) print(request.user.email) it display the good thing, the correct id and email for that specific user. But when I press the button for upload, it's loading in the field for the first user created. The problem, I think that is in this line: user = AccountUser.objects.get(contact_user = userId), but I don't know why, if in the beginning, at the first prints, it's show me correctly. The model for ContactUser: class ContactUser(models.Model): user = models.ForeignKey(AccountUser, related_name='contact_user', on_delete=models.CASCADE) date = models.CharField() message = models.CharField() def __str__(self): return f"{self.user}" -
Django 3.2+: case-sensitive string comparisons within MySQL tables
Django documentation (3.2 to 4.0) states: In MySQL, a database table’s collation determines whether string comparisons (such as the expression and substring of this function) are case-sensitive. Comparisons are case-insensitive by default. from 3.2 on, there is mention that it is now possible to define at the level of the CharField the collation to use: https://docs.djangoproject.com/en/3.2/ref/databases/#collation-settings but I find nowhere what value I should use for db_collation to enable case-sensitive string comparisons for a given CharField: case_sensitive_collation = ??? name = models.CharField(max_length=50, db_collation=case_sensitive_collation) Just found this gist to do the contrary: CreateCollation and db_collation to implement a case-insensitive Charfield with Postgres > 12 https://gist.github.com/hleroy/2f3c6b00f284180da10ed9d20bf9240a can somebody help me out? -
how to display a nested list
I have a recursive table, of which I want to present the main elements and their sebelements id name parent order 1 Menu A 1 2 Menu B 2 3 Menu a 1 1 4 Menu b 2 1 5 Menu C 3 6 Menu D 4 7 Menu a 6 1 8 Menu b 6 2 And what I want to present respecting the order of the main Menu, and within each menu its submenu with the assigned order View menus = Menu.objects.values('id', 'name', 'icon', 'parent').filter(estado=1).order_by('order') I'm using the regroup tag but it doesn't even group it by parent I think the change must be in values but I can't find the solution TEMPLATE {% regroup menus by parent as menu_list %} {% for parent in menu_list %} {{parent.grouper}} {{parent.id}}, {{parent.name}} {% for submenu in parent.list %} {{submenu.id}}, {{submenu.name}} {% endfor %} {% endfor %} Desired result Menu A Menu a Menu B Menu b Menu C Menu D Menu a Menu b -
How can i use django template tag to view some thing that i have created in database?
When i create multiple product i can see my <div class='card'> content in browser. But i can not see the values that i have submited in my database fields. For example i have created a product in admin page with number of 1 since i have specified {{pr.number}} in my template. how can i see the values of database fields that i added in admin page in my templates? template: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> </head> <body> {% for i in pr%} <div class='card'> <div class="number">{{pr.number}}</div> <img src="{% static '3307209.jpg'%}"> <span class="prname">{{pr.name}}</span> <p id="id">{{pr.description}}</p> <button><span class="price"> {{pr.price}}</span> <img id='add'src="{% static 'add.png'%}"> Add to cart</button> </div> {%endfor%} </body> </html> models: from django.db import models # Create your models here. class product(models.Model): number=models.IntegerField() name=models.CharField(max_length=20) description=models.CharField(max_length=150) price=models.IntegerField() views: from django.shortcuts import render from .models import product # Create your views here. def a (request): db=product.objects.all() return render (request,'main page.html',{'pr':db}) -
ForeignKey and ManyToManyField in a list of all obejcts
Despite my consultation of the documentation I can't find my solution. I want to show in my templates the values linked by ManyToManyField and ForeignKey. I have this model: class Adresse(models.Model): libelle = models.fields.CharField(max_length=100) numero = models.fields.IntegerField(null=True) street = models.fields.CharField(max_length=100) code = models.fields.IntegerField(null=True) city = models.fields.CharField(max_length=100, null=True) country = models.ForeignKey(Country, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.libelle}' class Trip(models.Model): title = models.fields.CharField(max_length=100) traveller = models.ManyToManyField(Character) date_start = models.DateField(default=date.today) date_end = models.DateField(default=date.today) def __str__(self): return f'{self.title}' class Activity(models.Model): trip = models.ForeignKey(Trip, null=True, blank=True, on_delete=models.SET_NULL) adresse = models.ForeignKey(Adresse, null=True, blank=True, on_delete=models.SET_NULL) date_start = models.DateField(default=date.today) date_end = models.DateField(default=date.today) class Meta: verbose_name_plural = "Activities" and this view to display the total list of trips: from django.shortcuts import render # Create your views here. from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, redirect, render from travel.models import Trip, Adresse, Activity from profiles.models import Character @login_required def travel_list(request): travels = Trip.objects.all() travellers = Character.objects.all() template = 'travel/travel_list.html' context = { 'travels' : travels, 'travellers' : travellers, } return render(request, template, context) @login_required def travel_detail(request, travel_id): travel = get_object_or_404(Trip, id=travel_id) activities = Activity.objects.filter(trip_id=travel_id) travellers = travel.traveller.all().order_by("last_name", "first_name") template = 'travel/travel_detail.html' context = { 'travel': travel, 'activities' : activities, 'travellers' : travellers, } return render(request, template, context) et … -
Create Hierarchical Category Tree In Django
I have a large CSV (27k + rows) that I want to import into a model and from there create a hierarchical tree in a template. Example The child categories go up to 9 levels deep. I was thinking MPTT would maybe be the way to go because of the size of the dataset, but the tutorial doesn't talk about large imports and I can't extrapolate how to use their example in a large set. I'm not married to mptt, I'd be fine even doing this with multiple tables and somehow relate them like a many to one. That brings me to my question: How do you relate the child to the parent in a large set you can't hand type in? Category Screenshot mptt tutorial example from myapp.models import Genre rock = Genre.objects.create(name="Rock") blues = Genre.objects.create(name="Blues") Genre.objects.create(name="Hard Rock", parent=rock) Genre.objects.create(name="Pop Rock", parent=rock) Things I've Tried I know this is wrong on multiple levels. That is not a good use of time/space on a large set. def show_categories(request): categories = Categories.objects.all() parents = {} children = {} for cat in categories: if cat.cat_parent_id == 0: parents[cat.cat_name] = cat.category_id if cat.cat_parent_id > 0: children[cat.cat_name] = cat.cat_parent_id return render( request, "amazon_niche_finder/categories.html", { … -
Django How to fix UnboundLocalError in Models.py
I am getting the following error in models.py, "except Balance.DoesNotExist: UnboundLocalError: local variable 'Balance' referenced before assignment". How can I fix this error? I am trying to create a book keeping website. I have created three classes within my models.py file Models.py class Residents(models.Model): house_number = models.CharField(max_length=100,unique=True,primary_key=True) name = models.CharField(max_length=100) contact_number = PhoneNumberField() def __str__(self): return self.house_number + " " + self.name class Balance(models.Model): primary_key=True) residents = models.OneToOneField(Residents, on_delete=models.CASCADE, primary_key=True) date = models.DateTimeField(default=timezone.now) previous_balance = models.DecimalField(max_digits=1000, decimal_places=2 , null=True) transaction = models.DecimalField(max_digits=1000, decimal_places=2, null=True) def save(self, *args, **kwargs): current_balance = self.previous_balance + self.transaction class Transaction(models.Model): transaction_id = models.CharField(primary_key=True,max_length=100,unique=True) residents = models.ForeignKey(Residents, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) updated = models.DateTimeField(auto_now=True) transaction_Amount = models.DecimalField(max_digits=1000, decimal_places=2) date = models.DateTimeField() def save(self, *args, **kwargs): if self.created is None: self.created = timezone.now() try: last_bal = Balance.objects.filter(pk = self.residents).get() except Balance.DoesNotExist: Balance, Created = Balance.objects.update_or_create(residents = self.residents,date=datetime.date.today(), previouse_balance=last_bal.current_balance, transaction=self.transaction_Amount) else: Balance.objects.create(residents = self.residents, date=datetime.date.today(), previouse_balance=0.00, transaction=0.00) Whenever a new transaction is made I would like the system to first check if the resident have made a transaction yet, if the resident did I would like to update the balance ,else create a new Balance Error except Balance.DoesNotExist: UnboundLocalError: local variable 'Balance' referenced before assignment -
Django: list object is not callable in forms.py
I’m trying to add a RegexValidator validator to a contact form (forms.py) to prevent spammers from adding http:// and https:// links in the message. I’ve included from django.core.validators import RegexValidator at the top of forms.py. This example of general_message works fine when not using the validator: general_message = forms.CharField(label='General message*', required=True, widget=forms.Textarea( attrs={'class': 'form-control', 'maxlength': '1000', 'rows': 8} )) But I get the error 'list’ object is not callable in the example below: general_message = forms.CharField(label='General message*', required=True, widget=forms.Textarea, validators=[RegexValidator(regex=r'http(s)?|HTTP(s)?', message="No http or https allowed", code="invalid")] ( attrs={'class': 'form-control', 'maxlength': '1000', 'rows': 8} )) It appears I have my brackets and parentheses correct. What causes the error?