Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form with multiple image value return list object has no attribute _committed when I try to submit it
I have a form inside my forms.py file when I try to submit the form it throws me an error: 'list' object has no attribute '_committed'. In that form, I want to allow user to upload multiple image in one model field, for that I have to follow this documentation, but I don't have an idea why it's throws the error every time I try to submit it. model class LevelType(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) images = models.FileField(upload_to='images-level') ``` ``` ``` forms.py class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True class MultipleFileField(forms.FileField): def __init__(self, *args, **kwargs): kwargs.setdefault("widget", MultipleFileInput()) super().__init__(*args, **kwargs) def clean(self, data, initial=None): single_file_clean = super().clean if isinstance(data, (list, tuple)): result = [single_file_clean(d, initial) for d in data] else: result = single_file_clean(data, initial) return result class LevelTypesForms(forms.ModelForm): images = MultipleFileField() class Meta: model = LevelType fields = [ 'level', 'bank_name', 'account_number', 'account_name', 'images', 'price', 'currency', 'description', 'accept_payment_with_card', ] views.py: class CreateLevelType(CreateView): model = LevelType form_class = LevelTypesForms success_url = reverse_lazy('Level-Types') template_name = 'Account/create_level_type.html' def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['level'].queryset = Level.objects.filter(user=self.request.user) return form def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.user = self.request.user form.save() images = form.cleaned_data["images"] … -
Django blog comment functionality with Jquery not working, takes me to JSON page instead
So i am building a blog with Django and I am trying to implement a comment functionality with JQuery to avoid a page refresh. I've written the codes but when I click on the comment submit button, I get sent to a white page with JSON data. I've struggled with this problem for too long and i'm hoping for a solution here. Following are the relevant codes. in my detail page, this is the html for the comment form: <div id="comment-container" class="comment-container" style="display: none;"> <form id="comment-form" method="post" action="{% url 'article:comment_submit' post.slug %}"> {% csrf_token %} <textarea id="comment-textarea" style="font-size: 16px; color: #333; background-color: #f2f2f2; border: 1px solid #ccc; border-radius: 4px; padding: 8px; outline: none; text-align:left;" name="comment" rows="4" cols="50"> </textarea> <button id="submit-comment" style="display: block;" type="button">Submit</button> </form> </div> still in my detail page is an empty div tag where I intend to prepend/append the comments: <div id="comments-section"> </div> in my main.js, I have: $(document).ready(function() { // Function to submit the comment form using AJAX $("#submit-comment").on("click", function(event) { event.preventDefault() var commentText = $("#comment-textarea").val().trim(); if (commentText !== "") { var formData = $("#comment-form").serialize(); // Get the comment submission URL from the data attribute var commentSubmitURL = "{% url 'article:comment_submit' post.slug %}"; $.ajax({ type: "POST", url: … -
an error is displayed OSError at /images/create/[Errno 38] Function not implementedRequest Method:POST
here is the form code: from django import forms from .models import Image from django.core.files.base import ContentFile from django.utils.text import slugify import requests class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ['title', 'url', 'description'] widgets = { 'url': forms.HiddenInput, } def clean_url(self): url = self.cleaned_data['url'] valid_extensions = ['jpg', 'jpeg', 'png'] extension = url.rsplit('.', 1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('The given URL does not ' \ 'match valid image extensions.') return url def save(self, force_insert=False, force_update=False, commit=True): image = super().save(commit=False) image_url = self.cleaned_data['url'] name = slugify(image.title) extension = image_url.rsplit('.', 1)[1].lower() image_name = f'{name}.{extension}' # download image from the given URL response = requests.get(image_url) image.image.save(image_name, ContentFile(response.content), save=False) if commit: image.save() return image here is the views.py: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.shortcuts import get_object_or_404 from django.http import JsonResponse from django.views.decorators.http import require_POST from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, \ PageNotAnInteger from .forms import ImageCreateForm from .models import Image @login_required def image_create(request): if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_image = form.save(commit=False) # assign current user to the item new_image.user = request.user new_image.save() messages.success(request, … -
Ubuntu UWSGI Permission Denied
I am doing the command : sudo supervisorctl update sudo supervisorctl status This is the response i get from running the command bridged RUNNING pid 9808, uptime 0:01:57 celery RUNNING pid 9809, uptime 0:01:57 site FATAL Exited too quickly (process log may have details) Here is my site.conf code, this site.conf is supposed to run under django environment, in my webEnv environment there is the uwsgi runner. The uwsgi is used as worker for online judge website. [program:site] command=/home/jeff/webEnv/bin/uwsgi --ini uwsgi.ini directory=/home/jeff/site stopsignal=QUIT stdout_logfile=/tmp/site.stdout.log stderr_logfile=/tmp/site.stderr.log So i try checking the site.stderr.log, and here what the response said about the code. detected number of CPU cores: 3 current working directory: /home/jeff/site writing pidfile to /tmp/dmoj-site.pid open("/tmp/dmoj-site.pid"): Permission denied [core/utils.c line 3>[uWSGI] getting INI configuration from uwsgi.ini *** Starting uWSGI 2.0.22 (64bit) on [Sun Jul 30 13:29:09 2023] ***compiled with version: 11.3.0 on 29 July 2023 17:26:29 os: Linux-5.19.0-50-generic #50-Ubuntu SMP PREEMPT_DYNAMIC Mon Jul>nodename: Ubuntu machine: x86_64 clock source: unix detected number of CPU cores: 3 current working directory: /home/jeff/site writing pidfile to /tmp/dmoj-site.pid open("/tmp/dmoj-site.pid"): Permission denied [core/utils.c line 3> My uwsgi.ini code is like this. [uwsgi] # Socket and pid file location/permission. uwsgi-socket = /tmp/dmoj-site.sock chmod-socket = 666 pidfile = /tmp/dmoj-site.pid … -
Understanding reusable apps in Django
I am building a backend REST API using Django and Django-rest-framework for venues to sell tickets and fans to book seats. So far, I have a monolith app called 'concert', which contains all my models.py, serializers.py, and views.py. Each of these files now has 1000+ lines, so I'm thinking about how to split my code into smaller chunks. I watched James Bennett's Reusable Apps talk, but I don't understand why anyone would create reusable apps. For example, I have two models Concert and ConcertTicket. Obviously ConcertTicket has a ForeignKey reference to Concert, and so the model relationship flows in this direction. On the other hand, inside serializers, ConcertSerializer depends back on ConcertTicketSerializer, since I am using the latter as a nested serializer. It seems like if I separate this into a concert and ticket app, I will have a really weird dependency where ticket.models depends on concert.models, but concert.serializers depends on ticket.serializers. I won't be able to share my app to the Django community because of how specialized it is to the industry, so I cannot see why anyone would try to create reusable apps at all. Is this still "best practice" with Django-rest-framework? Wouldn't it be better to maintain … -
Read-only file system error while uploading image/files in django site in Vercel hosting
I have deployed my django site in vercel(using free hosting plan). Now while I am trying to create a model object (which has image/file field) from admin panel, is not saving. Instead of this it is showing that OSError at /admin/portfolio/biodata/add/ [Errno 30] Read-only file system: '/var/task/media' I think media folder is saved in /var/task/media this directory and this directory doesn't have any permission to write it. Here is my models.py: class Biodata(models.Model): name = models.CharField(max_length=100) profile_pic = models.ImageField(upload_to='img/profile_pic') about_me = models.TextField() cv_file = models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) .... .... def __str__(self): return self.name Now, can anyone tell me that how can I override the permission or solve this issue so that I can upload images or files from admin panel. Thanks in advance. -
Docker Container Build integrating Vite, React, Django & Postgres
I am trying to integrate Vite, Django, React and eventually DRF within Docker containers. However, I've been at it for a while, but everything I've tried has become a tangled web of frustration, so I'd be greatly indebted to anyone willing to provide some advice. I got the containers up and running with Django and Postgres with no issues. I then added Vite, and it seemed to be working correctly as well. However, once adding React and the rest of the "static files", whenever I build the container I face the following issues: First, the build fails to run unless I comment out the code in main.js (see below). When I comment out the code in main.js, the build completes, but when I visit the server, index.html loads (without any content), and I get a 404 - Not Found: /main.js in my Docker logs each time. In one iteration, I changed the <script type="module" src="main.js"></script> in index.html to src="frontend/main.js and I stopped getting the 404 error, and the <text>hello,world</text> element was displayed correctly. However, every successive container build fails with: Rollup failed to resolve import "frontend/main.js" from "/frontend/index.html". I'd include the full error, but there's enough code here already... File … -
ModelNotFoundError: No module named 'guardian.shortcuts'
I am trying to run a Django project, I tried to import assign_perm and remove_perm from guardian.shortcuts (code listed here: from guardian.shortcuts import assign_perm, remove_perm). and got an error: ModuleNotFoundError: No module named 'guardian.shortcuts' I am using python3.8.9 and django2.0.7. I have already tried install guardian(0.2.2) and Django-guardian(2.4.0). Please help me to figure it out. THX! -
How can i add a searchable drop down list/filter of cities?
I created a map using Folium in Python to visualize some geospatial data. However, I want to add a search bar with a drop-down list of cities that I want to manually write. This search bar should allow users to search for a specific city and, upon selection, the map should automatically pan to that city's location. How can I achieve this functionality using Folium? **index.html** <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <title>HomePage</title> </head> <body> <!--- NAVBAR --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Map App</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'index' %}">Map <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> <form class="form-inline my-2 my-lg-0" method="post"> {% csrf_token %} {{form}} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!---END NAVBAR--> <div class="container"> <div class="row mt-5"> <div class="col-md-12 offset-md-0"> {{m | safe }} </div> </div> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script … -
Django View - How to Efficiently Filter Combined Querysets from Multiple Models?
I have a Django view that combines and sorts querysets from three different models (Event, Subject, and Article) to create a feed. I'm using the sorted function along with chain to merge the querysets and sort them based on the 'created_at' attribute. The feed is then returned as a list. However, I'm facing challenges when it comes to filtering the feed based on user-provided search and author parameters. Since the feed is in list form, I can't directly use the filter method from the Django QuerySet. class FeedView(View): form_class = YourFormClass template_name = 'your_template.html' def get_queryset(self): """ Get the combined and sorted queryset from events, subjects, and articles. """ events = Event.objects.all() subjects = Subject.objects.all() articles = Article.objects.all() feed = sorted( chain(articles, subjects, events), key=attrgetter('created_at'), reverse=True, ) return feed def filter_queryset(self, queryset): form = self.form_class(self.request.GET) if form.is_valid(): data = form.cleaned_data search = data.get('search') if search: queryset = [item for item in queryset if search in getattr(item, 'name', '')] author = data.get('author') if author: queryset = [item for item in queryset if author in getattr(item, 'created_by__username', '')] return queryset def get(self, request, *args, **kwargs): queryset = self.get_queryset() queryset = self.filter_queryset(queryset) context = { 'object_list': queryset, } return render(request, self.template_name, context) -
Submenu not displaying properly when i fectch data from database in Django
Good all I wanted to create a dynamic menu with submenu populating the menus from database. I created two tables mainmenu which related to submenu. The mainmenu gets populated and is didplayed properly but the submenu is populated but does not dropdown properly, the submenu stays ontop of each other. However if I manually code both mainmenu and submenu both work far. What am I doing wrong? Thanks for your time. What I Wanted What I am Getting My Code - Django Template <div class="collapse navbar-collapse sub-menu-bar" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> {% for mainmenu in mainmenu %} <li class="nav-item"> <a href="{{ mainmenu.menulink }}">{{ mainmenu.name }}</a> {% for submenu in mainmenu.submenu.all %} <ul class="sub-menu"> <div> <a href="{{ submenu.menulink }}">{{ submenu.name }}</a> </div> </ul> {% endfor%} </li> {% endfor %} </ul> </div> My Custom Context Processor from setup.models import Setup, Mainmenu, Submenu def setup(request): setup = Setup.objects.first() return {'organisation': setup} def mainmenu(request): mainmenu = Mainmenu.objects.order_by("order").filter(menutype="main") return {'mainmenu': mainmenu} def submenu(request): submenu = Submenu.objects.order_by("order").filter(menutype="submenu") return {'submenu': submenu}` **My Database Table** class Mainmenu(models.Model): name = models.CharField(_("Menu Name"), max_length=256, blank=True, null=True, unique=False) menulink = models.CharField(_("Menu Link"), max_length=512, blank=True, null=True, help_text="Enter menu link like this, <code>https://uidc.com.ng/page/display/about-us/</code>") order = models.CharField(_("Menu Order"), max_length=512, blank=True, null=True) is_active = models.CharField(_("Is … -
how do i fix the look of the pages
Error Hi Everyone, I published my django project with ubuntu 22.04 and apache2, but it looks like the picture, I tried many ways for the solution but it didn't work, what do you think might be the reason, thanks in advance it should look like it's not like this -
Django Rest Framework - partial=True is suppressing errors
I have a fairly simple code to patch an object called Entity. I am using HTTP PATCH to pass a few fields and then using the following code to update the Entity object. def patch(self, request, id): entity = getEntityOr404(id) serializer = EntitySerializer(entity, data=request.data, partial=True) print(serializer.__dict__) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) As I pass the following request body in the PATCH call... { "email_id_verified": "true", "phone_id_verified": "true" } ....I see various errors messages in the serializer, the output is as below 'error_messages': {'required': 'This field is required.', 'null': 'This field may not be null.', 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'}} But surprisingly there are no errors in the response returned and the code is 200 OK. When I remove the partial=True it obviously starts throwing all sorts of errors. Can someone help me in understanding what is happening here? -
Django Rest Framework error - This field may not be null for required=False
The Serializer class is as follows: class EntitySerializer(serializers.ModelSerializer): is_active = serializers.BooleanField(required=False) class Meta: model = Entity fields = ['is_active', 'owner_name', ...] extra_kwargs = {'is_active': {'required': False}} The model is: class Entity(models.Model): owner_name = models.CharField(max_length=100, null=False) is_active = models.BooleanField(default=False, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I try to create an Entity with POST request which does not have is_active in the request body it throws the following error { "is_active": [ "This field may not be null." ] } I am expecting that serializer should work as the field is_active is optional and not throw the null error. I don't understand what is wrong. The field is_active is a boolean field and is declared as below is_active = models.BooleanField(default=False, null=True) The django versions are as follows Django==4.2.2 django-environ==0.10.0 django-rest-framework==0.1.0 djangorestframework==3.14.0 -
Trouble importing file from subdirectory in Django project
I have this file structure in Django project: project ├── app └── __init__.py views.py ... tasks └── __init__.py server_tasks.py In views.py I tried to import project/app/tasks/server_tasks.py by typing following statements from tasks import server_tasks or from tasks.server_tasks import * And python3 manage.py runserver gives me following output File "/home/user-unix/python/django_projects/project/app/views.py", line 6, in <module> from tasks import server_tasks ModuleNotFoundError: No module named 'tasks' How can I import server_tasks.py into views.py? I tried answers from very similar question on stackoverflow but it doesn't work for me. -
How to update web page after successfull ajax request without reload the page
I am sending the AJAX request to server and after success I would like to update the page without refreshing it fully. It is my snippet of code, but here I can just reloading the page and not sure how to do that without it, my line does not work either, could you help, please? PS. I am using Django for back-end function saveTags(slug, form, e) { e.preventDefault(); let tags = form.getElementsByClassName("new-tags")[0].value; if (tags != '') { var formData = { csrfmiddlewaretoken: '{{ csrf_token }}', slug: slug, tags: tags, }; var POST_URL = "{% url 'save_tags' %}"; $.ajax({ url: POST_URL, type: "POST", data: formData, success: function (data) { var x = document.getElementById("snackbar"); x.classList.add("show"); setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000); $("document").html(data); //window.location.reload(true); } }); // end ajax } return false; }; -
In Django, print a text in a textarea after clicking on a button
I would like to select an element of the combobox and print it in a textarea, after clicking on the button. I have no errors, but the problem that when I click the button nothing happens I have a combobox with this function: views.py def trips(request): country = request.GET.get('country') trips = Trip.objects.filter(country=country) return render(request, 'trips.html', {"trips": trips}) I would like to print trips in a textarea. So I created the textarea and the button (I DON'T want them in a form) home.html .... .... .... {% include "trips.html" %} <!-- Textarea--> {% include "result.html" %} <!-- NOTE: textarea name="result" id="id_result"></textarea>--> <!-- Button--> <button type="button" class="mybtn" href="{% url 'test'%}">Button 1</button> <button type="submit" name='mybtn' value={{test}}>Button 2</button> In views.py I also added the function to print in the textarea (but surely I must have done something wrong) def test(request, trips): new = ("my trips is ", trips) return render(request,"result.html", {"new": new}) In urls.py urlpatterns = [ path('trips', views.trips, name='trips'), path('mytest', views.test, name='test'), ] -
Django Python : This variable is defined, yet the shell says it is undefined not allowing me to process the page
Hi I'm relatively new to Django and am struggling to understand how models work with views. This is from a form used to create a flashcard. I'm trying to assign the characters inputted in the fields to the classes parameters. Then I would like to display the parameters in a card which I do in the template. Whilst I would like this issue fixed I would also be open to see if there are any better and more efficient ways to approach this issue. This is the section of my views.py that raise the issue: def flashcard(response): if response.method == "POST": form = Flashcard_verif(response.POST) if form.is_valid(): print("is workinggg boii") head = form.cleaned_data["header"] ques = form.cleaned_data["question"] ans = form.cleaned_data["answer"] flashcard_data = Flashcard(header=head, question=ques, answer=ans) global rawHeader, rawQuestion, rawAnswer rawHeader, rawQuestion, rawAnswer = Flashcard(header=head, question=ques, answer=ans).flash_format() print(rawHeader, rawQuestion, rawAnswer) flashcard_data.save() else: form = Flashcard_verif() return render(response, "main/Flashcard.html", { "form":form, "header":rawHeader, "question":rawQuestion, "ans":rawAnswer, }) This is the flashcard model: class Flashcard(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="flashcard", null=True) header = models.CharField(max_length=40) question = models.CharField(max_length=200) answer = models.CharField(max_length=200) def __str__(self): return self.header def flash_format(self): print(self.header, self.question, self.answer) return self.header, self.question, self.answer This is the template: {% extends 'main/base.html' %} {% load static %} {% block … -
Watchlist matching query does not exist
Iam trying to find out if a movie exists on the watchlist on my movie project and this error occured while i goes to detail page of a movie that doesn't exists in watchlist, how can i solve this? this is the code. this is my Watchlist model class Watchlist(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) movie=models.ForeignKey(Movie,on_delete=models.CASCADE) quantity=models.IntegerField(default=1) date=models.DateField(auto_now_add=True) def __str__(self): return self.movie.name this is my movie detail request function on views.py def view_movie(request,mslug): user=request.usermovie=Movie.objects.get(slug=mslug) watchlist=Watchlist.objects.get(user=user,movie__slug=mslug) return render(request,'moviesingle.html',{'mov':movie,'watchlist':watchlist}) this is the movie detail template <div class="social-btn"> {% if watchlist.is_none %} <a href="{% url 'Watchlist:add_watchlist' mov.id %}" class="parent-btn"> <i class="ion-plus"></i> Add to Watchlist</a> {% else %} <a href="" class="parent-btn"> <i class="ion-heart"></i> Already in Watchlist</a> {% endif %} </div> while going to a movie that exists on the watchlsit, its showing 'Already on watchlist', the problem is with the movies not in watchlist.. -
Django: Hide required field in form and generate value from other fields
Having a class like this: class MyClass(): foo = CharField('Foo', max_length=42) bar = CharField('Bar', max_length=42) baz = CharField('Baz', max_length=42) Fields "foo" and "bar" should be show in the form, field "baz" should NOT be shown. When POST'ing, the field "baz" should be generated from "foo" and "bar", e.g.: baz = foo + bar The "baz" field can be prevented from shown in the form by using the "HiddenInput" widget. Ok. But using the CBV: Where to generate the "baz" content from "foo" and "bar"? In the "def post()", in the "def is_valid()", in the "def clean()"? Or somewhere else? -
an error is displayed The view images.views.image_create didn't return an HttpResponse object. It returned None instead
' from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): if request.method == 'POST': # форма отправлена form = ImageCreateForm(data=request.POST) if form.is_valid(): # данные в форме валидны cd = form.cleaned_data new_image = form.save(commit=False) # назначить текущего пользователя элементу new_image.user = request.user new_image.save() messages.success(request,'Image added successfully') # перенаправить к представлению детальной # информации о только что созданном элементе return redirect(new_image.get_absolute_url()) else: # скомпоновать форму с данными, # предоставленными букмарклетом методом GET form = ImageCreateForm(data=request.GET) return render(request,'images/image/create.html',{'section': 'images','form': form}) ' if I write code from the phone and run it on Termux I tried to check the code but didn't find anything -
Implementing WooCommerce attributes into Django
I want to create a model where I can dynamically add the three attributes color, size and type like the images below taken from WooCommerce. Sometimes each feature comes in a single form and sometimes it comes in a double form -
python3.8 cannot import ed448 from cryptography.hazmat.primitives.asymmetric
I am using python3.8 to run a Django project, I tried to import Pisa from xhtml2pdf, got a error message listed below: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/pisa.py", line 26, in <module> from xhtml2pdf.document import pisaDocument File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/document.py", line 24, in <module> from xhtml2pdf.builders.signs import PDFSignature File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/builders/signs.py", line 5, in <module> from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/incremental_writer.py", line 8, in <module> from . import generic, misc File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/generic.py", line 21, in <module> from .misc import ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/misc.py", line 18, in <module> from pyhanko_certvalidator.util import CancelableAsyncIterator, ConsList File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/__init__.py", line 8, in <module> from .context import ValidationContext File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/context.py", line 13, in <module> from .fetchers.requests_fetchers import RequestsFetcherBackend File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/fetchers/requests_fetchers/__init__.py", line 8, in <module> from .cert_fetch_client import RequestsCertificateFetcher File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/fetchers/requests_fetchers/cert_fetch_client.py", line 7, in <module> from ...errors import CertificateFetchError File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/errors.py", line 8, in <module> from pyhanko_certvalidator._state import ValProcState File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/_state.py", line 5, in <module> from pyhanko_certvalidator.path import ValidationPath File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/path.py", line 15, in <module> from .util import get_ac_extension_value, get_issuer_dn File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/util.py", line 10, in <module> from cryptography.hazmat.primitives.asymmetric import ( ImportError: cannot import name 'ed448' from 'cryptography.hazmat.primitives.asymmetric' (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py) P.S. my python version is 3.8.9, Django version is 2.0.7, cryptography version is 2.2.2. Can you please help me to figure it out? THX! -
Sending json and file(binary) together by requests() of python
I have this curl command which send file and data to my api. It works correctly. curl --location 'localhost:8088/api/' \ --header 'Content-Type: multipart/form-data' \ --header 'Accept: application/json' \ --form 'file=@"image.png"' \ --form 'metadata="{ \"meta\": { \"number\": 400 }}"' Now I want to do the equivalent thing to inside of the python. So I use requests however it says TypeError: request() got an unexpected keyword argument 'file' How can I do when sending the json and image data together? headers = { 'Content-Type': 'multipart/form-data', 'Accept': 'application/json' } metadata = {"number":400} response = requests.post('https://localhost:8088/api/', headers=headers, data={ metadata:metadata}, file = { open("image.png",'rb') } ) -
django show field from related model in form
I just don't get it. I have been reading but I am not even close to find the answer. It is most likely extremely easy. I have two models Person (Name and zipcode) and Zip (Zipcode and city). When registering a new person the field name and zipcode should be entered. When zipcode is entered the related correct city from the Zipmodel should be shown models.py class Zip(models.Model): zipcode = models.IntegerField() city = models.CharField(max_length=200) def __str__(self): return str(self.zipcode) class Person(models.Model): name = models.CharField(max_length=200) zipcode = models.ForeignKey('Zip',on_delete=models.CASCADE,) def __str__(self): return self.name forms.py from django import forms from .models import Zip, Person class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'zipcode',) class ZipForm(forms.ModelForm): class Meta: model = Zip fields = ('zipcode', 'city',) views.py from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonForm, ZipForm from .models import Zip, Person def index(request): return render(request, 'theapp/index.html' ) def person_new(request): if request.method == "POST": form = PersonForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('person_detail', pk=post.pk) else: form = PersonForm() return render(request, 'theapp/person.html', {'form': form}) def zip_new(request): if request.method == "POST": form = ZipForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('zip_detail', pk=post.pk) else: form = ZipForm() return render(request, 'theapp/zip.html', {'form': form}) def …