Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
intermittent 502 Bad Gateway nginx/1.18.0 (Ubuntu)
My django app has ben running for about 3 months now. I intermittently get a 502 Bad Gateway error message on any page, I will even get this error the Django admin page, so I don't think its my code. Most of the time the page loads fine, or if I just reload it will load. can someone help me understand where I'm making a mistake The output from sudo tail -20 /var/log/nginx/error.log yields: 2022/03/29 16:12:56 [error] 720#720: *8182 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /backyard/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/backyard/", host: "104.131.165.99", referrer: "http://104.131.165.99/backyard/" 2022/03/29 16:19:44 [error] 720#720: *8188 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /garage/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/garage/", host: "104.131.165.99", referrer: "http://104.131.165.99/garage/" 2022/03/29 16:26:29 [error] 720#720: *8194 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /garage/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/garage/", host: "104.131.165.99", referrer: "http://104.131.165.99/garage/" 2022/03/29 16:36:30 [error] 720#720: *8205 upstream prematurely closed connection while reading response header from upstream, client: 165.225.38.84, server: _, request: "GET /garage/ HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/garage/", host: "104.131.165.99", referrer: "http://104.131.165.99/garage/" 2022/03/29 16:42:58 [error] 720#720: *8209 upstream prematurely closed connection while … -
How can I get my image to display using django?
I cannot get my images to display on my webpage while using Django. All I see is the images 'alt' text displayed, and a broken image icon next to it. I'm able to successfully upload the image as originally intended. I'm using an Ubuntu AWS instance with Apache installed on it for my server. I also have Pillow installed for displaying images. I'm also able to successfully load my CSS, so I know that it probably isn't an issue with my static directories or settings. This is my settings.py file: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)zp1^v$1v9%@3e*rz4yp0o964-^!8@ruff4$((b5vcv6*h@d-x' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['ec2-3-14-217-157.us-east-2.compute.amazonaws.com', '3.14.217.157'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product.apps.ProductConfig', ] MIDDLEWARE = [ '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 = 'productapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
Using djnago-import-export import of blank TextField
Imagine I have Data stored in my Dabase. A Model contains a Django-TextField with blank=True but without null=True according to Djnago-convention. The Data was created via the admin-menu. Empty Text-Fields are stored as empty string which works just fine. But import trough django-import-export throws violates not-null constraint DETAIL: Failing row contains. Is this a problem of djnago-import-export? -
Filter queryset by year between two date fields
I have a start_date and an end_date fields in my model. The user shall be able to filter records by selecting a year value, so that records that span over multiple years should be shown if the year selected is included. For example: Selected year: 2019 start_date end_date 2017-03-12 2021-09-03 2019-12-12 2020-06-05 I can do this query by raw SQL like that: SELECT * FROM `orders` WHERE '2019' BETWEEN YEAR(`start_date`) AND YEAR(`end_date`); How can I do this using Django ORM and avoid raw SQL queries? Because I am already using the ORM in multiple filters and only remaining this bit. -
Django M2M queryset with multiple instances and Q
I have the following oversimplified models: class Surgerytype(models.Model): title = models.CharField(max_length=255, null=True, blank=True) class Content(models.Model): surgery = models.ManyToManyField(Surgerytype, null=True, blank=True) I have a lot of Content instances, which themselves have a lot of Surgerytypes related to them. You can think of Surgerytypes as tags. I have this query: content = Content.objects.all() # surgeries is an array of Surgerytype instances titles query = content.filter(Q(surgery__title__in=surgeries) When I ajax send to my backend a tag (i.e. a Surgerytype instance title), all good the query returns all the instances of Content that include this tag. Now, the problem is that if I select two tags, the queryset returns nothing instead of all Content instances that include these 2 tags and possibly more tags. I have found on SO how to do this for 1 M2M model in the Content model but it is quite dirty and not scalable at all (there are 3 other M2M/filters to add in the real Content model). Any ideas? Found many questions related to the subject but it doesn't seem to have a definitive, scalable answer. Many thanks to you all -
Django template link with Django include
is it possible to open a html link form in a Django html include? So, I don't want the link in the html to open in the browser address bar so that it can be seen. So I was wondering if you can somehow open it in the same template. But that didn't work for me, because the default data for the form is not taken. As example: in my .html file I have a URL <li role="presentation"><a href="{% url 'create_exposition' blog.id %}">create new blog</a></li> {% include "zed/create_exposition.html" with ...%} This link in urls.py re_path(r'^(?P<blog_id>[0-9]+)/create_exposition/$', views.create_exposition, name='create_exposition'), and in the views.py def create_exposition(request, blog_id): form = ExpositionForm(request.POST or None) blog= get_object_or_404(Blog, pk=blog_id) if form.is_valid(): blogs_expositions = blog.exposition_set.all() for s in blogs_expositions: if s.identifikationsnummer == form.cleaned_data.get("idnumber"): context = { 'blog': blog, 'form': form, 'error_message': 'You already added that exposition', } return render(request, 'zed/create_exposition.html', context) exposition = form.save(commit=False) exposition.blog= blog exposition.save() return render(request, 'zed/blog_detail.html', {'blog': blog}) context = { 'blog': blog, 'form': form, } return render(request, 'zed/create_exposition.html', context) Yes, I know it is still the old away and no genericview. I am already retooling piece by piece. -
How can Django Admin change "history" logs be used to also store copy of data?
Django Admin change "history" logs As you know Django Admin's sidebar shows a list of APP > MODELS. When you click on a MODEL, the focus area displays a list of RECORDS. Click on a RECORD, then the focus area shows a single RECORD as a form which you can change. Here, in the upper right hand corner of the change form, is a gray pill-shaped button labeled "HISTORY" with entries like: Dec. 9, 2021, 4:38 p.m. me Changed Table price headers. Feb. 26, 2022, 2:06 p.m. me Changed Table date headers. What I need is a copy of the record data before each change. Later, I need to query the Django database and--in this example--get the version of the record prior to the Feb 26 change. How can Django Admin change "history" logs be used to also store copy of data? Not for every Django Model The rest of the Models & Records in Django Admin should behave normally. I only have a few Models where I need history log and data. Not to be confused with model history When discussing this with other Django developers I have to explain the history I need is for the record's data, … -
CSS not showing in deployment for django
I'm trying to get my CSS to show on my Django app in deployment. My project is being hosted on an Ubuntu instance, using AWS. I'm using Apache to run my project on the instance. However, the CSS won't display in the browser. When I launch it from my IDE (PyCharm), the CSS will display on localhost perfectly. How can I fix this? I've looked all over for answers and so far nothing has worked. I've cleared my browsers cache, and tried on different browsers as well and the CSS still will not show. settings.py: """ Django settings for productapp project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+0-wtmj)^gt@#cn8)0=l(30#3s2df)&vi6f*yx10zrsnh+)s+6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ec2-3-14-217-157.us-east-2.compute.amazonaws.com', '3.14.217.157'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Disable swagger in django projectt
I have set up drf-yasg swagger and now I'm wondering what's the best way to disable swagger, because they should not be exposed after going live. -
Modify instance before it's saved on import
I'm setting up an import process for a model which has a ForeignKey relationship, and I've got an extra field on the model where I'd like to store the provided value if it's an invalid ID of the related table. The ID's in question here are UUIDs, so there's a good chance that someone along the line will provide some invalid data. class Result(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) passport = models.ForeignKey( to='results.Passport', null=True, blank=True, on_delete=models.SET_NULL ) invalid_passport = models.CharField( max_length=255, blank=True, null=True, help_text=_("An invalid passport number") ) The import file will contain a passport column for the UUID of the related object, but I'd like to save the provided value to invalid_passport if it doesn't match any Passport instances. My resource looks like this; class ResultResource(resources.ModelResource): """ Integrate django-import-export with the Result model """ passport = fields.Field( column_name='passport', attribute='passport', widget=ForeignKeyWidget(Passport, 'id') ) class Meta: instance_loader_class = CachedInstanceLoader model = Result fields = ( 'id', 'passport', 'invalid_passport' ) def init_instance(self, row=None): """ Initializes a new Django model. """ instance = self._meta.model() if not instance.passport: instance.invalid_passport = row['passport'] return instance def before_save_instance(self, instance, using_transactions, dry_run): """ Sets the verified flags where there is a passport match. """ if instance.passport: … -
How to cache object in django template and update if it was changed?
I have a simple Django app with a single view for displaying the product list: from time import sleep <other imports> class ProductListView(ListView): model = Product paginate_by = 50 allow_empty = True def get(self, *args, **kwargs): sleep(2) return super().get(*args, **kwargs) And the template: <div class="container"> {% for product in page_obj %} <div class="col-3 my-2"> <product details> </div> {% endfor %} </div> I use sleep(2) to emulate the slow uploading of a huge amount of objects from the database. Now I need to implement the next workflow: template from this view should be cached. So the first page upload should take >2 sec, the next one <2sec, uploaded from the cache. change Product item in the database (via admin page for example) page on refresh is loaded from cache, but product info should be updated to the newest I'm, researching the Django caching mechanism, but I'm not sure which one should I try. So is it possible in Django to implement this workflow? -
One To Many Connection
So I have two models Field and Sensor which have a OneToMany connection. Im creating a page where I have all the fields and whenever i click on one i get its respective sensors. I've made 4 test sensors (3 of them are on Field1, 1 on Field2) but its printing first one to first field and 2nd one to 2nd field maybe because of the pk parameter. Any clue how to fix that ? class Field(models.Model): friendly_name = models.CharField(max_length=24, blank=True) soil_type = models.CharField(max_length=24, choices=SOIL_TYPES, blank=True) cultivation = models.CharField(max_length=128, choices=CULTIVATIONS, blank=True) class TreeSensor(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) sensor_name = models.CharField(max_length=200, blank=True) longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) View : def detail(request, field_id): try: sensor = models.TreeSensor.objects.get(pk=field_id) except models.TreeSensor.DoesNotExist: raise Http404("No sensors for this field") return render(request, 'dashboard/detail.html', {'sensor': sensor}) html: <h1> {{ field.friendly_name}}</h1> {% for sensor in field.treesensor_set.all %} {{treesensor.sensor_name}} {%endfor%} -
How to instantiate model with init function in modelforms?
I have a program that uploads a csv of data in order to map values in the csv to other values. In order to do this, the user must select which columns in the csv they need to create the mapping, so that no extraneous information is on the mapping page. To do this I created a dynamic Django by overriding the init function in my ModelForm. The problem is that even though I'm able to dynamically show the column values, when the user tries to select the values and save them to the model, it fails, because the Model choices don't align with the dynamic checkbox values. So I've overridden the Model's init function to populate the model's choices. My problem is I'm not sure how to instantiate the model in the ModelForm to call the init function. model class ColumnMapping(models.Model): CHOICES =[('row_1', 'A'), ('row_2', 'B'), ('row_3', 'C')] company = models.ForeignKey(RawData, on_delete=models.CASCADE) columnNames = MultiSelectField(max_length=100, choices=CHOICES) def __init__(self, *args, **kwargs): self.choices = kwargs.pop('choices') super(ColumnMapping, self).__init__(*args, **kwargs) self._meta.get_field.choices = self.choices form - I think something needs to happen here in the Meta class, but since the model = ColumnMapping line doesn't instantiate the model (I don't think), I don't think … -
Module not found when trying to import files into Custom Django commands
Background I'm new to Django and trying to set up a Django database with react front end for a trading card game database. I'm using a custom command in Django to pull cards from MTG's API and then using a serializer to save the data I'm pulling. Problem When I try to run the custom command it fails because my program can't seem to find my serializer module. I have tried to specify the path with sys, but it doesn't seem to work and I believe all my modules have an __ init __.py so they can be recognized as modules. I'm definitely willing to admit I did these things incorrectly, however. The exact error: ModuleNotFoundError: No Module named 'MTG_hoard.api' Here is a snapshot of my project directory... Here is how I'm importing the serializer... Additional information I'm basing my project on another github project FearChar/project-4-django-app. This is how I'm importing my apps in settings.py -
Why Django formset saves only 1st form?
I have issue with formset- When I try to save all of my form from formset only first one is saved, but in request.POST I can see all of forms. What am I doing incorectly? thank you in advance! models.py: class Activity(models.IntegerChoices): LOADING = 1, 'Loading' UNLOADING = 2, 'Unloading' LOADING_UNLOADING = 3, 'Loading/Unloading' ANOTHER = 4, 'Another' class Road(models.Model): def __str__(self): return self.company_name company_name = models.CharField(max_length=100) point_address = models.CharField(max_length=200) activity = models.PositiveSmallIntegerField(default=Activity.LOADING, choices=Activity.choices) activity_time = models.DateTimeField() forms.py: class NewRoadForm(forms.ModelForm): class Meta: model = Road fields = "__all__" views.py def new_road(request, extra=2): NewRoadFormSet = modelformset_factory(Road, form=NewRoadForm, extra=extra) formset = NewRoadFormSet(queryset=Road.objects.none()) if request.method == "POST": formset = NewRoadFormSet(request.POST) print(request.POST) #<< here I see data from all forms if formset.is_valid(): for f in formset.cleaned_data: if f: print(f) ##<< here I see only from 1st form return HttpResponseRedirect(reverse("orders:new_road")) else: print(formset.errors) return render(request, 'orders/add_road.html', {'formset':formset, 'extra':extra}) template.html: {% extends 'orders/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} <input type="hidden" name="form-TOTAL_FORMS" value="{{ extra }}" id="id_form-TOTAL_FORMS"> <input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"> <input type="hidden" name="form-MIN_NUM_FORMS" value="2" id="id_form-MIN_NUM_FORMS"> <input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"> {{ formset.menagement_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} <input type="submit" value="save"> … -
generate zip folder and add to storage django
Hi guys I need to generate a zip file from a bunch of images and add it as a file to the database This is the code to generate the file def create_zip_folder(asin): print('creating zip folder for asin: ' + asin) asin_object = Asin.objects.get(asin=asin) # create folder output_dir = f"/tmp/{asin}" if not os.path.exists(output_dir): os.makedirs(output_dir) # download images for img in asin_object.asin_images.all(): urllib.request.urlretrieve(img.url, f"{output_dir}/{img.id}.jpg") # zip all files in output_dir zip_file = shutil.make_archive(asin, 'zip', output_dir) asin_object.zip_file = zip_file asin_object.has_zip = True asin_object.save() # delete folder shutil.rmtree(output_dir) return True This all works and I can see the files generated in my editor but when I try to access it in the template asin.zip_file.url I get this error SuspiciousOperation at /history/ Attempted access to '/workspace/B08MFR2DRS.zip' denied. Why is this happening? I thought the file is to be uploaded to the file storage through the model but apparently it's in a restricted folder, this happens both in development (with local file storage) and in production (with s3 bucket as file storage) -
TemplateDoesNotExist at /blogapp/reset_password/ path_to/reset_password_email.html
i am trying to reset password but i got this error TemplateDoesNotExist at /blogapp/reset_password/ path_to/reset_password_email.html urls.py from django.urls import path from . import views from .views import signupview from django.contrib.auth import views as auth_views from django.urls import reverse_lazy app_name='blogapp' urlpatterns=[ path('',views.home,name='home'), path('createblog/',views.blogview,name='blogview'), path('blog/',views.blogretrieve,name='blog'), path('signup/',views.signupview,name='signup'), path('login/',views.loginview,name='login'), path('logout/',views.logoutview,name='logout'), path('author/<int:pk>/',views.authorview,name='author'), path('blogdata/<str:pk>/',views.blog,name='blogdata'), path('profile/<str:pk>/',views.profile,name='profile'), path('change-password/', auth_views.PasswordChangeView.as_view(template_name='blogapp/change-password.html',success_url=reverse_lazy('blogapp:password_change_done'))), path('password_change/done/',auth_views.PasswordChangeDoneView.as_view(template_name='blogapp/password_change_done.html'),name='password_change_done'), path('reset_password/',auth_views.PasswordResetView.as_view(template_name='blogapp/reset_password.html', success_url=reverse_lazy('blogapp:password_reset_done'), email_template_name='path_to/reset_password_email.html'),name='reset_password'), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(template_name='blogapp/reset_password_sent.html'),name='password_reset_done'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view( template_name='blogapp/reset_password_form.html', success_url=reverse_lazy('blogapp:password_reset_complete')),name='password_reset_confirm'), path('reset_password_complete/',auth_views.PasswordResetCompleteView.as_view(),name='Password_reset_complete'), ] -
filter search result based on checkbox Django
Trying to filter products based on brands, with the use of checkboxes. models class Product(models.Model): """ Containing the products, each product belong to a category and each product have a feedback system """ category = models.ForeignKey(Category, related_name='products', on_delete=CASCADE) name = models.CharField(max_length=55) brand = models.CharField(max_length=55) price = models.FloatField() featured = models.BooleanField(default=False) image = ResizedImageField(size=[460,460], quality=100, upload_to='products', default='None', blank=True, null=True) slug = models.SlugField(max_length=400, unique=True, blank=True) description = models.TextField(default='product', blank=True) def __str__(self): return self.name views def products(request, slug): """ List all products of a category """ category = get_object_or_404(Category, slug=slug) products = Product.objects.filter(category=category) brands = Product.objects.filter(category=category).distinct('brand') # query brands and products when pressed list = request.GET.get('list', 'brands') == 'on' if list: products = Product.objects.filter(category=category).filter(Q(name__icontains=list) | Q(brand__icontains=list) | Q(description__icontains=list)) brands = Product.objects.filter(category=category).filter(Q(name__icontains=list) | Q(brand__icontains=list) | Q(description__icontains=list)).distinct('brand') context = { 'products': products, 'category': category, 'brands': brands, 'title': Product, } return render(request, 'products/products.html', context) html <div class="filter-content collapse show flex-wrap" id="collapse_2" style=""> {% for brand in brands.all %} <div class="card-body" id="tabl"> <label class="form-check" onChange="window.location.href=this.value"> <input class="form-check-input" type="checkbox" value="?list=brands" name="brands[]" id="brands{{ brand.id }}"> <span class="form-check-label">{{ brand.brand }}</span> </label> </div> {% endfor %} </div> When the checkbox is pressed, based on the brand.id on the given checkbox, it is supposed to change the query based products of that … -
Facebook Login - Problem redirecting after confirming permission for user info
I need help for the last step of my Facebook login function. The problem is that when a new user signs in for the first time, a popup called 'www.facebook.com/v11.0/dialog/oauth' appears which prompts the new user to confirm that they allow my page to access their information. The issue is that once that user accepts the terms and confirms by clicking the 'continue as name' button, instead of being booted to my home page like I wish it did, the users is kept on my login page instead. They then need to click a second time on the 'Connect by Facebook' button, which is now able to do its job and redirect my users to the proper page. Basically I'm looking for a way to tell the Facebook login to prompt the redirect from the inside of the oauth popup and skip the need for a double click. I have set up my access in JavaScript and my code looks like this: $(document).ready(function(){ $('.login-main').on("click", ".facebook_login_class", function(){ console.log('FACEBOOK LOGIN OPTION SELECTED'); FB.getLoginStatus(function(res){ if(res.status == "connected" ){ console.log('Connected on Facebook'); FB.api('/me?fields=email,name,first_name,last_name', function(fbUser) { $.ajax({ url:'facebook_login_ajax/', method:'GET', data:{ email:fbUser.email, code:fbUser.id, }, success:function(response){ if (response.Success == true){ window.location.href = '/myhomepage/'; } } }); }); … -
My django code is requesting a table that doesn't exist
! ! I tried to delete the 'db.sqlite3' file and do the migration again, but it didn't work -
django run script with on and stop with off button in a view
I am New to django, and i'm in pain right now, i can't find a solution to render a form with data that will go into an python script imported as a class, basically, this process is for freelancer bot, that will keep search project matching the skill tags and then bidding on it, all the data ill provide with a form and when i click "run bot" button the script will continue to run until another button "stop bot", would be pressed, i presented a similar situation corresponding to the real issue for better understanding of the question, html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="{% url 'bid_func' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button value="run-script">Run Bot</button> <button value="stop-script">Stop Bot</button> </form> </body> </html> form is amount = forms.FloatField() interval = forms.IntegerField() max_bid = forms.IntegerField() like below if request is post and run-script in request data, it will start the execuion of the data passed to the script, and when the stop-script is pressed, it will stop the process, def bid_func(request): form = BidBot() if request.method == 'POST': form = BidBot(request.POST) if 'run-script' in request.POST and … -
Populate Dropdown from another Table/View
I have a site model which is connected to the municipality where the site is located. Using this municipality in a dropdown field in the create form leads to quite long loading times. The reason is the large amount of municipalities in the database but also that the administrative units are linked to each other which seems to lead to cascading queries to populate the dropdown field. Is there a way to speed this up? I thought about making a materialized view and use it to populate the dropdown field but that would lead to a value error because the value from the dropdown must be an instance of the linked model as far as I know. Is there maybe another way to make the form load faster? Or is the materialized view the way to go and I am just getting something wrong? class site(models.Model): sid = models.AutoField(primary_key=True) site_name = models.CharField(max_length=250) site_notes = models.CharField(max_length=2500, blank=True, null=True) municipality = models.ForeignKey('local_administrative_unit', on_delete=models.PROTECT) geom = models.PointField(srid=4326) class administrative_level_5(models.Model): al5_id = models.CharField(primary_key=True, max_length=10) al5_name = models.CharField(max_length=150) geom = models.MultiPolygonField(srid=4326) class administrative_level_4(models.Model): al4_id = models.IntegerField(primary_key=True) al4_name = models.CharField(max_length=150) adm_level_5 = models.ForeignKey('administrative_level_5', on_delete=models.PROTECT) geom = models.MultiPolygonField(srid=4326) class administrative_level_3(models.Model): al3_id = models.IntegerField(primary_key=True) al3_name = models.CharField(max_length=150) adm_level_4 … -
Django can't connet to PostgreSQL Docker container via psycopg2
I am trying to migrate a django project on macOS Monterey 12.3, and I am having some troubles. It seems like psycopg2 doesn't want to connect to my docker container at all. Everytime it prints this error: django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 5433 failed: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. For my docker process, I create it by running docker run --name local-postgres -p 5433:5433 -e POSTGRES_PASSWORD=test123 -d postgres I am running python 3.9.12 in a virtual environment using pipenv, and my arch is arm64, for anyone wondering. I've tried changing the ports, I've tried resetting, completely removing docker and downloading it again, reinstalling django and reinstalling the venv again and so far nothing has worked. I've also tried setting the CONN_MAX_AGE=0 in settings, which has not worked. Please help -
Django forms - filter field by user.id
I have the following situation with Django that i cannot resolve. How to filter/sort field 'training' to represent only the trainings that are owned by the user that is logged in. Thank you in advance! class Exercise(mоdels.Model): MAX_LENGTH = 25 name = mоdels.CharField( mаx_length=MAX_LENGTH ) weight = mоdels.IntegerField() series = mоdels.IntegerField() reps = mоdels.IntegerField() training = models.FоreignKey('Workout', оn_delete=mоdels.CASCADE) class CreateExerciseFоrm(forms.ModelFоrm): class Meta: model = SingleExercisе fields = ('name', 'weight', 'series', 'reps', 'training', ) -
Django : Display file content in the same page on the click of a file listed in a table
I have this page where I upload files to a blob storage and then they are listed in a table. I want that the user can visualize the files that he has uploaded. So I would like to add next this two vertical containers, one to display the content of the file when the user clicks on one of the listed files. I have no idea how I should include that on my view "upload" see below. Would it be easier to display it in a new view ? Anyone can show me how I can include that in my view and the template ? Thank you views.py @authenticated_user @check_user_rights() def upload(request, id_contrat): # INITIALIZE THE CONTEXT TO FIX THE AUTHENTICATION context = initialize_context(request) username = request.session.get('user').get('name') ############################################################ # WE SET THE BLOB STORAGE PARAMETER ############################################################ credential = "" account_url = "" container = "" blob_service_client = BlobServiceClient(account_url= account_url, credential= credential) ############################################################ # UPLOAD FILES ############################################################ if request.method == 'POST': form = FilesForm(request.POST, request.FILES) files_selected = request.FILES.getlist('Filename') if form.is_valid(): for f in files_selected : # THE PREVOUS FILENAME IS STORED previous_name = f.name content = f.read() # WE RENAME THE FILE ext = f.name.split('.')[-1] name = f.name.split('.')[0] f.name = "%s_%s.%s" …