Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Possible concurrent writing of csv file by pandas
My Python function, which uses the pandas library, is currently reading from a csv file and writing back to the same csv file. Because this function may be called by multiple users who are using my Django web app, is there a possibility of errors if those users all call my function at the same time? The amount of data per user is simply a single row of 3-4 columns, so I expect the probability of simultaneous execution to not be significant if the read/write operation only takes a few milliseconds. If there will be errors, imagine 1 million users on my app, how do I mitigate this? -
Static files django
I'm starting learn Django and I stop on one thing - static files. I tried like its below make changes in seetings and html but it doesnt load on the website. Please help me ! **settings.py:** STATIC_ROOT = '/PycharmProjects/django_kurs/filmyweb/static/' STATIC_URL = '/static/' STATICFILES_DIRS = ['django_kurs/filmyweb/static/',] **filmy.html:** {% load static %} <!doctype html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1"> <title>Document</title> <link rel="stylesheet" href="{% static 'moj.css' %}"> </head> Thank You in advance ! -
Django ForeinKey in template
I'm building a multivendor in django. I have a general Merchant table and products table. How can i use the merchant shop name in product template. models.py class Merchant(models.Model): shop_name=models.CharField(max_length=100) shop_address=models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=255, unique=True) merchant=models.ManyToManyField(Merchant) details.html {{product.name}} {{product.brand}} {{product.category__shop_name}} the shop_name is not appearing in the template. thanks beforhand. -
Django test client gives 404 when trying to get a public file from google cloud storage. Works fine when using requests lib
I have a public file on cloudstorage with public url = https://storage.googleapis.com/xyz/abc.pdf import requests requests.get(url) # gives status_code=200 But in django test, following gives 404 error: self.client.get(url) # status_code=404 -
Django - rating system database design
I'm trying to implement rating system for my Django app and got a little stuck on designing database for this. I haven't really used ManyToMany field until now, so I'm not really sure if it makes sense. And also when it comes to actual rating, I would just like to increment good/medium/bad by 1 and then just display, for example, good: 20x Could someone provide feedback on this? class Ratings(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ratings_from = models.ManyToManyField(User, related_name='ratings_from') book = models.ForeignKey(Book, on_delete=models.CASCADE) good = models.IntegerField(null=True, blank=True) medium = models.IntegerField(null=True, blank=True) bad = models.IntegerField(null=True, blank=True) comment = models.CharField(max_length=300)``` -
convert datetime to local in Django
In my postgresql db my datetime are stored as the following format: >>> p.publish datetime.datetime(2020, 12, 6, 6, 19, 36, 269492, tzinfo=<UTC>) now I want to display times locally using {% load tz %} {{ post.publish|local }} nothing happens. Then I tried to do it in the shell: pytz.utc.localize(p.publish,is_dst=None).astimezone(local_timezone) which gives me the following error: ValueError: Not naive datetime (tzinfo is already set) so my question is why it cannot convert timedate when tzinfo is already set, and how to get around it. Is it not the whole point to store data in data base with a certain timezone(here UTC) and then display it in different time zones when required? am I missing something here? -
User model costomization errors in django
I'm working in an app where I need to create multiple types of users with different permissions and hierarchy, but I get an errors about the models that I used. this is my models definition in models.py #models.py from django.db import models from django.contrib.gis.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.gis.db import models as gis_models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import EmployeeManager class Employee(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=128, blank=True) last_name = models.CharField(max_length=128, blank=True) registration_number = models.PositiveSmallIntegerField(unique=True, blank=False, null=False) email = models.EmailField() cni = models.CharField(max_length=18, blank=True) picture = models.ImageField(upload_to='DriversPictures/', max_length=100, blank=True) matricule_cnss = models.PositiveIntegerField(blank=True) driving_licence = models.PositiveIntegerField(blank=True) recruitment_date = models.DateField(auto_now=False, auto_now_add=False, blank=True) phone = PhoneNumberField(blank=True, help_text='numéro de telephone') adress = models.CharField(max_length=128, blank=True) city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL) region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL) is_exploitation_admin = models.BooleanField(default=False) is_supervisor = models.BooleanField(default=False) is_controlor = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) is_active = models.BooleanField(default=True) vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL) USERNAME_FIELD = 'registration_number' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = EmployeeManager() def __str__(self): return (self.registration_number, self.first_name, self.last_name) class Supervisor(Employee): zone_name = models.CharField(max_length=128, blank=True) class Driver(Employee): supervisor_id = models.ForeignKey('Supervisor', blank=True, null=True, on_delete=models.SET_NULL) class Controlor(Employee): supervisor_id = models.ForeignKey('Supervisor', blank=True, null=True, on_delete=models.SET_NULL) gaz_station_id = models.ForeignKey('GazStation', blank=True, null=True, on_delete=models.SET_NULL) class Vehicle(models.Model): serie = models.PositiveSmallIntegerField(unique=True, blank=True) matricule = models.CharField(max_length=18, … -
how to join two forms details using username as primarykey?
My forms.py looks like this:- class cust_login(forms.Form): Username = forms.CharField() Firstname = forms.CharField() Lastname = forms.CharField() Email_adress = forms.EmailField(widget=forms.EmailInput) Password = forms.CharField(widget=forms.PasswordInput) Password_Again = forms.CharField(widget=forms.PasswordInput) class Cust_address_details(forms.ModelForm): class Meta(): model = Cust_addres fields = ['Phone_no','house_no','building_name','street','area','city','state','pincode'] I want the Username to be unique and it should be the primary key connecting the two forms. So, that later on when I want to check the customer details. I only need to type the Username of the customer. my models.Py looks like class Cust_detail(models.Model): Firstname = models.CharField(max_length=30) Lastname = models.CharField(max_length=30) signup_Username = models.EmailField(max_length=40) signup_Password = models.CharField(max_length=15) class Cust_addres(models.Model): Phone_no = models.CharField(max_length=10) house_no = models.CharField(max_length=50) building_name = models.CharField(max_length=50) street = models.CharField(max_length=50) area = models.CharField(max_length=30) city = models.CharField(max_length=30) state = models.CharField(max_length=30) pincode = models.CharField(max_length=6) Please help me out I'm stuck on this for a few days. -
Django TinyMCE adding custom style formats
I would like to add a custom style format to the TinyMCE editor on my Python Django website, so I can set a block of text to have a custom CSS class. I am looking at the TinyMCE documentation on style_formats and have found this javascript snippet. How do I write this in Python so I can add this to my TINYMCE_DEFAULT_CONFIG? tinymce.init({ selector: 'textarea', style_formats: [ // Adds a h1 format to style_formats that applies a class of heading { title: 'My heading', block: 'h1', classes: 'heading' } ] }); -
Why am I getting pymongo ServerSelectionTimeoutError?
This is a small Django project using MongoDB as a database running with Docker. I am getting a pymongo ServerSelectionTimeoutError. docker-compose.yml I tried finding the solution with mongo shell using docker exec -it container_id bash but everthing seems fine in there. Command I use to start mongo shell inside a running container is mongo -u signals -p insecure I also tried to connect to this database using MongoDB Compass and it worked. I am able to connect to MongoDB Compass. Connection string is mongodb://signals:insecure@localhost:27017/webform. I am able to see all the collections in MongoDB Compass but my Django application is not able to connect with database. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'kv2ischvghz-st=13_-=1d=8ffpjsb_pi*9n%agi)k8w*g+70)' DEBUG = True ALLOWED_HOSTS = ['*'] APPEND_SLASH=False # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'WebForm.signals', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'WebForm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'WebForm.wsgi.application' # Database … -
Django Apache2 - Target WSGI script cannot be loaded as Python module error - mod-wsgi
i'm trying to deploy a website on VPS. Before everything, i was having python version problem. The problem was not let me to install up to date Django version. I contacted support and they did updated python version to 3.7. After setting module installations, i did some test on port 8000 with venv and app was working. After the test, i did setup up Apache2. Right now it showing 500 Internal Server Error. I believe this is python version error I'll be so grateful and happy if you help me. Please feel free to ask me anything The Os: Distributor ID: Ubuntu Description: Ubuntu 16.04.7 LTS Release: 16.04 Codename: xenial Apache2 Error log sudo tail -f /var/log/apache2/error.log [Sun Dec 06 08:31:42.487403 2020] [core:notice] [pid 907:tid 139908822431616] AH00094: Command line: '/usr/sbin/apache2' [Sun Dec 06 08:31:55.848991 2020] [mpm_event:notice] [pid 907:tid 139908822431616] AH00493: SIGUSR1 received. Doing graceful restart [Sun Dec 06 08:31:55.914428 2020] [mpm_event:notice] [pid 907:tid 139908822431616] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations [Sun Dec 06 08:31:55.914470 2020] [core:notice] [pid 907:tid 139908822431616] AH00094: Command line: '/usr/sbin/apache2' [Sun Dec 06 08:32:09.945999 2020] [wsgi:error] [pid 1009:tid 139908701574912] [remote 46.1.174.214:0] mod_wsgi (pid=1009): Target WSGI script '/home/alpcusta/diricangrup/diricangrup/wsgi.py' cannot be loaded as Python module. … -
How to check and see if an output contains the desired elements from any list or not?
I am trying to write tests for a particular app in django using the python's unittest library. def test_permissions_for_admin(self): admin = Group.objects.get(name='Administrator') permisisons = admin.permissions.all() admin_permissions = ['add_ipaddress', 'change_ipaddress', 'delete_ipaddress', 'view_ipaddress', 'add_subnet', 'change_subnet', 'delete_subnet', 'view_subnet'] for p in permissions: print(p.codename) for p in permissions: self.assertIn(p.codename, admin_permissions) The Above code prints this, OUTPUT: change_emailaddress delete_emailaddress view_emailaddress add_ipaddress change_ipaddress delete_ipaddress view_ipaddress add_subnet change_subnet delete_subnet view_subnet view_group change_organization change_organizationowner add_organizationuser change_organizationuser delete_organizationuser view_organizationuser add_user change_user delete_user view_user Whereas What I am trying to check is that, all the permissions present from the variable admin_permissions are present in this output or not. I have tried using the assertIn, assertEqual, & assertTrue methods but it doesn't seem to work here. Is there anything else I could look for or any method present which I am not aware of to solve such kind of issues. -
Removing a string character in list Python
I have the data in a dictionary format, as below; i want to remove the '" 'character in list. how can i achieve that? Any help, would be much appreciated. { "test2": [ [ "'testdesc...', ' fdfd', ' dsgdgdfgdfg'" ] ] } I tried something like this in my views, but it won't reflect any changes. views.py : for record in data: test_list = [] test_list.append(record['description']) record['test2'] = [x.split(' " ') for x in test_list] -
How to get the total number of Likes related to an Author and user it to send notifications when reaching a certain number
I have a notification system in my Django project, when a user likes a Post the author of the post receives a notification that a post is liked and when this like is unliked the notification is deleted. Now I am trying to add a functionality in the notification system to get the total number of likes for all the posts created by an author and send a notification to the author when the total of likes reaches a certain number, instead I set a function that when a post reaches a certain number of likes a notification is sent. I have been trying to accomplish this but I am getting several errors. I am going to comment on my trials so in the below codes. As per the last trial I have made I am receiving: TypeError: total_likes_received() takes 1 positional argument but 2 were given Here is the Post model class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='author') num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the Like model class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) def total_likes_received(self): return self.filter(post__author=Post.author).count() #The number of Likes received … -
calculate signal after first calculate signal is done
i have two signals, first calculate total per line and second is total of all lines. with the example i have now, first only do correct, second one = 0. until i update the invoice for example, then it s updated too. i want to start first one then automaticaly second one do the job correctly. def invoiceitem_pre_save(sender, instance, *args, **kwargs): instance.calculate(save=False) print('invoiceitem saved') pre_save.connect(invoiceitem_pre_save, sender=InvoiceItem) def invoice_pre_save(sender, instance, *args, **kwargs): instance.calcul(save=False) print('invoice saved') pre_save.connect(invoice_pre_save, sender=Invoice) -
Django-mptt not listing names in templates
i am using django-mptt library to build a category tree. when i put the code below in my template i get this error. index.html {% load mptt_tags %}{% load mptt_tags %} <ul class="root"> {% recursetree nodes %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> this is the error i get. VariableDoesNotExist at / Failed lookup for key [nodes] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'listing': <TreeQuerySet [<Category: Clothes>, <Category: Children Clothes>, <Category: Mens Clothes>, <Category: Womens Clothes>, <Category: Electronics>, <Category: Foods>]>}] view.py def index(request): listing=Category.objects.all() context={ 'listing':listing } return render(request,'catalog/index.html',context) -
Django/Angular: Empty Object Being Sent
I am sending a request using angular, I tried setting the Content-Type to "application/json", it said- "unsupported media type", I changed it to "form-data", it stopped giving the error but the request results in an empty object even though when I console log the object before sending, it shows the correct JSON object. What could be going wrong? How do I fix it? I have two headers, since I am trying to send a file object as well, and for that I thought I'd use two requests, one only for the file and other for the rest since they might need different headers. Angular:- serivce.ts id : "" base_url = "http://127.0.0.1:8000/details/" create_url = this.base_url + 'create/' token = localStorage.getItem('token') httpHeaderNormal = new HttpHeaders({ 'Content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'Authorization': `Bearer: ${this.token}` }) httpHeaders = new HttpHeaders({ 'Content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'Authorization': `Bearer: ${this.token}` }); constructor(private http: HttpClient, private activatedRoute: ActivatedRoute, private injector: Injector) { }; getDetail(id: number): Observable<any> { console.log(id); return this.http.get(this.base_url + id + "/", { headers: this.httpHeaderNormal }) } updateDetail(detail, id, fileToUpload): Observable<any> { const endpoint = this.base_url + id + "/"; if (fileToUpload) { const formData: FormData = new FormData(); formData.append('logo', fileToUpload, fileToUpload.name); console.log(formData); this.http.put(endpoint, formData).subscribe( res => { console.log(res); … -
String model references must be of the form 'app_label.ModelName' error while adding a Foreign Key field to model
I have an app customer inside company/sales/ with app_label as 'company.sales.customer'. This app contains a model Customer in models.py. I want this model to be linked as a foreign key in another app 'orders'. models.py of 'orders': from django.db import models class Order(models.Model): party = models.ForeignKey('company.sales.customer.Customer', on_delete=models.CASCADE) --other fields-- apps.py of 'customer': from django.apps import AppConfig class CustomerConfig(AppConfig): name = 'company.sales.customer' label = 'company.sales.customer' settings.py : INSTALLED_APPS = [ ----, 'company.sales.customer' ] -
I cannot output the value of the foreign key via jsonresponse serealize
I want to get json serialized the name of the products insted of the id ones. I tried to add natural_keys method on the parent model with no luck. I can receive the json data good but in this way: [{"model": "ocompra.compradetail", "pk": 1, "fields": {"producto": 238, "precio": "620.00", "cantidad": 1}}, {"model": "ocompra.compradetail", "pk": 2, "fields": {"producto": 17, "precio": "65.00", "cantidad": 2}}] Any suggestions will be much appreciated! Thanks, views.py def detalle(request): template_name = "ocompra/compra_ok.html" contexto={} data={} if request.method=="GET": cat = CompraDetail.objects.all().order_by("codigo") contexto={"obj":cat} if request.method=="POST": codigos=request.POST.getlist("codigos[]")#Codigo/s de la Orden de Compra codigos= [int(x) for x in codigos]#Convierte la lista en integer items_detalle = CompraDetail.objects.filter(compra__in=codigos).select_related('producto') for item in items_detalle: print(item.producto.nombre, item.cantidad, item.precio, item.subtotal) #data['success'] = True #print (data) return JsonResponse(serializers.serialize('json', items_detalle,fields=('producto', 'cantidad','precio'), use_natural_foreign_keys=True), safe=False) #return JsonResponse(data) return render(request,template_name,contexto) models.py from django.db import models from django.utils.timezone import datetime from articulos.models import Articulos # Create your models here. class CompraHead(models.Model): numero=models.AutoField(primary_key=True) cliente= models.CharField(max_length=200,default="Consumidor Final") direccion=models.CharField(max_length=100,null=True,blank=True) telefono=models.CharField(max_length=50,null=True,blank=True) fecha=models.DateField(default=datetime.now) observaciones=models.CharField(max_length=400) subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2) descuento=models.IntegerField(default=0.0) total=models.DecimalField(default=0.00,max_digits=9,decimal_places=2) class CompraDetail(models.Model): compra=models.ForeignKey(CompraHead,on_delete=models.CASCADE) producto=models.ForeignKey(Articulos,on_delete=models.CASCADE) precio= models.DecimalField(max_digits=10,decimal_places=2) cantidad=models.IntegerField(default=0) subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2) def natural_key(self): return (self.producto.nombre) js var token = '{{csrf_token}}'; var data = JSON.stringify({"codigos":codigos}); data = {"codigos[]":codigos}; console.log(data); $.ajax({ headers: { "X-CSRFToken": token }, "url": '/ocompra/detalle/', "type": "POST", "dataType": "json", data: data, success: function(data){ // … -
object is not iterable error in Django Rest Framework
I am new to django rest framework, I am trying to build a simple movie API. I created 3 models Movie, Cast and Reviews, after applying migrations I added values in tables in django admin. When I start the server the api works fine until I again add values in Cast table or reviews table it gives me error like: "'Cast' object is not iterable". And its also not showing the Movie table data. What am I doing wrong. Here is My code: models.py from django.db import models # Create your models here. class Cast(models.Model): actor = models.CharField(max_length=225) producer = models.CharField(max_length=225) director = models.CharField(max_length=225) screenwriter = models.CharField(max_length=225) class Reviews(models.Model): name = models.CharField(max_length=225) comment = models.CharField(max_length=225) class Movies(models.Model): name = models.CharField(max_length=225) genre = models.CharField(max_length=225) ratings = models.IntegerField() cast = models.ForeignKey(Cast, on_delete=models.CASCADE) review = models.ForeignKey(Reviews, on_delete=models.CASCADE) serializer.py from .models import Movies, Reviews,Cast from rest_framework import serializers class CastSerializer(serializers.ModelSerializer): class Meta: model = Cast fields = ('actor', 'producer', 'director', 'screenwriter') class ReviewsSerializer(serializers.ModelSerializer): class Meta: model = Reviews fields = ('name', 'comment') class MoviesSerializer(serializers.ModelSerializer): cast = CastSerializer(many=True) review = ReviewsSerializer(many=True) class Meta: model = Movies fields = ('name', 'genre', 'ratings', 'cast' , 'review') views.py from django.shortcuts import get_object_or_404 from .serializers import MoviesSerializer, ReviewsSerializer, CastSerializer … -
Make multilevel nested list from csv in Python
I have a csv with the following row structure (9 columns): Nr - A1 x - A1 y - A2 x - A2 y - B1 x - B1 y - B2 x - B2 y see also Picture: Picture of csv structure What I need is to read this file into an array that has a 3 level hierarchy like this: [[[A1 x, A1 y],[A2 x, A2 y]],[[B1 x, B1 y],[B2 x, B2 y]]] so that I can Shuffle the A-pairs within each other and the B-pairs within each other without removing their relationship to each other (so that there is always one y and one x, not tow xx and two yy). Shuffle all the order of A-pairs and B-pairs altogether without changing their inner structure (so that one time all the A-pairs start all B-pairs follow and one time the other way around). My current code to read in the csv is like that each row is read in and then I tried to make separate arrays out of that, but all of that resulted in way too much post processing of the retrieved values. I think, there might be a better way to read the csv … -
How to add a specefied number of characters in django form
so I am trying to build a django form for accepting orders for my ecommerce website. I want the user to enter their zip code, but it should be of only 6 characters, not more, not less. How can I achieve this? Here is my form so far: class OrderForm(forms.Form): name = forms.CharField(max_length=30) email = forms.EmailField() address = forms.CharField(widget=forms.Textarea()) zip_code = forms.CharField(max_length=6) The max_length attribute allows the user to enter less than 6 characters, which is not what I want. Any help would be appreciated. -
Reverse for 'bid' with no arguments not found. 1 pattern(s) tried: ['dasboard/orders/add/(?P<pk>[0-9]+)$']
I'm trying to set the the status of a model object to "Off" based on passed id, How do I achieve this. Here is my views.py def bid(request, id): if request.method == 'POST': bid = Order.objects.get(id=id) bid.status = "Off" # change field bid.save() return HttpResponseRedirect('/dashboard') urls.py path('dashboard/orders/add/<int:id>', bid, name='bid') html <a href="{% url 'order_detail' order.id %}" style="text-decoration: none; color:white;" class="orders_made"> -
How can I add a constraint to a Django model that forces two fields to match?
I need to add a constraint to my Company model that makes sure that if state is defined that country is also defined and that state__country matches country. My Models from django.db.models import F, Q class Country(models.Model): name = models.CharField(max_length=100, unique=True) abbr = models.CharField(max_length=3, unique=True) class State(models.Model): name = models.CharField(max_length=100, unique=True) abbr = models.CharField(max_length=2, unique=True) country = models.ForeignKey( Country, on_delete=models.PROTECT, to_field="abbr", default="US" ) class Company(models.Model): name = models.CharField(max_length=250, blank=True) state = models.ForeignKey( State, on_delete=models.SET_NULL, null=True, blank=True, related_name="companies", ) country = models.ForeignKey( Country, on_delete=models.SET_NULL, null=True, blank=True, related_name="companies", ) class Meta: constraints = [ models.CheckConstraint( # This causes an error: check=(Q(state__isnull=True) | Q(state__country=F("country"))), name="state_and_country_must_match", ), ] When I run the migration, I get the following error caused by Q(state__country=F("country")): django.core.exceptions.FieldError: Joined field references are not permitted in this query So, what's the correct way to write this? By the way, another option would be to for country to be None if state is defined, but I'd rather not do that as I'd like to be able to get all companies in a country using country.companies. -
save with signals on same model on django
I would like to merge these methods on figure_1 so i can get the figure_2 and use signals to save the results on the same model. something is wrong so results are not saved on the model figure_1 : class Invoice(models.Model): date = models.DateField(default=timezone.now) amount_gtotal = models.DecimalField(max_digits=20, decimal_places=2, default=0) amount_gtax = models.DecimalField(max_digits=20, decimal_places=2, default=0) amount_gamount = models.DecimalField(max_digits=20, decimal_places=2, default=0) def amount_gtotal(self): items = self.invoiceitem_set.all() amount_gtotal = 0.00 for item in items: amount_gtotal += item.price * item.quantity return amount_gtotal def amount_gtax(self): items = self.invoiceitem_set.all() amount_gtax = 0 for item in items: amount_gtax += item.price_sell * item.quantity * item.vat return amount_gtax def amount_gamount(self): amount_gamount = self.amount_gtotal() + self.amount_gtax() return amount_gamount figure_2 : def calculate(self): invoiceitems = self.invoiceitem_set.all() amount_gtotal = 0 amount_gtax = 0 amount_gamount = 0 for invoiceitem in invoiceitems: amount_gtotal += item.price * item.quantity amount_gtax += item.price_sell * item.quantity * item.vat amount_gamount += amount_gtotal + amount_gtax totals = { 'amount_gtotal': amount_gtotal, 'amount_gtax': amount_gtax, 'amount_gamount': amount_gamount, } for k,v in totals.items(): setattr(self, k, v) if save == True: self.save() return totals def invoice_pre_save(sender, instance, *args, **kwargs): instance.calculate() pre_save.connect(invoice_pre_save, sender=Invoice) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.PROTECT) price_sell = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) vat = models.DecimalField(max_digits=5, decimal_places=2) I …