Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing static path to included template
Is it possible to pass a static path as a variable to an included template? I need to repeatedly include a template on my page but its always with different logos. For example: {% with img={% static 'img/dashboards/belgium_flag.svg' %} %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} {% with img={% static 'img/dashboards/netherlands_flag.svg' %} %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} This doesn't work.. Is there any workaround to this besides creating a model to support an image attribute to each Country instance? -
sending an email manually in Django admin panel, and show a successful alert instead of redirect
this my view.py: from django.contrib import messages from django.core.mail import send_mail from django.shortcuts import redirect from django.http import HttpResponse def sendmail(request): if request.method == 'GET': send_mail('this is subject', 'Hello alex', "mysite.com <orders@mysite.com>", ['reciver_email@gmail.com'], fail_silently=False) return HttpResponse('ok') this my app.url.py: from django.urls import path from . import views urlpatterns = [ path('/redirect/' , views.sendmail, name='sendmail'), ] this my url.py: urlpatterns = [ path('', include('register.urls')), path('admin/', admin.site.urls), ] this is my change_form.html that override admin templates: {% extends "admin/change_form.html" %} {% load i18n %} {% block submit_buttons_bottom %} <a href="{% url 'sendmail'%}"> <input type="button" value="Click" name="mybtn" /></a> {% if messages %} <ul class="messagelist">{% for message in messages %}<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>{% endfor %}</ul> {% endif %} {{ block.super }} {% endblock %} and this my app image: my app when I click on the button the email was sent. look at this but, I want when the email was sent, just show an alert that email sent successfully. my problem is, I don't want to redirect to another page. what should I do? -
Django GraphQL Test: How to test addition of new model fields?
I have a simple model as, class Person(models.Model): first_name = models.CharField(max_length=20) and I have setup the GraphQL to query the data, import graphene import graphene_django from .models import Person class PersonType(graphene_django.DjangoObjectType): class Meta: model = Person fields = '__all__' class PersonQuery(graphene.ObjectType): persons = graphene.List(PersonType) def resolve_persons(*args, **kwargs): return Person.objects.all() So far so good. Later I decided to write unittests for querying the persons data from django.test import TestCase from .models import Person from .schema import schema class TestGraphQLQuery(TestCase): @classmethod def setUpTestData(cls): cls.person = Person.objects.create(first_name="Jack") def test_person_query(self): query = """ query{ persons { id firstName } } """ result = schema.execute(query).data expected = {'persons': [{'id': f'{self.person.pk}', 'firstName': self.person.first_name}]} self.assertEqual(result, expected) and this too working. Later, my model got updated with one additional field, age and hence the model updated to class Person(models.Model): first_name = models.CharField(max_length=20) age = models.IntegerField(default=0) After the changes, I ran the unittests. As expected, it passes. Question How can I create the test case so that, the test should fail upon addition or removal of any fields? -
ModuleNotFoundError: No module named 'encodings'; rhel8; python3; apache2.4; mod_wsgi; django 3.1
Am trying to setup my django application (virtual environment) using apache and mod_wsgi. the application is running on RHEL8 machine and the only python running is python 3. RHEL version == Red Hat Enterprise Linux release 8.2 (Ootpa) python version == Python 3.6.8. apache version == Apache/2.4.37 (Red Hat Enterprise Linux). mod_wsgi version == 4.7.1. django version == 3.1. My Python virtual environment home is: python-home using sys.prefix i have created the mod_wsgi.so using CMMI method. below is the library detail ldd mod_wsgi.so details below is my virtual host conf file for apache. i have also tried adding python-path (like below), although not written in conf file details below. WSGIDaemonProcess sohail python-home=/home/ilearn/webapps/sohail python-path=/home/ilearn/webapps/sohail/src webapptest.conf: <VirtualHost *:80> WSGIScriptAlias /webapptest /home/ilearn/webapps/sohail/src/webapptraining/wsgi.py WSGIDaemonProcess sohail python-home=/home/ilearn/webapps/sohail WSGIProcessGroup sohail WSGIApplicationGroup %{GLOBAL} <Directory /home/ilearn/webapps/sohail/src/webapptraining> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> As soon as i startup my apache server i see the error ModuleNotFoundError: No module named 'encodings' in error logs. [core:notice] [pid 4576:tid 139861315184960] AH00052: child pid 4893 exit signal Aborted (6) Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' appreciate any help or advise to resolve the problem. thanks. -
django - How can I prefill formset forms data using database query result?
I am creating a student attendance form where need to get details of student name, student class and Id from student model based on teacher selecting student class in one form. I have tried using initial by using for loop on query data to prefill the form in formset, however it populates data for one record only. Below is the code for forms.py, models and views.py. Can someone help on this forms.py class student(models.Model): studentid = models.AutoField(primary_key=True) Gender = models.CharField(max_length=6, choices=gender, null=True) Name = models.CharField(max_length=100, null=True) DOB = models.DateField(null=True) Image = models.ImageField(null=True, upload_to='images') Status = models.CharField(max_length=10, choices=statchoice, null=True) Father_name = models.CharField(max_length=100, null=True) Mother_name = models.CharField(max_length=100, null=True) Address = models.CharField(max_length=200, null=True) Contact_no = models.IntegerField(null=True) Email = models.EmailField(null=True) Admission_class = models.CharField(max_length=40, null=True, choices=grade) Admission_date = models.DateField(null=True) Current_class = models.CharField(max_length=40, null=True, choices=grade) Leaving_date = models.DateField(null=True, blank=True) objects = models.Manager() def __str__(self): return str(self.studentid) class student_attendance(models.Model): Student_ID = models.CharField(max_length=100, null=True) Student_Name = models.CharField(max_length=100, null=True) Student_class = models.CharField(max_length=100, null=True, choices=grade) Attendance_date = models.DateField(null=True, auto_now_add=True, blank=True) Attendance_status = models.CharField(choices=attendance, null=True, max_length=10) objects = models.Manager() Views.py def student_attend(request): if request.method == 'POST': data = request.POST.get('studentGrade') formset_data = student.objects.filter(Current_class=data) AttendanceFormSet = formset_factory(std_attendance, extra=(len(formset_data))-1) for element in formset_data: formset = AttendanceFormSet(initial=[ {'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"} ]) param = … -
ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1594338739818/work'
While deploying my website on heroku. I also updated my requirements.txt file still there is this issue. git push heroku master Enumerating objects: 98, done. Counting objects: 100% (98/98), done. Delta compression using up to 4 threads Compressing objects: 100% (87/87), done. Writing objects: 100% (98/98), 1.31 MiB | 29.00 KiB/s, done. Total 98 (delta 35), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.12 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting alabaster==0.7.12 remote: Downloading alabaster-0.7.12-py2.py3-none-any.whl (14 kB) remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: Collecting argh==0.26.2 remote: Downloading argh-0.26.2-py2.py3-none-any.whl (30 kB) remote: Processing /tmp/build/80754af9/asgiref_1594338739818/work remote: ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1594338739818/work' remote: remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 9782a444fca0b0d09e0566b33ecbffce4eb90d89 remote: ! remote: ! We have detected that you have triggered a build from source code with version 9782a444fca0b0d09e0566b33ecbffce4eb90d89 remote: ! at … -
Django still refreshing the page after integrating AJAX
In index.js: $("#weather_form").on("submit", function(event){ event.preventDefault(); $.ajax({ url: "/weather/", type: "POST", data: {...:..., ...:..., ...}, success: function (data){ alert("success") }, error: function(xhr,errmsg,err) { alert("error") } }); }); In views.py: class weather(base.TemplateView): ... @staticmethod def post(request, *args, **kwargs): ... if request.is_ajax and request.method == "POST": ... if form.is_valid(): ... return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200) else: return http.JsonResponse({"error": form.errors}, status=400) What's happening now is when I click submit, Django clears the entire page and then print the correct results_matrix on a blank page in string format. alert("success") does not appear or alert("error"). I don't know why the post function is doing this since I'm not returning a render of anything. -
Kubernetes: Django and Postgres Containers don't communicate
I have created a Django-Python application with a postgres database. Its working fine in my PC as well as in any other windows based systems. I am trying to use K8s to host the application. I have setup the postgres container successfully. But when I am trying to create the Django-Python container and tryong to start it, it shows me this kind of error: Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The Deployment and service yaml for the postgres container: --- # Deployment for the PostgreSQL container apiVersion: apps/v1 kind: Deployment metadata: name: postgresql namespace: trojanwall labels: app: postgres-db spec: replicas: 1 selector: matchLabels: app: postgres-db strategy: type: Recreate template: metadata: labels: app: postgres-db tier: postgreSQL spec: containers: - name: postgresql image: postgres:10.3 ports: - containerPort: 5432 env: - name: POSTGRES_USER valueFrom: secretKeyRef: name: postgres-db-credentials key: user - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-db-credentials key: password - name: POSTGRES_DB value: 'postgres' volumeMounts: - mountPath: /var/lib/postgresql/data name: postgresql-volume-mount resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" cpu: "500m" volumes: - name: postgresql-volume-mount persistentVolumeClaim: claimName: postgres-pv-claim --- # Service for the PostgreSQL container apiVersion: v1 kind: Service metadata: name: postgresql namespace: trojanwall labels: app: … -
Get Data from foreign key in django
I have created two tables in Sqlite one have the main experience data and other have the details of the data as class experience(models.Model): e_name = models.CharField(max_length=30) e_post = models.CharField(max_length=50) e_startdate = models.CharField(max_length=30) e_enddate = models.CharField(max_length=30) def __str__(self): return self.e_name class experiencedetail(models.Model): e_name = models.ForeignKey(experience,on_delete=models.DO_NOTHING) e_detail = models.CharField(max_length=100) i am trying to shoe the details as shown in this image my Html code is {% for exp in experience %} <div id="{{exp.e_name}}" class="tabcontent"> <h2 class="hf">{{exp.e_post}} @ <span>{{ exp.e_name }}</span></h2> <p>{{exp.e_startdate}} - {{exp.e_enddate}}- {{exp.id}}</p> <div class="exp-description"> <h4> <ul style="list-style: square;"> {% for expd in exp_detail %} {% if 'expd.e_name' == 'exp.e_name' %} <li>{{ expd.e_detail }}</li> {% endif %} {% endfor %} </ul> </h4> </div> </div> {% endfor %} but this expd.details does not show any data. The data is present in the database. -
PyQt based desktop application which has a subscription based model
I have developed a desktop application in python using PyQt5 which acts as a UI for the hardware I am trying to sell. I want to convert this desktop application into a SaaS(software as a service) where people will buy the hardware and then subscribe to the software to be able to use the hardware. My question is how do I add this functionality. I don't have much of an experience with web servers. Although I do understand that I will have have a server which will handle the requests from the PyQt app and also a database to store the information about the subscription. I am ready to learn Django or flask. How will I make the software secure, in the sense people won't be able to bypass the subscription and use the app indefinitely. I also do understand that there will be some piece of code written in python (probably using Django) running in the backend of the web server. How will the Django backend interact with a database. I also don't understand how will the PyQt app connect to the server. How will the PyQt app check for the subscription? Obviously there will be a login page. … -
How to follow a link without creating templates in Django
I want to create a small online store on Django. I have a model of books that are sold in a store class Book(models.Model): title = models.CharField("Name", max_length=100) Views def BooksView(request): books = Book.objects.all() return render(request, "main/books_list.html", {"books": books}) Books page template {% extends 'main/base.html' %} {% block title %} Books_list {% endblock %} {% block content %} <h1>Books_list</h1> {% for el in movies %} <div> <h3>{{ el.title }}</h3> <img src="{{ el.poster.url }}" class ="img-fluid"> </div> {% endfor %} {% endblock %} I have created several books, how can I make it so that I can click on {{el.title}} and go to the link of each book? -
Django: Performing a raw sql query with count()
I want to make a query to get the number of rows in the model MyTable that have the field expire (datetime) be a date in the current week. In MySQL I execute the following query: select count(expire) from MyTable where yearweek(expire) = yearweek(now()); So I can get the rows that belongs to the current week starting from Sunday. I tried replicate that using queryset in my view like this: now = datetime.now() myquery = MyTable.objects.filter(expire__year=now.year).filter(expire__week=now.isocalendar()[1]) But the thing is, Django method of querying starts from Monday, I want it for Sunday. So I though in doing a raw sql query Like this: myquery = MyTabel.objects.raw('select count(expire) from MyTable where yearweek(expire) = yearweek(now());') But it doesnt work, it doesnt output a value. How can I make this query? I'm using mysql 5.7, python 3.7 and django 2.1.11 I know these are all old versions but I can't update. -
Django/Docker: error in path for serving templates
I try to "dockerize" a Django project. I've already dockerized a Django project ; I've tried to use the exactly same project architecture. I have first config dev environnement. I buil/run the 2 containers (web and db): OK. I migrate: OK When I try to collectstatic I got an error FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/core/static' and that right, static folder is at the same level as core app. As I config dev environnement, with Django web server, I don't have to care about serving static files. So I've try to acces localhost:8000 and got an error: That means I have an error in path config but I can find where as I replicate the same structure... project architecture - my_project |_ app |_ core |_ wsqi.py |_ settings |_ base.py |_ dev.py |_ prod.py |_ urls.py |_ requirements |_ base.txt |_ dev.txt |_ prod.txt |_ static |_ templates |_ layout |_ _footer.html |_ _nav.html |_ base.html |_ home.html |_ 404.html |_ 500.html |_ Dockerfile |_ Dockerfile.prod |_ entrypoint.sh |_ entrypoint.prod.sh |_ manage.py |_ .dockerignore |_ nginx |_ .env.dev |_ .env.prod |_ .gitignore |_ docker-compose.yml |_ docker-compose.prod.yml base.py import os from django.utils.translation import ugettext_lazy as _ BASE_DIR … -
How to use Relay's pagination feature with filterset_class from django-filter when using graphene-django
I've a Django project where I'm using django-graphene to create a GraphQL API. There's an issue when trying to use DjangoFilterConnectionField together with the relay.Connection (which is the core of pagination's feature) My model is too large and has many relationships, but let's keep things simple... class Pattern(models.Model): code = models.CharField( max_length=15 ) name = models.CharField( max_length=50 ) slug = AutoSlugField( populate_from='name', max_length=150 ) ... My node looks like: class PatternNode(DjangoObjectType): # Many fields here... ... class Meta: model = Pattern interfaces = (relay.Node,) filterset_class = PatternFilterSet As you can see, I've setup the filterset_class attribute in the Meta of my Node. So, here's that filter set: class PatternFilterSet(FilterSet): order_by = OrderingFilter( fields=( ('date', 'date'), ('name', 'name'), ) ) productcategorization__design__contains = CharFilter(method="product_categorization_design_filter") products__predominant_colors__contains = CharFilter(method="products_predominant_colors_filter") class Meta: model = Pattern fields = { 'name': ['exact', 'icontains', 'istartswith'], 'alt_name': ['exact', 'icontains', 'istartswith'], 'slug': ['exact'], 'pattern_class': ['exact'], 'sectors': ['exact', 'in'], 'products__instances': ['exact'], 'productcategorization__business': ['exact'], 'productcategorization__market_segment': ['exact', 'in'], } @staticmethod def product_categorization_design_filter(queryset, name, value): """ Does a productcategorization__design__contains filter "manually" because adding it in the Meta.fields does not work for ArrayField. Args: queryset (patterns.managers.PatternQuerySet) name (str) value (Array) comma delimited list of designs Returns: filtered_queryset (QuerySet) """ return queryset.filter(productcategorization__design__contains=value.split(",")) @staticmethod def products_predominant_colors_filter(queryset, name, … -
Django-CSP - AJAX request with vanilla JS blocked by CSP
I have a Django-based D&D-wiki webpage that I'm working on in my free time which I'm using to learn more about web development. I recently implemented a Content-Security-Policy using django-csp. That went well and the switch was fairly painless, given that I only had 20 or so templates to deal with. Here my CSP settings: //Django settings.py CSP_DEFAULT_SRC = ("'none'",) CSP_STYLE_SRC = ("'self'", 'stackpath.bootstrapcdn.com', 'fonts.googleapis.com', "'unsafe-inline'", 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com', 'rawcdn.githack.com', 'maxcdn.bootstrapcdn.com',) CSP_SCRIPT_SRC = ("'self'", 'localhost', "default-src", 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com','maxcdn.bootstrapcdn.com',) CSP_IMG_SRC = ("'self'", 'ipw3.org', 'data:', 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com', 'i.imgur.com',) CSP_FONT_SRC = ("'self'", 'fonts.gstatic.com', 'maxcdn.bootstrapcdn.com',) CSP_MEDIA_SRC = ("'self'",) CSP_INCLUDE_NONCE_IN = ('style-src',) Even more recently started learning about AJAX requests and wanted to implement a simple POST request. Sadly, my CSP blocks this request, which I believe should be allowed given that I allowed self and localhost in CSP_SCRIPT_SRC: //JS Event Listener that creates and sends the AJAX request document.getElementById('create-timstamp').addEventListener('click', function(event){ const isValid = validateForm(); if (isValid){ xhr = new XMLHttpRequest(); xhr.open('POST', getCreateTimestampURL(), true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); const csrf = document.querySelector('input[name="csrfmiddlewaretoken"]').value; xhr.setRequestHeader("X-CSRF-TOKEN", csrf); xhr.onload = function(){ document.querySelector('.timestamp-create-box').remove(); } const timestampForm = document.forms['timestamp-form']; const timestamp_seconds = toTimeInt(timestampForm['time'].value); const timestamp_name = timestampForm['name'].value; const data = `name=${timestamp_name}&time=${timestamp_seconds}`; xhr.send(data); return false; } //For completion's sake here also the … -
Page not found...The current path, customer, didn't match any of these. Django,python
I feel like I just need another pair of eyes, cant figure this out on my own for several hours. I am a beginner as you can tell. Thought that the problem might be some type error in these two files but I just cannot find it views.py file from django.shortcuts import render from django.http import HttpResponse from.models import * def home(request): customers=Customer.objects.all() orders=Order.objects.all() total_customers=customers.count() total_orders=orders.count() delivered=orders.filter(status="Delivered").count() pending=orders.filter(status="Pending").count() context={'orders':orders,'customers':customers, 'pending':pending, 'delivered':delivered,'total_orders':total_orders} return render(request, 'accounts/dashboard.html',context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html',{'products' :products}) def customer(request, pk): customer=Customer.objects.get(id=pk) return render(request, 'accounts/customer.html') ****urls.py**** from django.urls import path from . import views urlpatterns = [ path('', views.home), path('customer/<str:pk>/', views.customer), path('products/', views.products), ] error by django Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/customer Using the URLconf defined in crm1.urls, Django tried these URL patterns, in this order: admin/ customer/<str:pk>/ products/ The current path, customer, didn't match any of these. -
Djnago admin.StackedInline logic to automatic clone related models
I have a model A with oneToMany relationship with Model B. Django admin side, to manage this relationship, I'm using one admin.StackedInline Into this formset I added a custom Integer field 'MYFIELD' (not related to the model). My idea is this: when the user save the model, for each related model, I would like check this MYFIELD to clone this related model. This is a sort of multiplier: for each related model, if the value is N I will create N clones of it. Probably I have to implement this logic into the method save_related but it's not clear for me how can duplicate. -
Reset auto-increment index value on SQLite(Django)
I'm creating a Blog app using Django. So when I delete a post which is at the database index of 3 and adds another post to the blog, it adds the post on the database column of index 4, and there won't be any column of index 3. So How can I change that new post index to 3 itself? -
request.session.modified vs SESSION_SAVE_EVERY_REQUEST
I understand how these work differently in practice. For example, if I have: request.session.['cart'].remove('item') the session won't be saved without explicitly calling request.session.modified = True or having SESSION_SAVE_EVERY_REQUEST = True in settings.py. Or I could get around using either by using: cart = request.session['cart'] cart.remove('item') request.session['cart'] = cart My question is if there is any drawback to using SESSION_SAVE_EVERY_REQUEST whether in performance or unintended consequences. I don't see any reason why I wouldn't want to save the session if I modified a value in it. -
Procfile issue while deploying on Heroku
I am deploying y Django application on Heroku. At first I added the Profile this way: I could run 'heroku local', while in the folder where Procfile with no issue and the app was running fine locally. Then I realized while deploying on Heroku that Procfile had to be in the root directory for it to be recognized. So I changed it's directory: Running 'heroku local' I got an no module names'trusty_monkey.wsgi' error. So I change my Procfile from : web: gunicorn trusty_monkey.wsgi to: web: gunicorn trusty_monkey.trusty_monkey.wsgi But now I have this error: What I don't understand is why it doesn't get the 'trusty_monkey.settings' now when they were no issues before? -
Django / Apache / Ubuntu Static files not being served
Everything was working fine until I moved from my local PC to a web server (AWS Ubuntu). I am using Apache with WSGI adapter. I followed all the guides I could and have been at this for several days and still can't figure out why none of my images or styles are displaying. I am having trouble wrapping my head around how static files work and there may be a simple reason why this isn't working but I can't figure it out. I have followed so many guides and am at a loss. Yes I have run collectstatic, but all this seems to do is throw all my static files into the static folder. Not sure what the purpose of this is and I am having trouble understanding it on the django website. You can view my site here: http://13.56.18.7/ The site loads without styles, If you check Chrome Dev tools, it shows none of my files being found: Build: urls.py from django.contrib import admin from django.urls import path from app_main.views import (home_page, services_page, history_page, offers_page, contact_page) from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', home_page, name='home_page'), path('admin/', admin.site.urls), path('services/', services_page), url(r'^services/', … -
Django orm: moving selected records from a column to another and save to database
I have the following list: list = [ "WP1788/1", "WP1810/1", "WP1810/2", "WP1812/1", "WP1815/1", "WP1818/1", "WP1823/1", "WP1827/1", "WP1828/1", "WP1828/2", "WP1828/3", "WP1828/4", "WP1828/5", "WP1828/6", "WP1837/1", "WP1840/1", "WP1841/1", "WP1855/1", "WP1860/1", "WP1861/1", "WP1863/1", "WP1872/1", "WP1873/1", "WP1873/2", "WP1879/1", "WP1884/1", "WP1888/1", "WP1895/1", "WP1895/2", "WP1906/1", "WP1906/2", "WP1908/1", "WP1908/2", "WP1909/1", "WP1909/2", "WP1913/1", "WP1918/1", "WP1919/1", "WP1919/2", "WP1919/3", "WP1922/1", "WP1928/1", "WP1928/3", "WP1928/4", "WP1928/5", "WP1928/6", "WP1944/1", "WP1944/2", "WP1945/1", "WP1946/1", "WP1947/1", "WP1955/1", "WP1962/1", "WP1965/1", "WP1965/2", "WP1967/1", "WP1969/1", "WP1977/1", "WP1988/1", "WP1991/1", "WP1991/5", "WP1995/1", "WP2002/1", "WP2012/1", "WP2015/1", "WP2017/1", "WP2021/1", "WP2022/1", "WP2024/1", "WP2033/1", "WP2033/2", "WP2044/1", "WP2050/1", "WP1585/1", "WP1585/2", "WP1585/4", "WP1585/5", "WP1585/6", "WP1585/7", "WP1585/8", "WP1585/9", "WP1624/103", "WP1624/105", "WP1624/108", "WP1624/109", "WP1624/118", "WP1624/119", "WP1624/120", "WP1624/121", "WP1624/123", "WP1624/129", "WP1624/130", "WP1624/137", "WP1624/145", "WP1624/165", "WP1624/83", "WP1624/85", "WP1624/91", "WP1624/93", "WP1670/1", "WP1708/10", "WP1708/12", "WP1708/13", "WP1708/14", "WP1708/15", "WP1708/17", "WP1708/20", "WP1708/22", "WP1708/26", "WP1708/27", "WP1708/28", "WP1779/26", "WP1838/1", "WP1844/1", "WP1876/1", "WP1882/1", ] I would like to select the wps (Wp model) in the database with ID in list, something like: wps_selected = Wp.objects.filter(ID in list) and then copy the value from the column working_hours to the column non_profitable and save it to database. Is that possible using ORM. I know how to do it in SQL but I am still a bit comfuased about using ORM -
EBS + Django - MEDIA doesn't work (permission denied)
I have a Django project on Elastic Beanstalk. Now I'm trying to make media work. Since media is a user-uploaded content I guess I can't just use myproject/media folder. When I try to upload/save a file it returns: PermissionError: [Errno 13] Permission denied: '/opt/python/bundle/7/app/media' Do you know what to do? Is there a place that I can use as a media folder that won't be deleted? In settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Can i direct a form to specific user with Django?
Hello I have created a model for a form that asks for the recipient, title, content of the message. I want that message to be viewed by the recipient only how can i do that? -
How to display a text, from a python program, to a HTML form in Django?
I am new to Django and web programming and HTML. I am trying to create a webpage using Django, with following functionality: When the page is browsed for the first time, it should invoke a program rules.py and display a text output from rules.py to a paragraph in the page. The page contains a form with label as 'name'. The user will look at the message displayed from rules.py and enter a name in the form and click on 'submit' On clicking submit, the page should POST the request, alongwith the 'name' entered and execute program validate.py, that returns a numeric code (0: success, 1: invalid), and a text (next instruction if success, error message is failure). This text should be displayed back to my page, in the same place where the output from rules.py was displayed earlier. Then based on the message displayed, user will enter another name, and same process will repeat. How to display a text in the form that is output from a python program? I am able to display the output in the label of the input name field, using code below. But I don't want to change the label, I want a paragraph / …