Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No registered models were found when using django-simple-history in inhered model
I've created a class to inherit to my django models so I can use django-simple-history. However, when trying to generate migrations, it indicates that there are no changes detected class VersionableModel: history = HistoricalRecords() def getHistory(self): pass class SoftDeleteModel(models.Model): is_deleted = models.BooleanField(default=False, verbose_name='Deshabilitado') objects = SoftDeleteManager() all_objects = models.Manager() class DimensionAmenaza(SoftDeleteModel, VersionableModel): mombre_dimension_amenaza = LowerCharField(blank=False, unique=True, max_length=100) peso_dimension_amenaza = models.FloatField(validators=[validate_percent], null=False, blank=False) -
Change color scheme of django-baton admin interface
So I wanna change the color scheme of the interface, I've read the self-help stuff from https://otto-torino.github.io/django-baton but it's not making much sense to me, I've located the _variables.scss file, which I need to change to make it work, how do I go about this, would really appreciate your help thx! Django-baton package link: https://github.com/otto-torino/django-baton -
What does Herokus metric graph display?
I use Heroku, but I'm either too dumb or am looking in all the wrong places to get info on how the dynos work. I initially thought that a single dyno could run a bunch of different processes simultaneously. But I realized that if that were the case, then when I increased the dyno count, my memory usage would have gone down. Since that isn't the case, it must mean that the memory usage graph actually displays the most memory-intensive dyno. But that doesn't feel right because that doesn't seem to be mentioned anywhere. So my question is are any of my assumptions correct and/or is there a helpful resource for having a better understanding of dynos? -
Why does .env file isn't working in django docker?
I am working on django docker project. I added .env file, but I have this error: celery_1 | File "/project/core_app/__init__.py", line 5, in <module> celery_1 | from .celery import app as celery_app celery_1 | File "/project/core_app/celery.py", line 11, in <module> celery_1 | from core_app.settings import INSTALLED_APPS celery_1 | File "/project/core_app/settings.py", line 90, in <module> celery_1 | 'NAME': os.environ['DB_NAME'], celery_1 | File "/usr/local/lib/python3.9/os.py", line 679, in __getitem__ celery_1 | raise KeyError(key) from None celery_1 | KeyError: 'DB_NAME' It seems that I specified env_file in docker-compose correctly but error said that code doesn't see environment variables. How can I fix the problem? settings.py import environ import os env = environ.Env() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': 'db', 'PORT': 5432, } } .env -- just a few configs DB_USER=postgres DB_PASSWORD=post222 DB_NAME=lk_potok_4 DB_PORT=5444 DATABASE_URL=postgres://postgres:post222@db:5432/lk_potok_4" docker-compose.yml -- full file https://pastebin.com/0feAg5xq version: '3.9' services: django: build: ./project # path to Dockerfile command: sh -c " python manage.py makemigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 core_app.wsgi" volumes: - ./project:/project - ./project/static:/project/static expose: - 8000 env_file: - .env environment: - DATABASE_URL=${DATABASE_URL}" - DEBUG=1 - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} - DB_NAME=${DB_NAME} db: image: postgres:13-alpine volumes: - pg_data:/var/lib/postgresql/data/ expose: - 5432 … -
Django model newly created object from pre_save signal handler disappears
In our Django app, in order to prevent users from randomly updating their profiles for compliance purposes, we need all profile updates to be reviewed. I added a pre_save signal to the User model and in the signal handler, I create an object to the table ProfileUpdateRequest using ProfileUpdateRequest.objects.create(...) and then raise an exception. The exception is then caught in the ViewSet to return a proper response. However, when I tested it, I found that every time I update the user profile, a new object of ProfileUpdateRequest was created but not applied to the database. I assigned the returned value of the create() method to a variable and logged it out. I saw the id of the new object increasing all the time, but there was no new object added to the table at all. I wonder whether the changes were not applied to the DB immediately and the exception broke the normal workflow which caused the changes not to be applied to the DB. -
Attempting to get C code to find size of directory to compile with Emscripten
I'm having an issue getting my C code to compile with emscripten; fun fact this my first stack overflow post, as most of the time when I have an issue regarding a system or programming language there is a pre-existing question on here I can reference to get an answer, however this is different. I'm attempting to display the size of my Django Root directory on the webpage, this is the C code I am attempting to compile. #include <stdio.h> #include <errno.h> #include <unistd.h> #include <ftw.h> #include <sys/types.h> #include <sys/stat.h> static unsigned int total = 0; int sum(const char *fpath, const struct stat *sb, int typeflag) { total += sb->st_size; return 0; } int main() { char *DJANGO_ROOT = "/usr/src/app"; if (!DJANGO_ROOT || access(DJANGO_ROOT, R_OK)) { return 1; } if (ftw(DJANGO_ROOT, &sum, 1)) { perror("ftw"); return 2; } printf("%s: %u\n", DJANGO_ROOT, total); return 0; } This is the output I receive when attempting to compile the file using "emcc dir_size.c -o dir_size.html" yalt@mainframe:~/Network/Mainframe/rabbithole_site/django_root/my_app/static/js/wasm/dir_size$ emcc dir_size.c -o dir_size.html error: undefined symbol: ftw (referenced by top-level compiled C/C++ code) warning: Link with `-sLLD_REPORT_UNDEFINED` to get more information on undefined symbols warning: To disable errors for undefined symbols use `-sERROR_ON_UNDEFINED_SYMBOLS=0` warning: _ftw may … -
Django - Can I delete an instance of object from a choices selection set (ModelChoiceField)?
I am newbie in the Django world, so i am wondering if its possible to get an instance from a selection set (choice field) and then delete it. In my case I want to pick a Profile, and then delete it. enter image description here views.py class SelectProfileFormView(views.FormView, LoginRequiredMixin): form_class = SelectProfileForm template_name = 'profile/delete-member.html' def form_valid(self, form): profile = Profile.objects.get(pk=self.kwargs['pk']) profile.delete() return super().form_valid(form) form class SelectProfileForm(forms.ModelForm): profiles = forms.ModelChoiceField( widget=forms.Select, queryset=Profile.objects.all(), # empty_label="----None----", ) # here you can filter for what choices you need class Meta: model = Profile fields = () I get this error: "KeyError at /profile/select/" "pk" How can I delete the chosen instance? Should I make a selection view and then a delete view separately? If so how can I redirect with the correct pk instance? Thanks in advance! -
How to modify a models to be able to give access to users in django
I am working on a classroom project and I am completely new to Django. How to modify my models (course,user) so that I can add students to the course in two ways 1)By entering the class code by students. 2)By sending join invitations to students from a list of all students by selecting some by the teacher and if the student confirms/accepts he will be added. i am attaching the models below user model class CustomUser(AbstractUser): email = models.EmailField() is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) Course Model class Course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(25)]) classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) slug=models.SlugField(null=True, blank=True) def __str__(self): return self.course_name def save(self, *args, **kwargs): self.slug = slugify(self.classroom_id) super().save(*args, **kwargs) def is_valid(self): pass -
Match between dictionaries in list
hello guys i have a question to how match between dictionaries i send 3 request to youtube api first to search second to video third to channel what i try to create is dic that have Title of the video Thumbnails of the video and the profile of the channel that make the video. here you can see the code and the requests i send: def get(self,request): search_url = "https://www.googleapis.com/youtube/v3/search" video_url = "https://www.googleapis.com/youtube/v3/videos" channel_url = "https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+commaSeperatedList+'&fields=items(id%2Csnippet%2Fthumbnails)&key={}".format(settings.YOUTUBE_DATA_API_KEY) para_search = { 'part': 'snippet', 'q': 'Learn Python' , 'key': settings.YOUTUBE_DATA_API_KEY, 'maxResults': 3, 'type': 'video' } search_response = requests.get(search_url,params=para_search) print(search_response.text) results = search_response.json()['items'] ids =[] for result in results: ids.append(result['id']['videoId']) para_videos = { 'part': 'snippet', 'key': settings.YOUTUBE_DATA_API_KEY, 'id':','.join(ids), } video_response = requests.get(video_url, params=para_videos) print(video_response.text) results = video_response.json()['items'] dict_youtube = {} list_youtube = [] channelIdList = [] for result in results: dict_youtube = { 'title': result['snippet']['title'], 'thumbnails': result['snippet']['thumbnails']['high']['url'], 'channelId': result['snippet']["channelId"], } channelIdList.append(result['snippet']["channelId"]) list_youtube.append(dict_youtube) param_channel = { 'part':'snippet,contentDetails,statistics', 'key':settings.YOUTUBE_DATA_API_KEY, 'id':','.join(channelIdList) } channel_response = requests.get(channel_url,params=param_channel) print(channel_response.text) results = channel_response.json()['items'] profile = [] profile_dic = {} for result in results: profile_dic = { 'channelId': result['id'], 'profile': result['snippet']['thumbnails']['default']['url'], } profile.append(profile_dic) print(profile) print(list_youtube) print(profile): [{'channelId': 'UC8butISFwT-', 'profile': 'https://yt3.ggpht.com/ytc/AifQn-nYNfkgLvVPkw=s88-********-no-rj'}, {'channelId': 'UCWv7*mDpPBA', 'profile': 'https://yt3.ggpht.com/tBEPr-zTNXEeae7VZK2PXSwzMBKVR7W0MI7gyND8=s88-c-k-c0x00ffffff-no-rj'}] print(list_youtube) [{'title': 'Learn Python - Full Course for … -
Django standalone app - problem reading app settings in main project
I am using Django 3.2 I am writing a standalone app MyApp that uses GeoIP2 I want to be able to have a project using the MyApp app, to be able to do either one of the following. set GEOIP2_PATH in project.settings OR (default) fall back on the GEOIP2_PATH value set in MyApp.settings This is what I have so far: MyApp/settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GEOIP_PATH = os.path.join(BASE_DIR, 'userprofile/geodata') # ... MyApp/utils.py from django.conf import settings from MyApp import settings as myapp_settings def get_attribute_from_settings(attribute_name): try: value = getattr(settings, attribute_name) except AttributeError: try: value = getattr(myapp_settings, attribute_name) except AttributeError: raise ImproperlyConfigured() finally: return value Code that uses GeoIP2 from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception from ipware import get_client_ip geo = GeoIP2() def do_something(address): # Barfs at next line: info = geo.city(address) When the function above is called, I get the following exception thrown: raise GeoIP2Exception('GeoIP path must be provided via parameter or the GEOIP_PATH setting.') django.contrib.gis.geoip2.base.GeoIP2Exception: GeoIP path must be provided via parameter or the GEOIP_PATH setting How can I use the get_attribute_from_settings() to get the default GEOIP2_PATH if not set in project.settings? -
Filter Django query by annotated field using a subquery
I am trying to further filter a Django query using an annotated field: My (simplified) tables: class Inventory(models.Model): item = models.CharField(max_length=10, primary_key=True) lot = models.CharField(max_length=10) ... MORE FIELDS ... class Car(models.Model): name = models.CharField(max_length=10) item= models.ForeignKey(Inventory, on_delete=models.PROTECT, null=True, blank=True) ... MORE FIELDS ... I would like my results set for the Inventory query to include the name of the car assigned to that item. This works fine: Inventory.objects.annotate(car=Subquery(Cars.objects.filter(item=OuterRef('item')).values('name'))) The car name is retrieved in the queryset. I used to have the car in the item (so it was easy to filter on the car), but due to other requirements, I has to move the reference the other way around - car now has an item field). I ensure that once an item is associated with a car, it cannot be used again for another car since the Subquery must return a single result. Now, I would like to further filter the queryset by the annotated field that brings back car: Inventory.objects.annotate(car=Subquery(Cars.objects.filter(item=OuterRef('item')).values('name'))).filter(car__icontains='AA') Now, I get an error raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) Is it possible to do this the way I am trying? -
Deployment in the digital ocean and Django multiplies sessions
I have an application deployed in digital ocean already in production mode (ubuntu); For some reason I can't log in: I enter my credentials and all is well but I am not redirected. In the database I store some data of the session, whether you log in or not, a single user should generate a single record, but it generates between 12-18 records per page, that is, visiting a couple of links will have already stored around 30. I have mounted the service locally and it does not present this inconvenience, neither in production or development mode. What could it be? -
How to retry Django Celery task on Exception when Internal Server Error is raised?
I am trying to use Celery to send anywhere from 1 to about 25 consecutive requests to a third-party API. The measure of success is whether I get a URL back in the response payload: response_json["data"]["url"]. Celery or not, sometimes I get the data I expect, and sometimes I don't. I decided to experiment with Celery to retry the API call while taking advantage of the built-in exponential backoff, which sounds perfectly suited to my needs, but I am struggling to implement. When the data I am expecting is not available in the response payload, I get a TypeError: 'type' object is not iterable (i.e., there is no such item in the response). But I am also getting an Internal Server Error, which I wonder whether I need to handle or whether I could use to trigger the retry. Here is a example of one of several similar approaches I have tried: @shared_task(autoretry_for=(Exception), retry_backoff=True, retry_backoff_max=120) def third_party_api_request(payload, api_url, headers): response = requests.request("POST", api_url, headers=headers, data=payload) response_json = response.json() return response_json["data"]["url"] # output: Internal Server Error: -- snip -- autoretry_for = tuple( TypeError: 'type' object is not iterable Another approach I have tried: @shared_task(bind=True) def third_party_api_request(self, payload, api_url, headers): try: response … -
Timestamped model __init__() got multiple values for argument 'on_delete'
I'm trying to create a foreignkey relationship in DRF models with an on_delete fk_city = models.ForeignKey("region_mgmt.City", "warehouses", on_delete=models.SET_NULL) TypeError: __init__() got multiple values for argument 'on_delete' below is my code: from django_extensions.db.models import TimeStampedModel class State(TimeStampedModel, models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.CharField(max_length=100) postal_code = models.CharField(max_length=20, blank=True, null=True) fk_country = models.ForeignKey(Country, related_name="states", on_delete=models.CASCADE) def __str__(self): return self.name class City(TimeStampedModel, models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.CharField(max_length=100) postal_code = models.CharField(max_length=20, blank=True, null=True) fk_state = models.ForeignKey(State, related_name="cities", on_delete=models.CASCADE) def __str__(self): return self.name does anyone know the reason and its solution? -
Create index on nested element JSONField for Postgres in Django
I have a Django model in my python project with a meta class detailing it's indexes. I'm curious if there's a way to create the index using the nested path of the json object. In this case we know the structure of our json and I wanted to stick with a BTree or Hash index on the specific element. If I were simply running this as raw sql, I'd expect to just do something like: CREATE INDEX ON foster_data(root->'level_1'->'level_2'->>'name'); I was hoping I could do something like this in my model: from django.db import models from django.contrib.postgres import indexes class ParentGuardians(Facilitators): # which extends models.Model parent_identifier = models.IntegerField(db_column='p_id', default=None, blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['table_id', name='UniqueConstraint for Parents') ] indexes = [ models.Index(fields=['p_id', ]), indexes.BTreeIndex(fields=[models.JSONField('{"root": {"level_1": {"level_2": "name"}}}'), ] , name="jsonb_p_id_idx"), ] or even: ... indexes.BTreeIndex(fields=["root->'level_1'->'level_2'->>'name'", ] ... But the named field fields only wants strings and only wants them to be the top level field defined in the model. I'm aware of this questions: Indexing JSONField in Django PostgreSQL but it seems more of a hack and wanted the result generated from the codebase and makemigrations, not to manually edit it. Is this possible more recently? -
How to configure an NGINX & UWSGI in Django
I am deploying my Django app on VPS and I would like to use NGINX & UWSGI I have followed this tutorial https://www.youtube.com/watch?v=ZpR1W-NWnp4 in order to configure my NGINX server. Below is my NGINX configuration file named my_nginx.conf: # the upstream component nginx needs to connect to upstream django { server unix:///root/PIDC/ProjetAgricole/uwsgi_nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name 173.249.8.237; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /root/PIDC/ProjetAgricole/media; # your Django project's media files - amend as required } location /static { alias /root/PIDC/ProjetAgricole/staticfiles; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /root/PIDC/ProjetAgricole/uwsgi_params; # the uwsgi_params file you installed } } I just changed the paths only in this file. When I run this command, I am getting this output that seems … -
show Error Message For Duplicate Item {IntegrityError}
I want to be saved reservation information when is not duplicate After the user clicks on the send message button. i Got This Error django.db.utils.IntegrityError: UNIQUE constraint failed: Restaurant_reservation_received.date, Restaurant_reservation_received.time, Restaurant_reservation_received.table_number My Views: if request.method == "POST" and request.POST.get('name'): reservation = Reservation_Received() reservation.name = request.POST.get('name') reservation.date = request.POST.get('date') reservation.time = request.POST.get('time') reservation.count = request.POST.get('count') reservation.table_number = request.POST.get('table_number') reservation.save() return JsonResponse({'msg1':'Success'}) else: pass if request.method == "POST" and request.POST.get('name2'): contactus = ContactUs() contactus.name2 = request.POST.get('name2') contactus.subject = request.POST.get('subject') contactus.email = request.POST.get('email') contactus.message = request.POST.get('message') contactus.save() return JsonResponse({'msg2':'Success'}) return render(request, 'home.html',context) HTML CODE <form class="row" id="reservationform" action="" method="post"> {% csrf_token %} <div class="col-md-10 col-sm-12 center-col"> <div class="col-md-6 col-sm-12 reservation-name"> <input name="name" type="text" placeholder="Your Name" required="True" class="input-round big-input"> </div> <div class="col-md-6 col-sm-12"> <div class="select-style input-round big-input"> <select name="date" required="True"> <option selected="selected" value="">Select Day</option> {% for item in reservation_date %} <option value="{{ item.date }}"> {{ item.date }}</option> {% endfor %} </select> </div> </div> <div class="col-md-6 col-sm-12"> <div class="select-style input-round big-input"> <select name="time" required="True"> <option selected="selected" value="">Select Time</option> {% for item in reservation_time %} <option value="{{ item.time }}">{{ item.time }}</option> {% endfor %} </select> </div> </div> <div class="col-md-6 col-sm-12"> <div class="select-style input-round big-input"> <select name="count" required="True"> <option selected="selected" value="">Select Number Of Person</option> {% for item … -
Some static files can't be loaded because it is blocked by CORS policy (Django) even it is configured based on Django documentation
I faced an issue with a CORS policy and cannot see what is wrong. I use Django framework and my static files are hosted in Azure Blob So I am getting errors for these files and it says tuat Access-Control-Allow-Origin is not present: What is strange that other files from the same host are loaded.. CORS settings looks like this: ALLOWED_HOSTS = ['support.mdesk.lt', 'https://suppaccountstorage.blob.core.windows.net'] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'support.mdesk.lt', 'https://suppaccountstorage.blob.core.windows.net', ) CSRF_TRUSTED_ORIGINS = ['https://support.mdesk.lt'] INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'bootstrap4form', 'supportSystem', 'storages' ] SITE_ID = 1 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', ] Wham am I doing wrong? -
How can I find how much 1 star/2 star----5star present in percentage?
I've created a form for being stored ratings and feedback in the database. Ratings and Feedback are being stored in the database perfectly. But the problem is, I can't find out how many different types of rating stars are present in the database. How can I find out how many 1 star/2star/---5 stars are present in the object model in percentage? What should I do It? models.py: class Frontend_Rating(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="frontend_rating") Rating = models.IntegerField(null=True) Feedback = models.TextField(max_length=250, null=True) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) + str("(") + str(self.Rating) + str("stars") +str(")") Views.py: def index(request): #rating____________________ frontend_all_ratings = Frontend_Rating.objects.all() number_of_frontend_rating = frontend_all_ratings.count() average_rating = 0 frontend_one_star = 0 frontend_two_star = 0 frontend_three_star = 0 frontend_four_star = 0 frontend_five_star = 0 percentage_frontend_ONE_star = 0 percentage_frontend_FIVE_star = 0 for frontend_rating_item in frontend_all_ratings: frontend_rating = frontend_rating_item.Rating if frontend_rating: total_ratings = 0 total_ratings += frontend_rating average_rating = round(total_ratings/frontend_all_ratings.count(),1) context = { "frontend_five_star":frontend_five_star, "frontend_one_star":frontend_one_star, } return render(request,'0_index.html',context) -
django-polymorphic Aggregate Sum Price
I want a clean way to sum the price of all products in a queryset when using django-polymorphic. Install dependencies: pip install django-polymorphic Create app: manage.py startapp content path: content/models.py from django.db import models from polymorphic.models import PolymorphicModel from polymorphic.managers import PolymorphicManager from django.utils.text import slugify from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Content(PolymorphicModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='content') title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) objects = PolymorphicManager() class Meta: unique_together = ('user', 'slug') def __str__(self): return str(self.title) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Post(Content): pass class Note(Content): pass class ProductA(Content): price = models.DecimalField(max_digits=6, decimal_places=2, null=True) class ProductB(Content): price = models.DecimalField(max_digits=6, decimal_places=2, null=True) path: project/settings.py INSTALLED_APPS = [ ... 'content.apps.ContentConfig' # add this ] AUTH_USER_MODEL = 'content.user' Run: manage.py makemigrations manage.py migrate In interactive shell: u, _ = User.objects.get_or_create(username='user') post = Post.objects.create(user=u, title='First Post') note = Note.objects.create(user=u, title='First Note') prod_a = ProductA.objects.create(user=u, title='First Product A', price=12.99) prod_b = ProductB.objects.create(user=u, title='First Product B', price=18.99) I want a clean way to sum the price of all products in a queryset. Example: qs = Content.objects.instance_of(ProductA, ProductB) Returns: <PolymorphicQuerySet [<ProductA: First Product A>, <ProductB: First Product B>]> Since product A and B both have price, I thought I could … -
PostGIS built for PostgreSQL 13.0 cannot be loaded in PostgreSQL 14.2
I am running arch Linux, I installed postgresql and postgis to work with it in my Django project, but whenever i try to migrate my models i get this error PostGIS built for PostgreSQL 13.0 cannot be loaded in PostgreSQL 14.2 can anyone tell me what's the problem here please -
Django while True try loop in createview
I hope I am not being a little paranoid but I am trying to make that when there is a record or customer number the next record is different from the previous one, the reason why I do it this way is because there will be many people capturing data at the same time every day and I do not want to throw a 404 error or something like that but on the contrary, in case there is already a record in the database retry and retry and retry again. This is an example that I need to conclude to finish well my script, obviously before it makes a request to the database to verify the last record. I know it is possible to do this with function based views but at the moment I am testing class based views, I have been doing this for several hours. Any help is very important to me. Thanks guys. models.py from django.db import models # Create your models here. class Empresa(models.Model): nombre = models.CharField(max_length=20) numero = models.IntegerField(unique=True) views.py from dataclasses import field from django.shortcuts import render from django.views.generic import * from aplicacion.models import Empresa # Create your views here. class CrearEmpresa(CreateView): model … -
Whats the correct structure for Django templates?
I have a project in Django called: "my_site", and an app called "blog", I'm trying to render the "index.html" inside the path: my_site/blog/templates/blog/index.html. But keep getting this error: Template-loader postmortem Django tried loadi ng these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\blog\templates\index.html (Source does not exist) The view: def index(request): return render(request, 'index.html') the urls.py: urlpatterns = [ path('', views.index), path('posts', views.show_all_posts), path('posts/<slug:slug>', views.show_post) ] If i move the index.html outside the blog folder, like in this example: my_site/blog/templates/index.html the code runs and the index.html renders without problem, but i was taught that the correct structure is to create a folder inside templates with the same name of the app. So could anyone please explain me the way i should structure my files? -
Django REST Framework; ImproperlyConfigured; Could not resolve URL for hyperlinked relationship
Am trying to use DRF to make an election tracker; getting on what was supposed to be fairly simple ViewSet list and retrieve endpoints; django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "election-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Model Snippet... class Election(models.Model): _id = models.CharField( name="id", primary_key=True, validators=[election_ids.validate], max_length=32 ) date = ComputedDateField(compute_from="_date") # not relevant parent = models.ForeignKey( to="self", on_delete=models.CASCADE, default=None, null=True ) Serializers class ElectionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Election # Removing the 'url' from below stops the ImproperlyConfigured error on retrieve calls fields = ["url", "org", "date", "constituency", "parent"] read_only_fields = ["url"] depth=1 ViewSet class ElectionViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint that allows elections to be viewed or edited. """ lookup_field = 'id' lookup_value_regex = '[a-z0-9.\-_]+' # this might be the culprit, see below queryset = Election.objects.all().order_by("-date") serializer_class = ElectionSerializer permission_classes = [permissions.AllowAny] and relevant urls.py app_name = "counts" api_router = routers.DefaultRouter() api_router.register(r"users", UserViewSet, "users") api_router.register(r"groups", GroupViewSet, "groups") api_router.register(r"elections", ElectionViewSet, "elections") api_router.register(r"candidates", CandidateViewSet, "candidates") api_router.register(r"stages", StageViewSet, "stages") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("", … -
Is it possible to use f-strings with Concat(), Value() and F()
I have a varchar column whose values I would like to update. Here is what I have tried so far: for item in Item.objects.filter(): some_items = get_some_items(item) Item.objects.filter(field=item.field).difference(some_items).update( field=Concat( Value(settings.PREFIX), Value(f"{F('id'):>010d}") ) ) Which gives me TypeError: unsupported format string passed to F.__format__ I need help on how I can achieve this if possible.