Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django modified_at field with database level auto update
I need to have modifed_at fields in my Django project. A field that updates every time a row updates in the database, despite where the update comes from: through calling .save() or through queryset.update() or even when updates happen in the database directly and not from the Django app. there is an auto_now property that does not solve my problem according to this SO question(based on Django document). other SO questions(like this and this) ask the same thing, update instance at every change not only .save() This problem can be solved using triggers as said here but this way we need to write the same trigger for every modifed_at field in models. as discussed in this Django ticket this probelem will not be addressed and solved in Django. even the suggested patch only updates the instance if it changes via Django. the only way that comes to my mind is to do something like this in a mixin. a mixin that when inherited creates a trigger for fields with auto_now=True. maybe change SQL when Django creates the model creation SQL. but I don't know how to implement this. so I have two questions: what is the best way to achieve … -
Corrent Way to Structure Models, Views and Serializers
I have the following structure of Parent and Child models, where the child references the parent. class ParentModel(models.Model): name = models.CharField(max_length=255) class ChildModel(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey( ParentModel, related_name='children', on_delete=models.CASCADE ) created_by = models.ForeignKey(User, on_delete=models.CASCADE) class ParentSerializer(serializers.ModelSerializer): class Meta: model = ParentModel fields = ( 'name', 'children', ) class ChildSerializer(serializers.ModelSerializer): class Meta: models = ChildModel fields = ( 'name' ) class ParentViewSet(viewsets.ModelViewSet): serializer_class = ParentSerializer queryset = ParentModel.objects.all() class ChildViewSet(viewsets.ModelViewSet): serializer_class = ChildSerializer def get_queryset(self): user = self.request.user return ChildModel.objects.filter(created_by=user) I would like for ParentSerializer.children to only include the ChildModel objects with created_by as self.request.user. What is the correct way to filter ParentSerializer.children to the current user? I am open to changing the models as well. -
Create button to update in django posts with javascript fetch
I have an html that displays user's posts. At the same time, the post model is accessible via fetch (javascript). I want to create a button to update the content of the posts that django shows but with the fetch. The problem is that when the button is created in my code, instead of creating a button for each post, it creates 5 update buttons in the first post and it is logical because that is the id that I give it. How can I add a button to each of the posts that django shows with javascript? Note: the project its a test for the real project. I want to add a update button with javascritp in a django posts for update a field My html: <div id="formulario" class="form-style" style="border: 5px solid rgb(255, 170, 0);"> <h1>User's Posts</h1> {% for post in object_list %} <div id="posts-div" style="border: 5px solid red;"> <h3 id="user">{{post.usuario}} - User with id: {{post.id}}</h3> <h3>{{post.contenido}} - {{post.id}}</h3> </div> {% endfor %} <h1>Agregar</h1> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> </div> My views.py class PostsViewSet (viewsets.ModelViewSet): queryset = Posts.objects.all() serializer_class = PostsSerializer class PostView(CreateView, ListView): model = Posts fields = ['contenido','edad','usuario'] template_name = 'api_app/posts.html' … -
How to use ColorThief with Django Rest Api?
I'm very beginner with coding. I want to get a dominant color from pictures. Color have to be saved and showed as a hex code. For now i have created simple code with picture name, width and height. I don't know how to implement ColorThief to this small project. In models file at the bottom i have created some code which i don't know how to run. Here are some of my files: Models: from django.db import models from colorthief import ColorThief class UploadImage(models.Model): name = models.CharField( 'Name', max_length=100, ) image = models.ImageField( 'Image', upload_to='uploaded_media/', width_field='width', height_field='height', ) height = models.PositiveIntegerField( 'Image Height', blank=True, null=True, ) width = models.PositiveIntegerField( 'Image Width', blank=True, null=True ) def __index__(self): color_thief = ColorThief(self.image) self.image = (color_thief.get_color(quality=1),) self.save() return f'#{self.image[0]:02x}{self.image[1]:02x}{self.image[2]:02x}' Viewsets: from rest_framework import viewsets from rest_imageupload.serializers import UploadImageSerializer from imageupload.models import UploadImage class UploadImageViewSet(viewsets.ModelViewSet): queryset = UploadImage.objects.all() serializer_class = UploadImageSerializer Serializers: from rest_framework import serializers from imageupload.models import UploadImage class UploadImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImage fields = ('name', 'image', 'width', 'height') -
django-allauth messages not being displayed correctly
I'm using django-allauth in a project but unfortunately the messages on login and logout are not being displayed correctly. For example when I logout this message appears: <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f5b3f2c5e48> I've tried to reinstall Django and django-allauth but it hasn't fixed the problem. Any help/pointers much appreciated. -
One Wagtail API endpoint with different ViewSets
I'm using Wagtail API to set up a site with a single endpoint, but different Page types under that endpoint. In short, I have two models class TeamPage(Page) and class BlogPage(Page): and I want the following url paths GET /teams - TeamsAPIViewSet.listing_view to return a list of all TeamPages GET /teams/<slug> - TeamsAPIViewSet.detail_view to return the detail for a single TeamPage GET /teams/<slug>/blogs - BlogsAPIViewSet.listing_view to return a list of all BlogPages for a specific team GET /teams/<slug>/blogs - BlogsAPIViewSet.detail_view to return a specific BlogPage Registering the "teams" endpoint in api.py only allows a single ViewSet for that endpoint api_router.register_endpoint('teams', TeamsAPIViewSet) so, /api/teams will always use the TeamsAPIViewSet. I tried setting up paths in urls.py as follows: path('api/teams/', TeamsAPIViewSet.as_view({"get": "listing_view"}), name="listing"), path('api/teams/<slug:slug>/', TeamsAPIViewSet.as_view({'get': 'detail_view'})), path('api/teams/<slug:team_slug>/<slug:slug>', ContentAPIViewSet.as_view({'get': 'detail_view'})), path('api/teams/<slug:team_slug>/blogs/', BlogsAPIViewSet.as_view({'get': 'listing_view'})), path('api/teams/<slug:team_slug>/blogs/<slug:slug>/', BlogsAPIViewSet.as_view({'get' : 'detail_view'})), but that throws an exception, 'Request' object has no attribute 'wagtailapi_router' Any suggestions are appreciated. -
process remind to user on exact date and time in django
So I have notification system in place.For example when sending a task to user, user get a notification within my system. Right now I have only "instant" notifications. so when I send a task to someone, a notification is created in the db, and via web-socket the user is notified with the data of the notification. With the Reminder I have the problem, that the notification I want to send here is not necessarily "instant". I want to set the date to next Monday on 9 am. so User should receive the notification on Monday 9 am. Question: Is there an extension in django (or onboard methods) where I can execute stuff delayed? For example, send notification with the following data on Monday 9 am. -
How do I send available_apps in context to a view that is outside the admin panel in Django?
How can I get an application list like in get_app_list method in classy AdminSite? I try to do it this way, but then I get an empty list. from django.contrib.admin.sites import AdminSite def change_view(self, request): ... context = { ... 'available_apps': AdminSite().get_app_list(request) } return render(request, 'parts/part_form.html', context=context) I need this to display the admin side menu outside the admin panel. -
Syntax error in Django Mysql Migration running on Mac
Exception: ~/devel/project/project$ poetry run python manage.py migrate Operations to perform: Apply all migrations: account, admin, alerts, auth, business, chat, contact, contenttypes, critique, curriculum, django_cron, djstripe, gear, guardian, hosted_media, jobs, news, newsletter, promo, registration, robots, seminars, sessions, sites, socialaccount, taggit, thumbnail, users Running migrations: Applying djstripe.0008_auto_20150806_1641_squashed_0031_auto_20170606_1708...Traceback (most recent call last): File "/Users/martincho/Library/Caches/pypoetry/virtualenvs/project-FB7eKST1-py3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/Users/martincho/Library/Caches/pypoetry/virtualenvs/project-FB7eKST1-py3.9/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/Users/martincho/Library/Caches/pypoetry/virtualenvs/project-FB7eKST1-py3.9/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/Users/martincho/Library/Caches/pypoetry/virtualenvs/project-FB7eKST1-py3.9/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/Users/martincho/Library/Caches/pypoetry/virtualenvs/project-FB7eKST1-py3.9/lib/python3.9/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'"djstripe_invoice" SET "attempts" = 0 WHERE "attempts" IS NULL\' at line 1') This is a djstripe migration which I can't modify. Versions: ~/devel/project/project$ poetry show django name : django version : 2.2.28 description : A high-level Python Web framework that encourages rapid development and clean, pragmatic design. ~/devel/project/project$ poetry show dj-stripe name : dj-stripe version : 1.1.1 description : Django + Stripe Made Easy ~/devel/project/project$ poetry show mysqlclient name : mysqlclient version : 2.1.1 description : Python interface to MySQL MySQL version is … -
Do null foreign keys slow things down?
I'm implementing file attachments for certain objects in the project I am working on. There are six or so object classes which might reasonably have attached files (which would be revealed in their Detail views and managed via a link from there). The model would be like class JobFile( models.Model): job = models.ForeignKey( 'jobs.Job', models.SET_NULL, null=True, blank=True, related_name='attachments', ) quote = models.ForeignKey( 'quotation.Quote', models.SET_NULL, null=True, blank=True, related_name='attachments', ) #etc document = models.FileField( ... ) # the attachment One advantage of this rather than a Generic ForeignKey is that an upload can be attached to more than one sort of object at once. Another is the simplicity of referring to obj.attachments.all() in the obj detail views. I'm not looking for a large set of object classes to which these files might be attached. However, for any one file attachment most of its ForeignKeys will be null. I have seen various references to null ForeignKeys causing slow Django ORM queries. Is this anything I need to be concerned about? If it makes any difference, these objects will be almost exclusively accessed via the attachments reverse ForeignKey manager on the related object. The only time I can see a need for explicit filtering … -
Here is another question on No module named 'rest_framework_jwtmusicapp' musicapp being the name of the app i'm worrking on
I have installed the djangorestframework-simplejwt but i still get this red zig-zag underline on this import statement from rest_framework_jwt.settings import api_settings this is from veiws.py and here is the error code from my terminal (venv) C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\songcrud>python manage.p y 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.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework_jwtmusicapp' (venv) C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\songcrud>python -m pip install djangorestframework Requirement already satisfied: djangorestframework in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (3.10.0) (venv) C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\songcrud>python -m pip install djangorestframework-simplejwt Requirement already satisfied: djangorestframework-simplejwt in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (5.2.2) Requirement already satisfied: pyjwt<3,>=1.7.1 in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from djangorestframework-simplejwt) (2.6.0) Requirement already satisfied: djangorestframework in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from djangorestframework-simplejwt) (3.10.0) Requirement already satisfied: django in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from djangorestframework-simplejwt) (4.1.3) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from django->djangorestframework-simplejwt) (0.4.3) Requirement … -
Why I got "http://~" as redirect url parameter althoguh I set "https://~" to LOGIN_REDIRECT_URL in mozilla-django-oidc?
I've been trying to integrate Django app with Keycloak using mozilla-django-oidc and fix the problem as refered to in the title. I configured LOGIN_REDIRECT_URL and the configurations that are required in settings.py LOGIN_REDIRECT_URL = "https://~" and prepared Django template. {% if request.user.is_authenticated %} \<p\>Current user: {{ request.user.email }}\</p\> \<form action="{{ url('oidc_logout') }}" method="post"\> {{ csrf_input }} \<input type="submit" value="logout"\> \</form\> {% else %} \<a href="{{ url('oidc_authentication_init') }}"\>Login\</a\> {% endif %} However I clicked the Login link, then I got the error message which says invalid redirect url because redirect url parameter was changed to http://~. I looked through the code of mozilla-django-oidc, and seemed that there's no function changing "https://~" to "http://~" as redirect url parameter and I set "https://~" to LOGIN_REDIRECT_URL so there might be something wrong with reverse proxy which is Istio in my case. I haven't configured anything by myself so far. In case of using Ngnix, this problem can be solved like this. I'd like you to answer what's the cause of problem and how to fix it. I appreciate for your time to read this. -
AlterField shows the error `Duplicate key name`
In my migration file, there is the AlterField like this migrations.AlterField( model_name='historicalglobalparam', name='history_date', field=models.DateTimeField(db_index=True), ), my table historicalglobalparam has history_date column When appling this $python manage.py migrate The error appears django.db.utils.OperationalError: (1061, "Duplicate key name 'shared_models_historicalglobalparam_history_date_26e0c543'") However there comes error like this. I wonder it's AlterField not AddField Why this erorr comes? -
This site can’t be reached domain.de refused to connect
I have a project, Frontend with Flutter and Backend with Django. It was working fine. I wanted to change HTTP to HTTPs. now I am getting the error This site can’t be reached domain.de refused to connect The Nginx file for the Frontend: server { server_name visoon.de; root /home/visoon_frontend/build/web; index index.html; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/visoon.de/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/visoon.de/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } server { if ($host = visoon.de) { return 301 https://$host$request_uri; } listen 80; server_name visoon.de; return 404; } And Nginx file for the Backend: upstream visoon_app_server { server unix:/home/visoon_backend/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name visoon.de; client_max_body_size 4G; proxy_read_timeout 1200s; access_log /home/visoon_backend/logs/nginx-access.log; error_log /home/visoon_backend/logs/nginx-error.log; location /static/ { alias /home/visoon_backend/visoon_backend/static/; expires -1; } location /media/ { alias /home/visoon_backend/visoon_backend/static/media/; expires -1; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; # proxy_buffering off; if (!-f $request_filename) { proxy_pass http://visoon_app_server; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/visoon_backend/visoon_backend/static/; } } Does anyone know why I am getting this error? many thanks for considering my request. -
how to i save data in django after i filter in forms using kwargs.pop?
when a try to filter category to match user it works but I can't save data to the form anymore and it show any error? forms.py: from django import forms from django.forms import ModelForm from .models import Createservice from .models import Category class Serviceform(ModelForm): class Meta: model = Createservice fields = ['user', 'Service_name', 'description', 'your_sertificate', 'category'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(Serviceform, self).__init__(*args, **kwargs) print(self.user) if self.user is not None: self.fields['category'].queryset = Category.objects.filter( wilaya=self.user.wilaya) views.py: @login_required def createservice(request): if request.method == 'POST': user = request.user services = Serviceform(request.POST,request.FILES, user=user) if services.is_valid(): servicess = services.save(commit=False) servicess.user = user servicess.save() return redirect('index') else: user = request.user services = Serviceform(user=user) context = {"service": services} return render(request, 'services/createservice.html', context) createservice.html: <form action="{% url 'create-service' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="col form-group"> <label>Service_name</label> {{service.Service_name}} </div> <!-- form-group end.// --> <div class="col form-group"> <label>Description</label> {{service.description}} </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>your_sertificate </label> {{service.your_sertificate}} </div> <!-- form-group end.// --> <!-- form-group end.// --> </div> <!-- form-row.// --> <!-- form-row.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>select your category </label> {{service.category}} </div> <!-- form-group end.// --> <!-- form-group end.// --> </div> <!-- … -
Some static files showing some not in django project . Why?
[ As about.jpg runs but doesnt runs building.jpg is written. urlpatterns = [ path('', include('pages.urls')), path('listings/', include('listings.urls')), path('accounts/', include('accounts.urls')), path('contacts/', include('contacts.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Rest API instead of table in Django Proxy unmanaged models
In my Django arch. task I must connect multiple projects. Some can only communicate through REST API and don't have common database access. However, the task is to provide seamless communication on model level. I.e. my model should serve as a wrapper for read requests in such a way, that business layer does not see the difference between local models and models that wrap remote data. Assuming that inherited create-delete-update methods will do nothing. I have read these: Proxy models documentation Unmanaged models documentation Also documentation on creation of custom managers and querysets. However, not a single good example for what I am set to achieve. Perhaps you can provide a solid Django example how to modify manager and query set in this way? -
Invalid block tag on line 95: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? plz solve this
TemplateSyntaxError at /product/df/ Invalid block tag on line 95: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? i got this error when i making a ecommerce app ` </div> <!-- col.// --> {% if product.size_variant.count %} <div class="form-group col-md"> <label>Select size</label> <div class="mt-1"> {% for size in product.size_variant.all %} <label class="custom-control custom-radio custom-control-inline"> <input type="radio" onclick="get_correct_price('{{size.size_name}}')" name="select_size" {% if selected_size==size.size_name %} checked {% endif %} class="custom-control-input"> <div class="custom-control-label">{{size.size_name}}</div> </label> {% endfor %} ` please solve this problem -
Django, how to refresh html page not in urls.py only included with tags
I am working on an app that utilizes the {% include %} tags to build pages. Basically I have a layout.html that serves as the base and it has an include tag for the navbar.html and {% block content %} for other pages e.g. home, login, user etc. In the navbar.html there is another {% include %} for my notification.html which contains the badge icon for notifications. I am using django-notifications-hq to handle the notifications. Everything works, but to get new notifications, I have to refresh the page. I want the badge (or notifications.html) to update periodically. Here are the html pages, the layout.html, navbar.html and notification.html; they are not in the urls.py file, simply called via tags. layout.html {% load static %} <!DOCTYPE html> <html> <head> <title>Application</title> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap.min.css' %}" /> <link href="{% static 'css/login.css' %}" rel="stylesheet"> <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'javascript/tablesorter.js' %}"></script> <script type="text/javascript" src="{% static 'javascript/refreshpage.js' %}"></script> </head> <body> <div id="notifylist"> {% include 'VegeApp/navbar.html' %} </div> <hr /> {% if messages %} <ul class="alert"> {% for message in messages %} {% if message.tags == 'debug' %} <li class="alert alert-secondary">{{ message }}</li> {% endif %} {% if message.tags … -
Use OpenCellID data local in python to lookup single locations
I'm trying to host the OpenCellID dataset world (https://opencellid.org/downloads.php?token=world) local. Note: I have to run that local, because the machine has no connection to the internet (for the opencellid api) My usage: I am using django as a backend in python. I upload a file there with cellid data, which I want to convert to lat:long and import that set into the database. The opencellid dataset is very huge, so it's expensive to read the file all the time. Input: MCC-MNC-LAC-CellID Output lat:long from the specific line in the opencellid dataset I was reading the csv with pands, but It takes a lot of power and time to read it into a variable. -
Django Channels websocket error while building the tutorial
I'm using django channels tutorial and I did whatever there was in the tutorial , and I'm getting error from my Terminal while I click the send button of my message which is: "GET /ws/chat/lobby/ HTTP/1.1" 404 2232 my routing.py file : from django.urls import re_path from .consumers import ChatConsumer websocket_urlpatterns = \[ re_path('ws/chat/\<room_name\>', ChatConsumer.as_asgi()), \] my consumers.py : import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_dict = json.loads(text_data) message = text_data_dict['message'] self.send(text_data=json.dumps({ 'message': message })) views.py : from django.shortcuts import render def index(request): return render(request, "chat/index.html") def room(request, room_name): context = { "room_name": room_name } return render(request, 'chat/room.html', context) urls.py : from django.urls import path from .views import index, room urlpatterns = [ path('', index, name='index'), path('<str:room_name>/', room, name='room') ] asgi.py file : import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import Chat.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( Chat.routing.websocket_urlpatterns ) ), }) and my room.html file : <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br> <input id="chat-message-input" type="text" size="100"><br> <input id="chat-message-submit" type="button" value="Send"> {{ room_name|json_script:"room-name" }} <script> const roomName = … -
How can I assign different platform ID to multiple candidates before saving it to the database?
I have a formset that takes in 7 candidates and each candidate should have a platform id. When I try to assign a platform to a candidate in a for loop, it only assigns the first platform ID to all candidates. here is my view fuction. def addcandidate(request): party = PartyList.objects.all() partylist_form = PartylistForm() PlatformSet = formset_factory( PlatformForm,extra=7) candidateFormSet = formset_factory(CandidateProfileForm,extra=7) form1 = PlatformSet(prefix='platform') form2 = candidateFormSet(prefix='candidate') if request.method == 'POST': partylist_form = PartylistForm(request.POST) form1 = PlatformSet(request.POST, prefix='platform') form2 = candidateFormSet(request.POST,request.FILES,prefix='candidate') if form1.is_valid() and form2.is_valid() and partylist_form.is_valid(): try: partylist = PartyList.objects.get(partylist_name=request.POST['partylist_name']) except ObjectDoesNotExist: partylist = partylist_form.save() for f1 in form1: p1 = f1.cleaned_data['platform'] p2 = f1.cleaned_data['platform2'] p3 = f1.cleaned_data['platform3'] try: Platform.objects.get(candidate_platform=p1) except ObjectDoesNotExist: platform = Platform(candidate_platform=p1,candidate_platform2=p2,candidate_platform3=p3) platform.save() for count,f2 in enumerate(form2): name = f2.cleaned_data['name'] img = f2.cleaned_data['Candidate_Img'] try: CandidateProfile.objects.get(name=name) except ObjectDoesNotExist: candidate = CandidateProfile(Candidate_Img=img,name=name) candidate.save() candidate.platform = platform candidate.partylist = partylist if count == 0: candidate.position = Position.objects.get(id=1) elif count == 1: candidate.position = Position.objects.get(id=2) elif count == 2: candidate.position = Position.objects.get(id=3) elif count == 3: candidate.position = Position.objects.get(id=4) elif count == 4: candidate.position = Position.objects.get(id=5) elif count == 5: candidate.position = Position.objects.get(id=6) elif count == 6: candidate.position = Position.objects.get(id=7) candidate.save() return redirect(request.META['HTTP_REFERER']) else: print(form1.errors) print(form2.errors) print(form1.non_form_errors) print(form2.non_form_errors) context = … -
Boto3, how to disable ACL when using generate_presigned_url?
I keep getting this error: An error occurred (AccessControlListNotSupported) when calling the PutObject operation: The bucket does not allow ACLs I'm switching to chunked uploads, previously i could do below and this uploaded fine. original = models.FileField(storage=S3Boto3Storage(bucket_name='video-sftp',default_acl=None),upload_to='', blank=False, null=False) Now i'm using generate_presigned_url and the ACL parameter is being ignored. url = client.generate_presigned_url( ClientMethod="put_object", Params={ "Bucket": "video-sftp", "Key": f"{json.loads(request.body)['fileName']}", "ACL": "None" }, ExpiresIn=300, ) How do i solve? -
How to connect to a postgres database in a docker container?
I setup my django and postgres container on my local machine and all working fine. Local server is running, database running but I am not being able to connect to the created postgres db. docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=my_user - POSTGRES_PASSWORD=my_password - POSTGRES_DB=my_db volumes: postgres_data: I tried this command: docker exec -it container_id psql -U postgres error: psql: error: could not connect to server: FATAL: role "postgres" does not exist I am very new to Docker. -
Dajngo admin: more "view on site" alternatives
I am creating a fairly standard CRUD application with Django. For now I have chosen an approach where the common/complex properties can be edited using custom forms and the more exotic elements of the application must be edited with the django admin - works quite nicely. In the Django admin I really like the "View on site" link which will take me to view an object on the site. Now I would really like to other "call back into the site" functionalities: From the list view in django admin I would like to be able to have a "View on site" which takes me to a "list view" in the application. From the application view in Django admin it would be nice to have a "View on site" which takes me to an "application root" in the application. Are any such things available?