Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to set all methods in a class as being in an atomic transaction in Django?
While using the custom action method of ViewSet in Django, I separated some business logics into another class, of which name is BusinessService. The BusinessService class can be used from many other methods, and after some analysis, I found all methods (more than 5) in the class should be in an atomic transaction. So the easiest but repetitive way might be adding @transaction.atomic decorator above the name of the methods, but as a way to follow the DRY principle, I was struggling to remove the redundant repetitions, but couldn't make it in a simple way. Is there any to make a whole class in an atomic transaction? Till now, I tried attaching @transaction.atomic above the name of a class, but, of course, had no success, so I analyzed the decorator, and found out the Atomic class which uses __enter__ and __exit__ for transaction management, which requires with or additional something. -
Whats the most efficient way to get all related models in a tree-like structure in django?
I have this model structure: models.py class Region(models.Model): code = models.CharField(max_length=10, unique=True, verbose_name=_('code')) name = models.CharField(max_length=255, verbose_name=_('name')) class Province(models.Model): code = models.CharField(max_length=10, unique=True, verbose_name=_('Code')) name = models.CharField(max_length=255, verbose_name=_('Name')) parent_region = models.ForeignKey('Region', on_delete=models.CASCADE, related_name='province', verbose_name=_('Regione')) class City(models.Model): code = models.CharField(max_length=10, unique=True, verbose_name=_('Code')) name = models.CharField(max_length=255, verbose_name=_('Name')) parent_province = models.ForeignKey('Province', on_delete=models.CASCADE, related_name='city', verbose_name=_('Region')) class CustomArea(models.Model): cities = models.ManyToManyField("City", verbose_name=_("Cities"), blank=True, related_name="in_area") provinces = models.ManyToManyField("Province", verbose_name=_("Provinces"), blank=True, related_name="in_area") regions = models.ManyToManyField("Region", verbose_name=_("Regions"), blank=True, related_name="in_area") I want to write a method for CustomArea model that returns a queryset with all the single City element in it. this is what I came up with: def list_cities(self): pks_provinces= self.provinces.all().values_list('id', flat=True) pks_regions= self.regions.all().values_list('id', flat=True) comuni = City.objects.filter(provincia__pk__in=pks_provinces).values_list('id', flat=True) | City.objects.filter(provincia__regione__pk__in=pks_regions).values_list('id', flat=True) | self.cities.all().values_list('id', flat=True) return comuni.distinct() Is this efficent enough? How can I improve this query to have all the single City element? -
Use template tags within a TextField
How to load a template tag within object that is retrieved from the models. email = models.TextField() Saved to model: this is a texts with a {{ test }} In my view i return: test = 'test' email_db = someclass.objects.get(pk=1) email_text = email_db.email return render(request, 'somepage.html', {'test':test, 'email_text':email_text}) somepage.html: {{ email_text }} outcome: this is a texts with a {{ test }} Is there a quick solution herefore ? thnx! -
TemplateSyntaxError at /AR Could not parse the remainder: '="AR"' from '="AR"'
I am trying to check if the language is == to AR to get a specific value from db and this is what I get: Internal Server Error: /AR Traceback (most recent call last): File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/smartif.py", line 175, in translate_token op = OPERATORS[token] KeyError: '="AR"' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/miryamelliye/development/spa/spa/frontend/views.py", line 10, in home return render(request, 'frontend/home.html', context) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/loader.py", line 15, in get_template return engine.get_template(template_name) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/loaders/base.py", line 30, in get_template contents, origin, origin.template_name, self.engine, File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 155, in init self.nodelist = self.compile_nodelist() File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 193, in compile_nodelist return parser.parse() File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 478, in parse raise self.error(token, e) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 476, in parse compiled_result = compile_func(self, token) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/defaulttags.py", line 964, in do_if … -
Django - How can I remove an html attribute from a Django widget?
I'm styling a search page in a Django project. I want to remove a single boolean attribute from the <select> tag generated by a ManyToManyField. The widget generated by Django looks like this: and I want it to look like this: I can get that result by inspecting the element in Firefox and simply changing <select id="id_regions" name="regions" multiple=""> to <select id="id_regions" name="regions"> Normally if you want a standard dropdown in Django, you would use a CharField in your model and set the choices to a list of tuples. We already do that in another place. However this is for work, and I don't want to change the relations in the database just for the sake of pretty frontend. This is the form in question: class ProviderFilter(django_filters.FilterSet): text = CharFilter(field_name="name", lookup_expr='icontains') class Meta: model = Provider fields = [ "regions", "themes", "sexes" ] The ManyToManyField called "regions", which I want to change the appearance of, comes from the model Provider and looks like this: class Provider(BaseModel): # Many fields omitted for brevity regions = models.ManyToManyField(Region, blank=True) and uses this class: class Region(BaseModel): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name Not sure if it's necessary, but here is a part … -
got an unexpected keyword argument 'update_fields', User needs to have a value for field "id" before this many-to-many relationship can be used
My models.py: class Source(models.Model): title = models.CharField(max_length=300) users = models.ManyToManyField(User, blank=True) def __str__(self): return self.title class Headline(models.Model): title = models.CharField(max_length=300) slug = models.SlugField(max_length=200, unique=True) content = models.TextField(default="") created_date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name='like', blank=True) dislikes = models.ManyToManyField(User, related_name='dislike', blank=True) lols = models.ManyToManyField(User, related_name='lol', blank=True) saves = models.ManyToManyField(User, related_name='save', blank=True) bearishes = models.ManyToManyField(User, related_name='bearish', blank=True) importants = models.ManyToManyField(User, related_name='important', blank=True) toxics = models.ManyToManyField(User, related_name='toxic', blank=True) source = models.ForeignKey(Source, on_delete=models.CASCADE) def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey(User, related_name='author', on_delete=models.CASCADE, blank=True, null=True) comment = models.TextField() newspost = models.ForeignKey(Headline, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return f"{self.author}" When I add a few ManyToMany field related to User model, it causes error when login/register/etc. These errors: File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1584, in _changeform_view self.save_model(request, new_object, form, not add) File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1097, in save_model obj.save() File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 536, in get return self.related_manager_cls(instance) File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 853, in init (instance, self.pk_field_names[self.source_field_name])) ValueError: "<User: test>" needs to have a value for field "id" before this many-to-many relationship can be used. What's wrong? -
installing gdk-pixbuf on Elastic Beanstalk v2
I am trying to get Django-Weasyprint working correctly on an AWS Linux2 Elastic Beanstalk instance. I have come across [this question][1] and when I add the code to .platform/hooks/predeploy the images all work but the href links stop working. I have, therefore, tried to upgrade the packages within the script and my script now looks like: #!/usr/bin/env bash yum install -y libxml2-devel libxslt-devel python-devel redhat-rpm-config libffi-devel cairo pango export PKG_CONFIG_PATH=/usr/lib64/pkgconfig:/usr/lib/pkgconfig export PATH=/usr/bin:$PATH export LDFLAGS=-L/usr/lib64:/usr/lib export LD_LIBRARY_PATH=/usr/lib64:/usr/lib export CPPFLAGS=-I/usr/include sudo yum-config-manager --enable epel sudo yum update -y sudo yum install -y gcc gcc-c++ glib2-devel.x86_64 libxml2-devel.x86_64 libpng-devel.x86_64 \ libjpeg-turbo-devel.x86_64 gobject-introspection.x86_64 gobject-introspection-devel.x86_64 wget http://ftp.gnome.org/pub/GNOME/sources/libcroco/0.6/libcroco-0.6.13.tar.xz tar xvfJ libcroco-0.6.13.tar.xz cd libcroco-0.6.13 ./configure --prefix=/usr make sudo make install cd .. wget http://ftp.gnome.org/pub/GNOME/sources/gdk-pixbuf/2.42/gdk-pixbuf-2.42.6.tar.xz tar xvfJ gdk-pixbuf-2.42.6.tar.xz cd gdk-pixbuf-2.42.6 ./configure --prefix=/usr --without-libtiff make sudo make install cd .. sudo yum install -y pixman-devel.x86_64 harfbuzz-devel.x86_64 freetype-devel.x86_64 wget http://www.freedesktop.org/software/fontconfig/release/fontconfig-2.13.93.tar.gz tar xvf fontconfig-2.13.93.tar.gz cd fontconfig-2.13.93 ./configure --prefix=/usr --enable-libxml2 make sudo make install cd .. wget http://cairographics.org/releases/cairo-1.16.0.tar.xz tar xvfJ cairo-1.16.0.tar.xz cd cairo-1.16.0 ./configure --prefix=/usr make sudo make install cd .. wget http://ftp.gnome.org/pub/GNOME/sources/pango/1.48/pango-1.48.4.tar.xz tar xvfJ pango-1.48.4.tar.xz cd pango-1.48.4 ./configure --prefix=/usr make sudo make install cd .. wget http://ftp.gnome.org/pub/GNOME/sources/librsvg/2.50/librsvg-2.50.5.tar.xz tar xvfJ librsvg-2.50.5.tar.xz cd librsvg-2.50.5 ./configure --prefix=/usr make sudo make install cd .. sudo ldconfig … -
Wagtail / Using ListBlock without some atributes in mixin
My mixin class: class FeatureList(blocks.StructBlock): title = blocks.TextBlock(default=None, blank=True, null=True) description = blocks.ListBlock(blocks.TextBlock(default=None, blank=True, null=True)) button_label = blocks.TextBlock(required=False, default=None, blank=True, null=True) button_url = blocks.URLBlock(required=False) and my models class ThreeListsBlock(DefaultFields, ThemeChooser, blocks.StructBlock): class Meta: icon = 'grip' tiles = blocks.ListBlock(FeatureList(), required=True) How can i use in ThreeListsBlock attributes from FeatureList() without button_url and button_label? I dont want creating copy FeatureList mixin. I want see in ThreeListsBlock only title and description. Thanks -
django rest framework serializer saving field value as empty strings, but no errors
django rest framework serializer saving field value as empty strings, but no errors views.py from django.shortcuts import render from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from .models import MyTodo from .serializers import MyTodoSerializer class MyTodoView(viewsets.ModelViewSet): queryset = MyTodo.objects.all() serializer_class = MyTodoSerializer and my model is models.py from django.db import models # Create your models here. class MyTodo(models.Model): # Autoincrement id id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, blank=True, default='') description = models.CharField(max_length=20, blank=True, default='') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title and my serializer is serializers.py from rest_framework import serializers from mytodo.models import MyTodo class MyTodoSerializer( serializers.ModelSerializer ): title = serializers.CharField(max_length=200, default='') description = serializers.CharField(max_length=200, default='') created_on = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False) def create(self, validated_data): return MyTodo.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.created_on = validated_data.get('created_on', instance.created_on ) instance.save() return instance class Meta: model = MyTodo fields = [ 'id','url','title','description', 'created_on' ] Looks pretty simple, straight forward but by CURL calls are saving empty fields, but Browsable API View is working very fine. Please tell me what am I doing wrong. Here is what I am trying to do Curl Client #!/bin/bash b64credential=$(echo 'admin:admin' | base64) access_token=$(curl -d "username=admin&password=admin" -X POST 'http://localhost:8000/api/token/' \ -H 'Accept:application/json' \ … -
Can i customise my crispy form in template?
I need to add after every label tag which will be button to enable input, so can i somehow do that in template? so can i turn this <form method="POST" action="/guide_register/" class="guide_register col-md-4"> {% csrf_token %} {%crispy form%} </form> into something like this <form action="/profile/" method="POST"> {% csrf_token %} {% for field in form %} <div class="form-row"> {{field.label_tag}} <i class="fas fa-pen"></i> {{field}} </div> {% endfor %} <br> <div class="form-row"> <input type="submit" value="Підтвердити" class="btn btn-primary"> <input type="reset" class=" btn btn-secondary" value="Відмінити"> </div> </form> but with crispy -
How to create database Structure Like Amazon Prime / Netflix / Hotstart in Django (ORM)
I want to create model with this fields -Basic Data to store -- Image Banner / Video Banner -- Title -- Description -- Directors -- Starring -- Genres -- Subtitles -- Year -- Length -- Audio languages -- Video Link -- Episode 2 or Movie Part 2 Avaiable -Buttons -- Add Watchlist Button -- Download Button -- Play Button / Continue Watching (if Applicable) -- Share Buttons -- Feedback - Lower Content Tab -- Episodes (If Applicable) -- Related - Details -- Producers -- Studio Need a poster for every show or movies and a thumbnail for every video (if episode applicable) *If Episode 2 or Movie's part two available they should be linked. Easy Upgradable / Manageable Ideas -
saving model to database throw ValueError in django
I have two model employee and department. Employee has one to one connection with department like class Employee(models.Model): department = models.ForeignKey(to=Department, on_delete=models.CASCADE) but when I try to create object from rest request, it throws ValueError: Cannot assign "{'id': 1, 'name': 'wrewrwerwe'}": "Employee.department" must be a "Department" instance. -
ORM django , filtre by object.proprety
Im trying to get result from this view Here is the models -
Waiting list in Django
I am making a model for a training that has the fields below: class Training(models.Model): class Meta: verbose_name = _("Training") registered = models.ManyToManyField(User, blank=True, null=True) waiting_list = models.ManyToManyField(User, blank=True, null=True) max_registered = models.models.PositiveSmallIntegerField() date = models.DateField(auto_now_add=False, auto_now=False) starting_time = models.TimeField(auto_now_add=False, auto_now=False) finishing_time = models.TimeField(auto_now_add=False, auto_now=False) My problem is to implement functionality for max registered participants to a training. When registered.count() == max_registered it should put users on the "waiting_list" instead of "registered". Any suggestions on how I should implement this? Is this something done in backend or frontend? Thanks in advance -
Show string if value is None in template
If a value is None I would like to show a - rather than rendering None in the table. However I get the following error: Could not parse the remainder: ' or '-'' from 'employee.full_name or '-'' I'd like to avoid doing a ton of if else statements if possible. Here's my code: {% for employee in employees %} <tr> <td>{{employee.full_name or '-'}}</td> <td>{{employee.position or '-'}}}</td> <td>{{employee.dob or '-'}}}</td> <td>{{employee.phone or '-'}}}</td> <td>{{employee.email or '-'}}}</td> <td>{{employee.address or '-'}}}</td> <td>{{employee.joined or '-'}}}</td> </tr> {% endfor %} The following Python code works as expected: dog = None print(dog or '-') -
How to pass JSON data through the Django backend to frontend view using Angular
I need a solution for this logic read the JSON files through Django backend, pass the data to the AngularJS frontend and populate the charts using the Google Charts library in the User Interface. Below is the structure of the barChart.json payload. { "chart_type": "bar", "x_data": ["primary School","None", "Phd","High School","Master"], "x_data": [29.817000007,41.25000,48.00000,187.00000,134.000000], "x_name": "education_level", "y_name": "city_development_index", "title": "city_develpoment_index group by education_level" } -
how to create a download api endpoint in djangorestframework for a csv file I am writing into after consuming data from a world weather online api's
I am consuming a weather api endpoint from HTTPS:https://api.worldweatheronline.com/premium/v1/weather.ashx and my views.py logic looks like this class HistoricalWeatherView(APIView): """Gets Historical Weather of a location""" def get(self, request, **kwargs): url = 'https://api.worldweatheronline.com/premium/v1/past-weather.ashx' param = request.query_params query_param = { 'key': 'my_api_key', 'q': param.get('location'), 'format': 'json', 'tp': 24, 'date': param.get('startdate'), 'enddate': param.get('enddate'), 'includelocation': 'yes' } weather_data = requests.get(url, params=query_param).json() output = len(weather_data['data']['weather']) final_weather = [] output_csv = 'historical_weather.csv' for result in range(output): final= { 'country': weather_data.get('data').get('nearest_area')[0].get('country')[0]['value'], 'areaName': weather_data.get('data').get('nearest_area')[0].get('areaName')[0]['value'], 'date': weather_data.get('data').get('weather')[result].get('date'), 'max_temperature': weather_data.get('data').get('weather')[result].get('maxtempC'), 'min_temperature': weather_data.get('data').get('weather')[result].get('mintempC'), 'indicator': weather_data.get('data').get('weather')[result].get('hourly')[0].get('weatherDesc')[0].get('value'), 'Humidity': weather_data.get('data').get('weather')[result].get('hourly')[0].get('humidity'), 'cloud_over': weather_data.get('data').get('weather')[result].get('hourly')[0].get('cloudcover'), 'windspeed': weather_data.get('data').get('weather')[result].get('hourly')[0].get('windspeedKmph'), 'precipitation': weather_data.get('data').get('weather')[result].get('hourly')[0].get('precipInches') } final_weather.append(final) df_weather = pd.DataFrame(final_weather) df_weather.to_csv(output_csv, index=False) return Response(final_weather, status=status.HTTP_200_OK) it generates the csv_file but I want to be able to create an endpoint where it can be downloaded to download folder localhost:8000/api/weather/history/download -
How to get value of {% url '...' %} programatically?
I would like to include the url of my DRF endpoint in the extra_context= field of my TemplateView so that I can pass it into my JS application in my template. I currently have it in my template, but it's just more convenient to store all the urls in the urls.py file. path('channel_bar', TemplateView.as_view( template_name='sales/bar_graph.html' extra_context={'dataUrl': reverse_lookup_drf_url('url-name')} ), name='sales.channel.bar'), and I don't know the Django name of the function reverse_lookup_drf_url(...) Tried searching "reverse lookup of template url tag programmatically" and a few permutations of it but didn't get any results. Anyone know the answer? I'm sure it's simple, just can't get a Google result. -
Allow end user to add / remove fields from model in Django
Please consider this situation: I've several clients on my website and each one can create employee from his dashboard. But each of them may want different fields in there form or user model. Example: Client_1 wants name, email, phone in there form Client_2 wants name, phone, address, and birth_date So from default form/model client should be able to remove unwanted fields and create his required fields. I Hope this can be done using Django or ContentTypes Please anyone knows then please provide detailed answer. It would be really helpfull. -
Django [Python], ImportError: cannot import name 'SimpleCookie' from partially initialized module 'django.http.cookie'
I have an M1 Apple Silicon Mac, and I am having some difficulty with my setup regarding Python version 3, specifically version 3.9.5. I also have Anaconda Navigator installed on my system. When I enter python3 --version into my zsh terminal, my Mac seems to point to the version of Python that is installed with Anaconda Navigator. I have included a screenshot of my VS Code instance where I was having an error trying to launch the default Django project, as well as some other files which contain my PATH variables. I have tried again and again to solve this issue, but I am more ore less stuck at this point. Any advice on how to configure my setup such that Django is available system-wide, with the latest version of Python, would be much appreciated. Scott My VS Code Django error -
I want to calculate timezone from lat/long in django in following format UTC +2 Central European summer time How can we do this? [closed]
I want to calculate timezone from lat/long in django in following format UTC +2 Central European summer time How can we do this? -
Django not using correct Postgres schema on Heroku
I have a Django app that I need to connect to a schema "new_schema" by default, rather than public. I've managed to get this working on my local instance by running CREATE SCHEMA new_schema; on the local database & then adding into my settings a database config like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=new_schema', }, 'NAME': 'database_name', 'USER': 'user_name', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '5432', }, } But, when I deploy to Heroku & create the schema there, I can't get the app to point to the new schema. In my production settings file, I have DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) DATABASES['default']['OPTIONS']['options'] = '-c search_path=new_schema' in order to get the Heroku database url into the right config format, and then add in my schema to the options. But for some reason this doesn't work - instead any migrations get applied to public as do db queries. I can explicitly set the new_schema in the Postgres users search_path, but there are other servers that need different default schemas I have been going in circles trying to resolve this for ages, I don't know what I'm missing! I can' tell if this is a problem with … -
ModuleNotFoundError: No module named 'crispy_formsmain'
Please help me as I am new to Django and I am learning out of my curiosity. I tried to find the solution but couldn't. I have spent 2 days to find the appropriate solution. Please help. I cloned the repository from github and it gives me the error as follows: (env) C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 954, in _bootstrap_inner self.run() File `"C:\ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 892, in run` self._target(*self._args, **self._kwargs) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-`packages\django\core\management\commands\runserver.py", line 110, in inner_runautoreload.raise_last_exception()` File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Tenzin Karma\Desktop\critique\Wrappers-India-Online-master\env\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_formsmain' -
How to optimize django queries without hitting the database
I have a geojson file that contains more than 77 500 rows et 20 columns. With my actual view, it takes more than 30 minutes to upload the file. How can I optimize it without hitting frequently the database? class Edge(models.Model): #geometry = models.LineStringField() target = models.ForeignKey(Node, on_delete=models.CASCADE) source = models.ForeignKey(Node, on_delete=models.CASCADE) network = models.ForeignKey(RoadNetWork, on_delete=models.CASCADE) class Node(models.Model): network = models.ForeignKey(RoadNetWork, on_delete=models.CASCADE) node_id = models.BigIntegerField() name = models.CharField('Node Name', max_length=200) location = models.PointField() Here is theView : def upload_edge(request, pk): template = "networks/edge.html" roadnetwork = RoadNetWork.objects.get(id=pk) node_instance = Node.objects.filter( network_id=pk).select_related() list_edge_instance = [] if request.method == 'POST': form = EdgeForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] objects = json.load(datafile) for object in objects['features']: objet_type = object['geometry']['type'] if objet_type == 'LineString': properties = object['properties'] target = properties.get('target') source = properties.get('source') try: target = Node.objects.get(node_id=target) source = Node.objects.get(node_id=source) node = Edge( target=target, source=source, network=roadnetwork) list_edge_instance.append(node) except ObjectDoesNotExist: pass Edge.objects.bulk_create(list_edge_instance) return redirect('home') else: form = EdgeForm() return render(request, template, {'form': form}) -
Filter api output by value stored in Join Table
I have many to many relationship between two models (First is origin country with list of countries and second is destination country with list of countries). I have created join table and I have set additional variable in it: class BorderStatus(models.Model): STATUS_CHOICES = [ ('OP', 'OPEN'), ('SEMI', 'CAUTION'), ('CLOSED', 'CLOSED') ] Country = models.ForeignKey(Country, on_delete=models.CASCADE) OpenDestination = models.ForeignKey(OpenDestination, on_delete=models.CASCADE) status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='CLOSED') class Meta: unique_together = (('Country', 'OpenDestination')) def __str__(self): return str(self.Country) + ' and ' + str(self.OpenDestination) Now I set the view that it lists a country and all countries related with a status, like this: [ { "name": "Germany", "dest_country": [ { "id": 1, "name": "New Zealand", "status": "SEMI" }, { "id": 2, "name": "Watahia", "status": "CLOSED" }, { "id": 3, "name": "France", "status": "OP" } ] } ] Here is my serializer: class OpenDestinationSerializer(serializers.ModelSerializer): class Meta: model = OpenDestination fields = '__all__' class BorderStatusSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField(source='OpenDestination.id') name = serializers.ReadOnlyField(source='OpenDestination.name') class Meta: model = BorderStatus fields = ('id', 'name', 'status',) class CountrySerializer(serializers.ModelSerializer): """ Connect serializer so that it is seen in the api""" dest_country = BorderStatusSerializer(source='borderstatus_set', many=True) class Meta: model = Country fields = ('name', "dest_country") Now I want to add a filter that only …