Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django admin is not accesible when DEBUG=False
I'm writing the backend for my app using django and django-rest-framework. The problem I have is that when I set DEBUG=False in my settings, the admin site (along with the browseable rest API) is no longer available, and I got a 500 response. The rest when queried/posted using JSON still works normally. This is my urlspatterns (I also tried including /admin at the top of the list) urlpatterns = [ path("", index, name="index"), path("api/", include(router.urls)), path("admin/", admin.site.urls), path("api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] Since I'm creating my app using react, I'm testing a project structured in a way that all the django apps are contained in the same folder, being the main app: backend. I had to make some minor changes in the apps to accommodate this structure. For instance, this is an excerpt of how the installed apps: INSTALLED_APPS = [ ... "rest_framework", "backend", "backend.projects", "backend.tasks", "backend.subtasks", "backend.comments", ] And this is a capture of the folder tree. I think it must be something that changes in app/template discovery when changing from DEBUG=True to False. Point out that everything else apart from that works correctly: the root of my backend is serving the react app correctly, rest API works correctly as … -
Send data to my views.py: CSRF token missing
I have an html page which allows to send the contents of a csv file. From a javascript file I do different processing on the content. Then I would like to send to my view to add it to my database. When i click on the button i get this error: Forbidden (CSRF token missing.): /app/addDataInDB [11/Nov/2022 14:06:56] "POST /app/addDataInDB HTTP/1.1" 403 2506 .html <form id="myForm" method="POST"> {% csrf_token %} <input type="file" id="csvFile" accept=".csv" /> <br /> <button type="submit">Envoyer</button> </form> ... <script src="{% static 'js/readCSV.js' %}"></script> .js const form = document.getElementById('myForm') form.addEventListener('submit', sendData); function sendData(event){ event.preventDefault(); const res = { 0:{"val1": 1, "val2":2}, 1:{"val1": 3, "val2":4}} $.ajax({ type: "POST", url: 'addDataInDB', data: { "result": res }, dataType: "json", success: function (data) { alert("successfull") }, failure: function () { alert("failure"); } }) } app/urls.py from django.urls import re_path from . import views urlpatterns =[ re_path(r'^addDataInDB$', views.addDataInDB, name='addDataInDB'),] app/views.py def addDataInDB(request): if request.method == "POST": print(request.POST) -
get select option selected on form submit
how to get select option selected on form submit in html, I am creating project in Django, where i am using few bootstrap fields, my problem is that when I submit form bootstrap select options get their default value which I do not want, I want to get selected option selected rather their default value, please let me know if anyone have any idea I have tried few Jquery methods which did not worked for me. -
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 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", then I got the error message which is 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 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 it to 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. -
AttributeError at /login/ 'NoneType' object has no attribute 'has_header'
Я делаю авторизацию на сайте django, используя этот гайд: https://proproprogs.ru/django/delaem-avtorizaciyu-polzovateley-na-sayte. Я создал views class LoginUser(DataMixin, LoginView): form_class = AuthenticationForm template_name = 'shop/login.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title="Авторизация") return dict(list(context.items()) + list(c_def.items())) потом в urls.py добавил path login urlpatterns = [ path('', index, name='index'), path('add_product', add_product, name='add_product'), path('login/', LoginUser.as_view(), name='login'), ] но при переходе на сайт через http://127.0.0.1:8000/login/ у меня появляется ошибка AttributeError at /login/ 'NoneType' object has no attribute 'has_header' Пытался гуглить но там конкретно такой проблемы как у меня не было, в основном писали про render и HttpRequest, но в моем коде его даже негде написать. Пытался гуглить но там конкретно такой проблемы как у меня не было, в основном писали про render и HttpRequest, но в моем коде его даже негде написать. -
The view products.views.get_product didn't return an HttpResponse object. It returned None instead
ValueError at /product/apple-ipad-air-5th-gen-64-gb-rom-109-inch-with-wi-fi5g-purple/ The view products.views.get_product didn't return an HttpResponse object. It returned None instead. how can i solve this problem please help me ` from django.shortcuts import render,redirect from products.models import Product from accounts.models import * from django.http import HttpResponseRedirect from products.models import * from django.utils.timezone import datetime # Create your views here. def get_product(request, slug): product = Product.objects.get(slug=slug) # comment = Comment.objects.get(slug=slug) if request.method == "POST": star = request.POST.get('star') name = request.user.first_name body = request.POST.get('body') review = Comment(star=star, name=name,body=body,date_added = datetime.today()) review.product = product review.save() return redirect(f'/product/{slug}', slug=product.slug) try: context = {'product': product, } if request.GET.get('size'): size = request.GET.get('size') price = product.get_product_price_by_size(size) context['selected_size'] = size context['updated_price'] = price return render(request, 'product\product.html' , context = context) except Exception as e: print(e) ` i am making a ecommerce website and i add review option then i got this error -
Display messages/notifications in NetBox
I would like some help with messages in NetBox, please. I'm writing a custom validator and I need to display a warning message if for example a device name doesn't fit the company's policy. I can't use the standard fail method in the CustomValidator class - the edit request should be fulfilled, it's just supposed to warn the user as well. I would like to use a box message like this one, just with the warning level. I tried something like this: from extras.validators import CustomValidator from django.contrib import messages class device_validator(CustomValidator): def validate(self, instance): if instance.name is not instance.name.upper(): messages.info(request, "Names of devices should be in all-caps.") return But clearly, my syntax is wrong. I get the "Server Error" window and following message: <class 'NameError'> name 'request' is not defined How do I define the request? Could someone please give me an example how to display a message in this context? Thank you. -
How to create a Django project that allows a User to install plugins from a marketplace Just like WordPress
I would like to create a Django project that allows me to sell services as packages. Here I mean, Users should visit my market place, choose a package they want, then click on Install. Just Like WordPress. This process should automatically do configurations in the background including running the required pip install app commands add the app into installed apps make necessary migrations collect static files I'm confused on how to implement this, and need your help on this. I have been able to create a Django project, and am able to package convert apps into packages. I also understand the consequences of conflicts in migrations and circular dependencies associated with multiple apps. What I want is to allow a user of my system to be able to install a package whenever they need to add it on their options, by just clicking install. -
add a custom attribute to the form using a class based view without use ModelForm class in django
is possible to add a custom attribute (like class="form-control") in all forms of a class based view without define ModelForm? -
Django Add 2 Numbers and get Name and print it back in an html
I'm new to python and django What is the correct syntax to render number and text? I want to get the name and add 2 numbers from addition.html and print it back to results.html I tried this code def add(request): my_context = { "fname" : (request.GET['first_name']), val1 = int(request.GET['num1']), val2 : int(request.GET['num2']), res : val1 + val2 #return render(request, "result.html", {'result': res}) } return render(request, "result.html",my_context) -
how to send data using FCM without a notification message
I am using FCM for my app, which uses Django as the back end and the front end written by flutter. I can send notifications from my Django app in certain situations and it works as expected. All I need now is to send some data to the flutter app which will behave on it somehow, but without sending a message or notification to the user. here is how am sending notifications from my Django backend : from pyfcm import FCMNotification push_service = FCMNotification(api_key="****") def send_single_notification(deviceID,title,body): try: push_service = FCMNotification(api_key="****") registration_id = deviceID message_title = title message_body = body result = push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) except: print("failed to send notification") def send_multi_notification(list_of_ids,title,body): try: registration_ids = list_of_ids message_title =title message_body = body result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body) except: print("failed to send notification") just need to send only data .. -
How to render Nextjs pages using django-nextjs on Django
I'm getting ERR_TOO_MANY_REDIRECTS everytime that I'm trying to load http://localhost:8000/about/ despite localhost:8000 loading the next index page correctly. my next about page: function about() { return <h1>about</h1>; } export default about; Django Views from django.http import HttpResponse from django_nextjs.render import render_nextjs_page_sync def index(request): return render_nextjs_page_sync(request) def about(request): return render_nextjs_page_sync(request) Django urls from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("", include("django_nextjs.urls")), path("", views.index, name="index"), path("about/", views.about, name="about"), ] https://github.com/QueraTeam/django-nextjs have been following django-nextjs offical docs. Is there something that I'm missing? -
A function passed to Response(APIView) prints normally, but in response returns none
Made a function to generate a report about different models. Applied it on a specified url 'report/', need to make it write "Report "" generated" in a view, but it writes "none", but it prints normally what i need. views.py class Report(APIView): def get(self, request): ro = ADMReport() courses_report = ro.course_report(ro.course_qs) groups_report = ro.studentgroup_report(ro.studentgroup_qs) result1 = ro.report_generating(groups_report) print(result1) result2 = ro.report_generating(courses_report) print(result2) return Response({'Done: ': result1}) services.py class FileManager: @staticmethod def pd_to_excel(report_tuple): report, name = report_tuple pd_report = pd.DataFrame(report, index=list(report.values())[0].keys(), columns=report.keys()) pd_report.to_excel(f'{slugify(name)}_report.xlsx', sheet_name='Sheet1') return f'Report "{name}" generated' urls.py urlpatterns = [ path('', include(router.urls)), # 127.0.0.1/api/v1/courses, 127.0.0.1/api/v1/groups path('report/', Report.as_view(), name='report') Expecting passing returned result looking as "Report "%name%" generated" to APIView instead of "none". -
Is root urls.py means config/urls.py in Django?
I am super newbie on programming using django as a backend. I am making a login function with JWT (using simplejwt). Trying to make it while watching simplejwt official doc, I don't know what is root urls.py means in doc. In the first line of the above picture. "root urls.py" === config/urls.py ?? Am I right...? -
Django and whitenoise - caching "too much"
I am using Whitenoise to serve static files (images, css, js) for a Django site. Now my problem is that the static files seem to be "cached to much"(?) when working locally. Description of actions: Initially my static files are served correctly I edit a file in static/ I run ./manage.py collectstatic (which correctly identifies one updated file). When going to http://127.0.0.1:8000/ my browser consistently shows the old stale version of the file. I have even tried completely removing the generated staticfiles/ folder - and the browser still seems to be able to dig out an old version of the file? This is when running locally in debug mode. Do not have a consistent understanding of how it is in production, but I think it works better (as it should?) there. My configuration: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', .... INSTALLED_APPS = [ # My apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... ... STATIC_URL = 'static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ ("js" , BASE_DIR / "static/js"), ("css" , BASE_DIR / "static/css"), ("img" , BASE_DIR / "static/img") ] I guess the problem is that I do not really understand the Whitenoise model … -
Django built-in login failed from react
django @method_decorator(csrf_exempt, name='dispatch') class UserLoginView(GenericAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) user = serializer.validate(request.data) if user is None: return Response(status=status.HTTP_400_BAD_REQUEST) else: user.before_last_login = user.last_login login(request, user) user.save() user = UserSerializer(user) return Response(data={'id': user.data['id'], 'img': user.data['image']} , status=status.HTTP_200_OK) react const res = await axios.post(`${APIURL}/account/login/`, { id: id, password: pwd, }); when I try to login from react, I get suceessful response( Response(data={'id': user.data['id'], 'img': user.data['image']}, status=status.HTTP_200_OK) ) but failes, still user is annonymousUser in django. How can I fix this error? -
Django. I can't understand the error of removing products from the catalog
I'm making a catalog, I can't understand why products are not displayed by catalog categories, it gives an error 404. The sections in the catalog work as they should. Here is the code: I am grateful in advance for any hint! models.py ` from django.db import models from django.urls import reverse class Catalog_text(models.Model): text_left = models.TextField('Text1') text_right = models.TextField('Text2') signature = models.CharField(max_length=255, verbose_name="Signature") class Meta: verbose_name = 'Text1' verbose_name_plural = 'Text2' class Catalog(models.Model): sections = models.CharField(max_length=150, db_index=True, verbose_name="Name") img = models.ImageField(upload_to='img/catalog/') slug = models.SlugField(max_length=150, db_index=True, unique=True, null=True) class Meta: ordering = ('sections',) index_together = (('id', 'slug'),) verbose_name = 'catalog' verbose_name_plural = 'catalogs' def __str__(self): return self.sections def get_absolute_url(self): return reverse('catalog', kwargs={"slug": self.slug}) class Category(models.Model): catalog = models.ForeignKey(Catalog, related_name='catalog', on_delete=models.CASCADE, verbose_name='Select a directory' ) name = models.CharField(max_length=150, db_index=True, verbose_name="Name") img = models.ImageField(upload_to='img/catalog/') slug = models.SlugField(max_length=200, db_index=True, unique=True, null=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('catalog-detail', kwargs={"slug": self.slug}) class Product(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE, verbose_name='Select a category' ) name = models.CharField(max_length=255, db_index=True,unique=True, null=True, verbose_name="Название") text = models.TextField('Текст') url = models.CharField(max_length=255, db_index=True, verbose_name="Link to the website") pdf = models.FileField(upload_to='pdf/') slug = models.SlugField(max_length=200, db_index=True, unique=True, null=True) class … -
pass loop from view.py to html template in Django
I try to get the data in my models "Machines" and then need to get Additional information form other table related to each machine. I try bellow code in views.py and render it to specified html page. def allmachinesLOGO(request): machines=Machine.objects.all() c="" for m in machines: if m.tb_order_set.filter(status="2").exists(): c="2" else: c="0" context ={'machines':machines,'condition':c} return render(request,'pline/machineslogos.html',context) {% if condition == "2" %} <h4> working</h4> <img class="btn-circle" style="width: 15px" src="{% static 'images/icons/icons8-green-circle-48.png' %}" alt="image" /> {% else %} <h4>stop</h4> {{ condition }} <img class="btn-circle" style="width: 15px" src="{% static 'images/icons/icons8-red-circle-48.png' %}" alt="image" /> {% endif %} what's the correct way to pass loop from views.py to template in Django -
Image files were deleted by itself in AWS-S3
I'm using python Django framework for server and AWS-S3 for store uploaded image. Also, i'm using django-storages library for handle S3. But sometimes images were deleted by itself not through django server. Image urls were still exist in DB. So i changed create, put, delete, get action to get in bucket policy But still deleted by itself. django-storages setting in settings.py is this AWS_SECRET_ACCESS_KEY = S3['secret_key'] AWS_REGION = 'ap-northeast-2' AWS_STORAGE_BUCKET_NAME = 'loopusimage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.%s.amazonaws.com' % ( AWS_STORAGE_BUCKET_NAME, AWS_REGION) AWS_DEFAULT_ACL = None DATA_UPLOAD_MAX_MEMORY_SIZE = 1024000000 FILE_UPLOAD_MAX_MEMORY_SIZE = 1024000000 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage and changed bucket policy is this "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::loopusimage/*" } ] } What should i do to solve my problem? -
Django disable ForeignKey field in Form
I've been working on a project lately, and I want to disable fields based on different conditions. Now what I wanted to was disabling a models.ForeignKey. But this doesn't work, even though I tried many solutions from multiple forums. I tried this: self.fields["area"].widget.attrs["disabled"] = True``` I already used this in other projects and it worked totally fine. But the select in the Form is still clickable and you can change the choices. Also I tried disabling it in the Widgets directly, didn't work either. -
At the django-admin statics not lodaing /static/admin/css/base.css not found
urlpatterns = [some_urls] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] statics configured DEBUG = TRUE python manage.py collectstatic did 1000 times cache cleared I have no idea what to do, can anyone help me please