Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi need help on local host when using python django
when running : 'py manage.py runserve'r, provide use this 'http://127.0.0.1:8000/' local host, but there is error comes up: Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions and wenpage couldnt open at all. -
Django: Built-in login fails with existing User
I have a question regarding django built in authentication system. I'm following this DjangoDoc. So I added the URLS in my urls.py: from django.urls import include, path from .views.views_user import * from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')) ] urlpatterns = format_suffix_patterns(urlpatterns) And here is my login.html: {% extends "base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login"> <input type="hidden" name="next" value="{{ next }}"> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> {% endblock %} So it renders correctly the template with the login form. And I have some existing Users, we can see them with Postman: [ { "id": 1, "username": "AdminEP", "password": … -
Unable to use http2 on nginx docker container
I want to use http2 by nginx image, but i tried very long the protocol are still using http/1.1 Dockerfile for nginx: FROM nginx COPY ./docker/nginx/etc/nginx/nginx.conf /etc/nginx/nginx.conf COPY ./docker/nginx/etc/nginx/conf.d/default.conf.https /etc/nginx/conf.d/default.conf /etc/nginx/nginx.conf is user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { # run ulimit -n to check worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; # Buffer size for post submission client_body_buffer_size 10k; client_max_body_size 8m; # Buffer size for header client_header_buffer_size 1k; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } /etc/nginx/conf.d/default.conf is: # Expires map map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name 0.0.0.0; ssl_certificate /etc/nginx/certs/server.crt; ssl_certificate_key /etc/nginx/certs/server.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; expires $expires; location = /favicon.ico { log_not_found off; } location /static/ { alias /static_files/; } location / { access_log /var/log/nginx/wsgi.access.log; error_log /var/log/nginx/wsgi.error_log warn; proxy_pass http://app_wsgi:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /ws/ { try_files $uri @proxy_to_ws; } location @proxy_to_ws { access_log /var/log/nginx/asgi.access.log; error_log /var/log/nginx/asgi.error_log warn; proxy_pass http://app_asgi:8001; proxy_http_version 1.1; proxy_set_header Upgrade … -
Django intercept adding objects to Many-to-Many field
I'm building a Django app and I want to overwrite the default adding to many-to-many field behaviour. Say I want to print out something when a relationship between 2 objects is created. class Foo(Model): ... class Bar(Model): foos = ManyToManyField(Foo) Is there anywhere where I can overwrite the add method of the many to many relationship manager class? Something like class ???: def add(self, obj, *args, **kwargs): super().add(obj, *args, **kwargs) print(f"{obj} added") and the expected output should be >>> foo1 = Foo.objects.create(...) >>> bar = Bar.objects.create() >>> bar.foos.add(foo1) foo1 added Thanks everyone. -
Can¨t open Debugger for Chrome in VSCODE
Error when I try to Launch Debugger Chrome -
Executing two celery workers from one line
I am working on a project for my university within a team where I was mostly working on the frontend and some basic django models, so I am not so familiar and eloquent with django-celery and I also did not set it up. At first we were using one celery worker, but I had to add one more so I was able to finish a user story. I am currently running two workers with one in a terminal each like this: exec celery -A my_proj --concurrency=1 worker exec celery -A my_proj --concurrency=1 worker -B -Q notification While i run those two my project works, but I need these to start from one line. So: How do I get those two into one line for a script? So far I've tried around this: exec celery multi start celery -A my_proj --concurrency=1 notification -A my_proj --concurrency=1 -B -Q notification But it stops my project from functioning. Any help is appreciated, thank you! -
Can't Authorize when i try to login to my django project from iphone
I have created a website using Django (Django-rest-framework, django-rest-knox), ReactJS and redux together. I have run the server from 0.0.0.0:8000 to reach the project from my iPhone and test there. The Website has been loaded however when I try to log in, it can not authorize and gives 401 error. On the other hand, I can authorize without any problem from browsers on PC (chrome, opera, firefox etc.) and android devices. I have also installed Opera Mini to my iPhone and, again I couldn't authorize it. I don't know which part of my code I have share. I also couldn't find any information about this issue. I would be glad if anyone can help me. -
Pipenv fails to install boto3 on remote server (Heroku)
I deployed my django project successfully, then I wanted to use AWS S3 for serving static files. So I installed the required packages and everything worked locally. But now when I try git push heroku master it fails with the following traceback: Writing objects: 100% (370/370), 5.85 MiB | 2.92 MiB/s, done. Total 370 (delta 69), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.6.10 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory remote: -----> Installing python-3.6.9 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 2018.5.18… remote: Installing dependencies from Pipfile.lock (acd4c8)… remote: An error occurred while installing boto3==1.12.31! Will try again. remote: Installing initially–failed dependencies… remote: Collecting boto3==1.12.31 remote: Using cached https://files.pythonhosted.org/packages/2a/4f/3facbb42e8d07db1ef9b8cefb28dd1dbfcd52a8e32a0323d57f59b10e147/boto3-1.12.31-py2.py3-none-any.whl remote: remote: THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them. remote: boto3==1.12.31 from https://files.pythonhosted.org/packages/2a/4f/3facbb42e8d07db1ef9b8cefb28dd1dbfcd52a8e32a0323d57f59b10e147/boto3-1.12.31-py2.py3-none-any.whl#sha256=8bf7e3611d46e8214bf225169ac55de762d9d341514f81ebae885dd601138fcf (from -r /tmp/pipenv-sdy5o9v6-requirements/pipenv-k_8vold6-requirement.txt (line 1)): remote: Expected sha256 913fc7bbb9df147ed6fa0bd2b391469652ee8cad3e26ca2355e6ff774d9516fb remote: Got 8bf7e3611d46e8214bf225169ac55de762d9d341514f81ebae885dd601138fcf remote: remote: You are using … -
How can I run my own .py automatically on Django
i'm working on my first Django project and I would like to know how can I set my scraper to run automatically every hour or so to update the data on my site. I'm still in development environment and to update the database I'm running it manually, but that's a key feature of my project. Any help please... -
Display data of a searched item using Django
I currently have a search bar. It searches clients that have filled a form, using first and last names, the search provides a list with the names being links to the client's page. I am struggling to display that specific person's data, the model has about 20 fields, it would need to display all. How could I retrieve the data of a single person and display all the data from the model? At present the page comes up blank, the URL displays the correct client id though. Thank you in advance. -
405 error when testing an authed django-rest-framework route
I'm testing a CreateAPIView with an APITestCase class. Things are working as expected as an anonymous user, but when I login() as a user, I get a 405 HttpResponseNotAllowed exception. I'm able to successfully create an object while authed as a user through the django-rest-framework web frontend. I'm using djangorestframework version 3.9.4 and Django 1.11.29. Here are the main parts of the code, for a general idea of what I'm doing: class SherdNoteCreate(CreateAPIView): serializer_class = SherdNoteSerializer def post(self, request, *args, **kwargs): data = request.data.copy() data['asset'] = kwargs.get('asset_id') serializer = SherdNoteSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class SherdNoteTests(APITestCase): def test_create_sherdnote_on_own_asset(self): # Removing this auth block allows the test to pass self.u = UserFactory(username='test_user') self.u.set_password('test') self.u.save() login = self.client.login(username='test_user', password='test') assert(login is True) asset = AssetFactory(primary_source='image', author=self.u) url = reverse('sherdnote-create', kwargs={'asset_id': asset.pk}) data = { 'title': 'note title', 'body': 'note body' } response = self.client.post(url, data, format='json') # This fails with a 405! self.assertEqual(response.status_code, status.HTTP_201_CREATED) I've been having trouble tracking down why this is happening. Let me know if you have any ideas. -
Using Django how can I get a set of records where the value used for filtering is to a many-to-many field
Assuming I have data that resembles: id | value | m2m__created | m2m__value ---+-------+--------------+----------- 1 | 10 | 2020-03-14 | 0 1 | 10 | 2020-03-21 | 5 2 | 20 | 2020-03-14 | 10 3 | 30 | 2020-03-14 | 20 what I want after filtering is: id | value | m2m__created | m2m__value ---+-------+--------------+----------- 1 | 10 | 2020-03-21 | 5 2 | 20 | 2020-03-14 | 10 3 | 30 | 2020-03-14 | 20 I'm trying to use something like this: Foo.objects.filter( foo_m2m__created__lte=start_date, ).order_by( 'id', '-foo_m2m__created', ).annotate( recently_created=Max('foo_m2m__created'), ).values( 'id', 'value', 'foo_m2m__created', 'foo_m2m__value', ) unfortunately, what I get is this: id | value | m2m__created | m2m__value ---+-------+--------------+----------- 1 | 10 | 2020-03-14 | 0 2 | 20 | 2020-03-14 | 10 3 | 30 | 2020-03-14 | 20 I've tried adding another .filter(foo_m2m__created=F('recently_created')) following the annotation, but the same thing happens. -
How to create tuple expressions in Django database queries?
I have some table ports(switch_ip, slot_number, port_number, many, more, columns) and would like to achieve the following PostgreSQL query using Django: SELECT switch_ip, array_agg((slot_number, port_number, many, more, columns) ORDER BY slot_number, port_number) info FROM ports GROUP BY switch_ip ORDER BY switch_ip Using django.contrib.postgres.aggregates here's what I got so far: Port.objects \ .values('switch_ip') \ .annotate( info=ArrayAgg('slot_number', ordering=('slot_number', 'port_number')) ) \ .order_by('switch_ip') I am unable to include more than one column in the ArrayAgg. None of ArrayAgg(a, b, c), ArrayAgg((a, b, c)), ArrayAgg([a, b, c]) seem to work. A workaround could involve separate ArrayAggs for each column and each with the same ordering. I would despise this because I have many columns. Is there any nicer workaround, possibly more low-level? I suspect this is no issue with ArrayAgg itself but rather with tuple expressions in general. Is there any way to have tuples at all in Django queries? For example, what would be the corresponding Django of: SELECT switch_ip, (slot_number, port_number, many, more, columns) info FROM ports If this is not yet possible in Django, how feasible would it be to implement? -
Web Design (Payment Processing Project) Plan Question:
I am creating a plan to build a payment processing web page (under my domain) where a user can access the page and use a 3rd party app to pay me (payment through the Plaid and Dwolla application). As of now, I do not need to track the user's information. I was thinking of using React on the frontend and Django on the backend. I have 4 questions: Do I only need a frontend, as I am not storing the user's information? Or is it best to have both backend and frontend for organization? Would you recommend using React, Django, and Heroku? Any recommendations on tutorials to follow (youtube, docs, etc)? Any tips on how to integrate Plaid/Dwolla? -
DJANGO: ModuleNotFoundError: No module named 'YoutubeAPI'
So i have created simple API in my and it is working fine. Now the thing is i want to host my API in any hosting website, So i found pythonanywhere. Now i have installed django, DRF in pythonanywhere bash console. and i made project (API) and startapp(YoutubeAPI) and added rest_framework in settings.py file and all things done. now i added my exact same data of models.py, serializer.py, views.py and urls.py and all in pythonanywhere project files. now when i run manage.py im getting module not found 'YoutubeAPI'. //below is tree structure attachment enter image description here -
Django: search_device_list() missing 1 required positional argument: 'id'
I have a search page that was working until I coded in the return of the search for editing. Ideally, the user does a search and it returns some values, all good so far. Then when the user clicks on the edit button for a value I want the fields to return in an editable format. Here is the views.py license_key = Maintenance.objects.get(id=id) maintenance_form = MaintenanceForm(instance=license_key) devices = Devices.objects.filter(maintenance = id) end_of_maintenance_support = MaintenanceForm() locations = Locations.objects.all() context ={"locations": locations} for locations in context['locations']: print(locations) if request.method == 'POST': location_name=request.POST.get('location_name') my_devices = Devices.objects.filter(locations = Locations.objects.get(location_name = location_name)) maintenance_form = MaintenanceForm(request.POST, instance=license_key) license_key = request.POST.get('license_key') maintenance_support_end_date = request.POST.get('maintenance_support_end_date') context["devices"]= my_devices context["location_name"]= location_name context["license_key"] = license_key context["maintenance_support_end_date"] = maintenance_support_end_date if maintenance_form.is_valid(): license = maintenance_form.save() print (license.license_key) postdevices= request.POST.getlist("devices") for device_hostname in postdevices: device = Devices.objects.get(device_hostname = device_hostname) print(device.maintenance.license_key) print(device.maintenance.maintenance_support_end_date) device.save() return render(request, 'inventory/search_device_list.html', context) Here is the template.py {% block content %} <h2 align="left">Search Page</h2> <!-- <form action="{% url 'inventory:render_results' %}" method="POST" > --> <form action="{% url 'inventory:search_device_list' %}" method="POST" > {% csrf_token %} <body> <table class=table> <tr> <td><b>Locations: &nbsp;&nbsp; </b></td> <td> <select name="location_name"> {% for locations in locations %} <option value="{{locations.location_name}}">{{locations.location_name}}</option>{% endfor%} </select> </td> <td><input type="submit" name = "submit" value="Submit"/></td> </tr> … -
Python gives me an error, even tho i gave him a request argument
so I'm learning django and it keeps giving me an error and I have no ide why. Look here is the function: def base_view(request, *args, **kwargs): return render(request, "base.html", {}) and here is the path in urls.py: path('home/', base_view(), name="home"), So as you can see, I gave him the request argument and he keep's giving me this error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\aleks\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\aleks\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aleks\Desktop\Programowanie\Moje Projekty\TAM\d\conda\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module … -
Render row group headings with django-tables2
I'm porting a PHP/PostgreSQL/DataTables project over to Django 3. I don't use DataTables for anything too fancy except for the rowGroup extension that groups the dataset into sections according to one of the fields in the dataset. Here's an example of what I'm talking about. I'd like to keep this simple, so I'm hoping to using django-tables2 to accomplish the same thing. Is it possible to render a table using django-tables2 that will group the rows in the resulting table according to values in a column in the dataset? -
Got this error while executing command pip install jinja
Collecting Jinja Using cached Jinja-1.2.tar.gz (252 kB) ERROR: Command errored out with exit status 1: command: 'C:\Program Files\Python38\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\siddh\\AppData\\Local\\Temp\\pycharm-packaging\\Jinja\\setup.py'"'"'; __file__='"'"'C:\\Users\\siddh\\AppData\\Local\\Temp\\pycharm-packaging\\Jinja\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\siddh\AppData\Local\Temp\pycharm-packaging\Jinja\pip-egg-info' cwd: C:\Users\siddh\AppData\Local\Temp\pycharm-packaging\Jinja\ Complete output (6 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\siddh\AppData\Local\Temp\pycharm-packaging\Jinja\setup.py", line 28 except DistutilsError, e: ^ SyntaxError: invalid syntax ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
"kafka.errors.NoBrokersAvailable: NoBrokersAvailable" problem
i investigate too much topic in stackoverflow but i couldn't find solution for me. I have a docker-compose file and i am trying to set true parameters for configuration. Other than that i have a django api that manages web requests. My goal is when a user visits someone elses "post" i want to send a message to kafka "x user visited y users 'z' titled post". Finished all my configurations. In endpoint i configured a producer that sends message to kafka. After request to endpoint it gives me that error in title. How can i solve that ? django view.py; def get(self,request,post_id,format=None): """ Gets a post """ post = self.get_post(post_id) serializer = PostSerializer(post) send_data(post.owner, request.user, post, datetime.now().strftime("%d/%m/%Y %H:%M:%S") ) return Response(serializer.data) send data func; def send_data(visitor_user:User, owner_user:User, visitedPost:Post, timestamp:date): from kafka.errors import KafkaError from kafka import KafkaProducer producer = KafkaProducer( bootstrap_servers=['kafka:9092'] ) visitor = visitor_user.first_name + " " + visitor_user.last_name + "(username:" + visitor_user.username + ") " owner = owner_user.first_name + owner_user.last_name + "(username:" + owner_user.username + ") " post = "'" + visitedPost.title + "' titled post." message = timestamp + "->" + visitor + "read" + owner + " 's " + post result = producer.send( 'visitation-log', … -
Django ORM inner join between tables having foriegn key of third table
I want to perform an inner join between tables that holds the foreign key of another table in VIEW.PY The raw query that I am trying to make in django is "SELECT * FROM table3 t3 inner join table2 t2 on t2.C=t3.E where t2.B=0 and t2.D=t3.F and ( (t3.G =1234 and t3.H=0) or (t3.H!=0 and t3.G is null) )" how to do this in django Views -
Event Stream in Django
I want to write an app to get Cryptocurrency price and Update Data via Event Stream. I write a code to get price from free API, but now i can note update this data and want to use Event Stream. -
Ascii encoding error during sending a mail in python
I'm working on django app and i have a form contains multiple fields, i can get the fields values through views.py file and when i just fill the fields in english everything is working like a charm but in case of my app i need to fill them in arabic. When i was trying to do this and see if it is working the same i got the error below on my screen: UnicodeEncodeError at / 'ascii' codec can't encode characters in position 24-27: ordinal not in range(128) This is my code: def index(request): if request.POST.get('sendEmail'): pname = request.POST.get('patient_name') cr = request.POST.get('city_region') mz = request.POST.get('mazq') hno = request.POST.get('house_no') yn = request.POST.get('your_name') mob = request.POST.get('mobile') if (pname != '' and cr != '' and mz != '' and hno != '' and yn != ''): server = smtplib.SMTP('smtp.gmail.com', 587) server.connect("smtp.gmail.com",587) server.starttls() server.login(username, password) FROM = yn print(FROM) TO = ["alisattarbarani@gmail.com"] SUBJECT = "New Subject" TEXT = pname + "\n" + cr + "\n" + mz + "\n" + hno ms = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT + '\n' + '\n' + FROM) server.sendmail(FROM, TO, ms) server.quit() msg = "Successfull Email" return render(request, "index.html", {"msg": msg}) msg = "Empty Fields!" return render(request, "index.html", {"msg": … -
Django 3 - CreateView with initial ForeignKey field
and in advance thanks for your time. So I am trying to create a "restaurant rating" app on Django 3. I have set up the following models: # Table storing the different restaurants class Restaurant(models.Model): restaurant_name = models.CharField(max_length=200, unique=True) restaurant_address = models.CharField(max_length=200) restaurant_street_number = models.CharField(max_length=10) restaurant_city = models.CharField(max_length=200) restaurant_cuisine_type = models.CharField(max_length=200) def __str__(self): return self.restaurant_name + ' - ' + self.restaurant_city class UserReview(models.Model): # Defining the possible grades Grade_1 = 1 Grade_2 = 2 Grade_3 = 3 Grade_4 = 4 Grade_5 = 5 # All those grades will sit under Review_Grade to appear in choices Review_Grade = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5') ) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) user_review_grade = models.IntegerField(default=None, choices=Review_Grade) # default=None pour eviter d'avoir un bouton vide sur ma template user_review_comment = models.CharField(max_length=1500) def get_absolute_url(self): return reverse('restaurants:reviews', args=[self.id]) This is the form I am using: # Form for user reviews per restaurant class UserReviewForm(forms.ModelForm): class Meta: model = UserReview # restaurant = forms.ModelChoiceField(queryset=Restaurant.objects.filter(pk=id)) fields = [ 'restaurant', 'user_review_grade', 'user_review_comment' ] widgets = { 'restaurant': forms.HiddenInput, 'user_review_grade': forms.RadioSelect, 'user_review_comment': forms.Textarea } labels = { 'user_review_grade': 'Chose a satisfaction level:', 'user_review_comment': 'And write your comments:' } Here are my URLs: app_name = 'restaurants' urlpatterns … -
Saving photo modified by PIL - Python 3+ Django 2+
I am trying to save my photo recive from my form changed by PIL in the ImageField field. file = cd['custom_img'] #get my file from my form #resize image image = Image.open(file) (w, h) = image.size if (w > 1000): h = int(h * 1000. / w) w = 1000 image = image.resize((w, h), Image.ANTIALIAS) rgb_image = image.convert('RGB') #save in object thumb_io = BytesIO() #create a BytesIO object rgb_image.save(thumb_io, 'JPEG', quality=80) # save image to BytesIO object thumbnail = File(thumb_io) #create a django friendly File object owner.basic_img = thumbnail owner.save() My code does not return any result. Nothing is still written in my field. My attempts: 1.) Checking if the file will be saved I tried to check if my picture was saved correctly. Everything works well. A modified photo is created from the form sent. #resize image print(file) image = Image.open(file) print(image) (w, h) = image.size if (w > 1000): h = int(h * 1000. / w) w = 1000 image = image.resize((w, h), Image.ANTIALIAS) rgb_image = image.convert('RGB') #save rgb_image.save('my_image.jpg') 2.) I tried to save the photo according to this tutorial thumbnail = File(thumb_io, name=image.name) # create a django friendly File object My code raises an error here AttributeError: …