Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create object if doesn't exist when calling it by related_name
NOTE: I'm aware of get_or_create and it does not apply here. I have a Django app with a lot of users. One of my project apps must keep some kind of user preferences relating to this app, so in its' models.py I've created: [models.py] class UserPreferences(models.Model): user = models.ForeignKey( get_user_model(), related_name='adminpanel_preferences' ) ... (more boolean fields, integer choices etc) I don't want to use signals for creating a UserPreferences objects every time new user is being created. My idea was to only create an object when such object is somehow requested. This might sound like a perfect get_or_create use case, however I need to call this object from a template using the related_name e.g: [template.html] {% if request.user.adminpanel_preferences.hardcore_mode_enabled %} ... {% endif %} And while normally the request.user.adminpanel_preferences would return UserPreferences.None, I want it to silently create the object (using default field values) instead. Is there a possibility to achieve such behavior without interfering the User model? The UserPreferences are not global app preferences, they only refer to this particular app and I'd love to keep these two independent. I have also tried using a custom objects manager with customized get_queryset method but it doesn't seem to work when using … -
How do you delete all manytomany relationships in a model in form_valid?
I am making a booking system with Django. I want to be able to have a view to "cancel" bookings. This involves setting the participants (manytomany) of the model to None and the booked_by to none. I don't want to delete the booking as someone else might like to book it later instead. I suppose the ability to delete all relationships in manytomany for the BookingSlot would work. I would like to be able to do this in form_valid(). #views.py class CancelBookingView(UpdateView): form_class = CancelBookingForm model = BookingSlot def form_valid(self, form): form.instance.booked_by = None #This works fine form.instance.participants.all = None #This doesn't work return super().form_valid(form) So far as you can see what I have tried, it hasn't worked. Help would be much appreciated, thank you! #models.py class BookingSlot(models.Model): start_time = models.TimeField("Start Time") end_time = models.TimeField("End Time") date = models.DateField("Date") location = models.ForeignKey(Court, on_delete=models.CASCADE) booked_by = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, default=None, blank=True, null=True, related_name="bookedBy_CustomerUser") participants = models.ManyToManyField(CustomUser, default=None, blank=True, related_name="participant_CustomerUser") -
Integrity error handled and personalized message
I put a constraint like this: class Supplier(models.Model): supplier_name = models.CharField(max_length=100, null=False, blank=False) supplier_created_by = models.ForeignKey("users.User", on_delete=models.CASCADE, related_name='user') class Meta: constraints = [ models.UniqueConstraint(fields=['supplier_name', 'supplier_created_by'], name='Supplier unique in company') ] My views is: class supplierCreateView(LoginRequiredMixin, CreateView): template_name = "supplier/supplier_create.html" form_class = SupplierModelForm def get_success_url(self): return reverse("supplier:supplier_list") def form_valid(self, form): supplier = form.save(commit=False) supplier.organisation = self.request.user.userprofile.company supplier.supplier_created_by = self.request.user supplier.save() and my template is a crispy form: <form method="post"> {% csrf_token %} {% crispy form %} <button type="submit" class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md">Submit</button> </form> When I try to add a new supplier which does not respect contraint, I go to a page : IntegrityError at /supplier/supplier_create/ duplicate key value violates unique constraint "Supplier unique in company" DETAIL: Key (supplier_name, supplier_created_by_id)=(suppl1Phil, 3) already exists. How can django check and send a message in my template (going back to it with infos filled before instead of an ugly error page :-) -
The view awesomeinventory.supplier.views.supplierCreateView didn't return an HttpResponse object. It returned None instead in Create view
My code is: views.py class supplierListView(LoginRequiredMixin, ListView): template_name = "supplier/Supplier_list.html" def get_queryset(self): organisation = self.request.user.userprofile.company return Supplier.objects.filter(organisation=organisation) class supplierCreateView(LoginRequiredMixin, CreateView): template_name = "supplier/supplier_create.html" form_class = SupplierModelForm def get_success_url(self): return reverse("supplier:supplier_list") def form_valid(self, form): supplier = form.save(commit=False) supplier.organisation = self.request.user.userprofile.company supplier.supplier_created_by = self.request.user supplier.save() my urls: from awesomeinventory.supplier.views import ( supplierListView, supplierDetailView, supplierCreateView, supplierContactListView, supplierContactCreateView, supplierContactDetailView, ) app_name = "supplier" urlpatterns = [ path("supplier_list/", view=supplierListView.as_view(), name="supplier_list"), path("supplier_create/", view=supplierCreateView.as_view(), name="supplier_create"), path("<int:pk>/detail/", view=supplierDetailView.as_view(), name="supplier_detail"), path("<int:pk>/update/", view=supplierDetailView.as_view(), name="supplier_update"), path("<int:pk>/delete/", view=supplierDetailView.as_view(), name="supplier_delete"), path("supplierContact_list/", view=supplierContactListView.as_view(), name="supplierContact_list"), path("<int:suppk>/supplierContact_create/", view=supplierContactCreateView.as_view(), name="supplierContact_create"), # int is supplier_id path("<int:pk>/Contact/detail/", view=supplierContactDetailView.as_view(), name="supplierContact_detail"), ] I m able to go to supplier:supplier_list page and it works well. But when I want to create a supplier with supplierCreateView, supplier is create but it seems to have an issue with get_success_url as I have error The view awesomeinventory.supplier.views.supplierCreateView didn't return an HttpResponse object. It returned None instead -
Extremely Slow Django Database Querying
Currently I'm working on a Django web application using the ORM database models. But all the database queries that I make take too long (all take more than 20ms up to 17000ms using MariaDB). I even tried querying on very easy db models without any foreign keys or other relations, maybe three columns (one of them an indexed primary key) and with only a few row entries in the db table (maybe 50 rows). Even those take too long. I'm monitoring all the queries with the Django debug toolbar and it shows that even the html template engine rendering of a QuerySet with only 10 results is extremely slow (10000 - 17000ms). It's unacceptable that a simple query like the following takes longer than 20ms: SELECT * FROM Table LIMIT 10 And yes, the tables have indexed columns like the id as the primary key, I don't query from a view and I pay close attention to when I evaluate the queries. It would be acceptable if a process only queried the database like 10 times per 20-100ms each query (users won't be able to notice a latency of 200-1000ms) but since few processes do need a few more queries … -
Exception Value: Field 'id' expected a number but got <WSGIRequest: POST '/api/checkout/'>
I am having problems with passing the Post request via Vue.js in Django. It keeps getting this error when I try to fill up the form and click buy. What I am doing is that I pass it through an api and try to send it to the database and save it there. The page continues working fine, but on the background nothing happens. In console it says error 500 and when clicking on Network it shows all of that information. I've been following this tutorial while building my own stuff: https://www.youtube.com/watch?v=2Ed3fTYcx-w&list=PLpyspNLjzwBmIDrDOaPkLLuy5YDDNW9SA&index=8&ab_channel=CodeWithStein var productapp = new Vue({ el:'#cartapp', delimiters:['[[', ']]'], store: store, data() { return { first_name: '', last_name: '', birth_date: '', phone: '', email: '', city: '', region: '', address: '', references: '', products: [{{productsstring|safe}}] } }, computed: { numItems: function() { return store.state.numItems }, totalCost: function() { return store.state.totalCost } }, methods: { submitForm() { var data = { 'first_name': this.first_name, 'last_name': this.last_name, 'birth_date': this.birth_date, 'phone': this.phone, 'email': this.email, 'city': this.city, 'region': this.region, 'address': this.address, 'references': this.references, }; fetch('/api/checkout/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, credentials: 'same-origin', body: JSON.stringify(data), }) .then((response) => { console.log('success') console.log(response) }) .catch(function (error) { console.log('Error 2'); }) … -
why Django admin list is not updating the edit from the frontend React js form?
i am trying to make a CRUD app in DRF-Reactjs and following Tania rascia's example i have successfully implemented add, delete, list view. but i am trying to edit the a specific row it is not updating in DRF backend. but the edited row is showing in the frontend. in DRF side views.py: @api_view(['POST']) def TodoUpdate(request, pk): todo = Todo.objects.get(id=pk) serializer = TodoSerializer(instance=todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) i am using cors header to interface between frontend to backend. here is the frontend code for edit: App.js: import React,{Fragment, useState,useEffect} from 'react' import EditList from './components/EditList'; import axios from 'axios' export default function App() { const initialTodoSate = { id: null, title: "", body: "" }; const [todos, setTodos] = useState([]); const [todoList, setTodolist] = useState(initialTodoSate); const [editing, setEditing] = useState(false); useEffect(()=>{ axios.get("http://localhost:8000/api/todo-list",{}) .then(res=>{ setTodos(res.data) }).catch(err=>{ console.log(err) }) },[]) const addTodoList = (todo) => { axios .post("http://localhost:8000/api/todo-create/",todo) .then((res) => { console.log(res.data); todo.id = todos.length + 1; setTodos([todo, ...todos]); }) .catch((err) => { console.log(err); }); }; const deleteTodo = (id) => { setEditing(false); axios.delete(`http://localhost:8000/api/todo-delete/${id}/`) .then(res=>{ setTodos(todos.filter((todo) => todo.id !== id)); }).catch(err=>{ console.log(err) }) }; const updateTodo = ( id,updatedTodo) => { axios .post(`http://localhost:8000/api/todo-update/${id}/`, id) .then((res) => { console.log(res.data); }) .catch((err) … -
Select related and prefetch related for multiple reverse foreign keys with Django?
I'm currently having issues accessing values in a queryset. I have a models.py for my app that is set up like this: class Company(models.Model): name = models.Charfield(max_length=250) class Patient(models.Model): status_choices = [ ('A', 'Current Admission'), ('D', 'Discharged'), ('U', 'Unknown'), ] first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) patient_status = models.CharField( max_length=15, choices=status_choices, null=True, default='U', verbose_name='Patient Status' ) related_company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='patients') class PatientStay(models.Model): admit_date = models.DateField() projected_dc_date = models.DateField(null=True, blank=True) is_active = models.BooleanField(default=False) stay_to_patient_relationship = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='stays') class PatientLOC(models.Model): loc_to_stay_relation = models.ForeignKey(PatientStay, on_delete=models.CASCADE, related_name='locs') level_of_care = models.CharField(max_length=30) loc_start = models.DateField(null=True) loc_end = models.DateField(null=True, blank=True) is_active = models.BooleanField(default=False) What I am trying to do is query this to get (for a particular company) the patients, their related stay (filtered for only active), and their related PatientLOC. A result like this: Company: -Patient --Stay ---PatientLOC's -Patient --Stay ---PatientLOC's -Patient --Stay ---PatientLOC's I have come up with this (less the filtering): company = Company.objects.select_related().prefetch_related('patients__stays', 'patients__stays__locs').get(id=2) Which I can loop through and get the patient and the stays, but I cannot seem to get to the LOC's for those patients. So, I can do something like this: company = Company.objects.select_related().prefetch_related('patients__stays', 'patients__stays__locs').get(id=2) patients = company.patients.all() for patient in patients: ...: print(patient) ...: print(patient.stays.all()) But … -
Django: Filtering a related field by date yields unwanted results
models: class Vehicle(models.Model): licence_plate = models.CharField(max_length=16) class WorkTime(models.Model): work_start = models.DateTimeField() work_end = models.DateTimeField() vehicle = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, related_name="work_times") However when I try to filter those working times using: qs = Vehicle.objects.filter( work_times__work_start__date__gte="YYYY-MM-DD", work_times__work_end__date__lte="YYYY-MM-DD").distinct() I get results that do not fit the timeframe given. Most commonly when the work_end fits to something, it returns everything from WorkTime What I would like to have: for vehicle in qs: for work_time in vehicle.work_times: print(vehicle, work_time.work_start, work_time.work_end) -
How does the form set work when saving the information?
I was developing an application which used formset, but at the time I was developing, they generated multiple doubts which were, because the data that persists in the database with formset has to be given a different treatment, that is, because you have to modify the formset.instance. This is my inlineformset: ProjectFormSet = inlineformset_factory( Project, Task, form=TaskForm, fields=['type_task', 'task', 'status'], extra=1, can_delete=True ) This is my CreateView: class ProjectCreateView(CreateView): template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: context['formset'] = ProjectFormSet(self.request.POST) else: context['formset'] = ProjectFormSet() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.save() return super().form_valid(form) If I leave the view like this it will generate an error where it will say that formset.save() is prohibited to avoid data loss due to an unsaved related object, but if I modify the formset.instance if it is saved correctly: class ProjectCreateView(CreateView): template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: context['formset'] = ProjectFormSet(self.request.POST) else: context['formset'] = ProjectFormSet() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance … -
Wrong template rendering
I don't understand why django wont render any other template , but home with this code: urlpatterns = [ url(r'^login/', login_page), url(r'^admin/', admin.site.urls), url(r'^contact/', contact_page), url(r'^about/', about_page), url(r'$', home_page), ] But as soon as I delete the home url , every url works just fine. Yes , I did join the base dir with the templates one. Also , it might be useful to add that Im using django 1.11. Thank you ! -
Django modify objects using key=value options
I'm doing http POST processing of incoming data modifications requests (from a DataTables table) for objects in my Django environment. The POST data comes to me in key=value pairs. The problem I'm running into is that I haven't found a way to turn this into something I can use. Django objects and modifications are done like this: id = 123 item = Stuff.objects.get(id=id) item.title = "New Title" item.save() I have the following data attributes: id = 123 attribute = "title" value = "New Title" How can I use them to modify a Django object? -
Why is django not sending my email and instead giving me an error?
I'm trying to get django to send an email but I get as a return in my terminal the print from my else that says there was a problem and it wasn't sent. Why is this happening? This is the code with the email: from django.core.mail import EmailMultiAlternatives from . import views def constancia_email(email): subject, from_email, to = 'Constancia Monotributo', 'bosi@outlook.es', email text_content = 'Hi, this is your pfd.' html_content = '<p><strong>Hi!</strong></p> <p>This is your pdf</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) attachment = open('constancia.pdf', 'rb') msg.attach('constancia.pdf', attachment.read(), 'text/pdf') msg.content_subtype = 'html' msg.attach_alternative(html_content, "text/html") msg.send() This is the view part with the email: #send email constancia_email(email) if constancia_email == True: print("Sus datos fueron enviados correctamente, en un máximo de 2 hs. estarás recibiendo tu constancia por email.") else: print("No hemos podido procesar su solicitud, por favor reintente nuevamente más tarde.") I added this to my settings because I was getting an error but I'm not sure if this helps because I just get the email in my console but it still isn't sent: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' -
Django ORM is looking for a column that I dont create never
Im trying to pull data from external databse with django. I used inspectdb command for get the models, that database have two tables, when I try to get data from the first table, it works...but when I try to get the data from second table throws the next error: 1054, "Unknown column 'hotel_reviews.id' in 'field list'" The column id dont exist and its correct, but why its looking for it? This is how i have the models: from django.db import models class HotelInfo(models.Model): country_area = models.CharField(max_length=45) hotel_id = models.CharField(primary_key=True, max_length=32) hotel_name = models.TextField(blank=True, null=True) hotel_url = models.TextField(blank=True, null=True) hotel_address = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) review_qty = models.IntegerField(blank=True, null=True) clean = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) comf = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) loct = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) fclt = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) staff = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) vfm = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) wifi = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'hotel_info' unique_together = (('hotel_id', 'country_area'),) verbose_name_plural = "hotels" class HotelReviews(models.Model): uuid = models.CharField(db_column='UUID', max_length=36, blank=True, null=True) # Field name made lowercase. hotel_id = models.CharField(max_length=32, blank=True, null=True) review_title = models.TextField(blank=True, null=True) review_url = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, … -
how to extract zip data from response in django
I want to retrieve data from below url for my django project. city bike trip, I am trying to something like this. data = requests.get('https://s3.amazonaws.com/tripdata/JC-201708%20citibike-tripdata.csv.zip') what I am getting zipped data with some info, my task is to unzip that data and convert it into django model object I saw people using gzip middleware in this answer but not sure if this solves purpose here, -
mock Job interview for python-aws developer
i'm bhandishboy, i'm python developer i've basic experience in web application development using python as language, django as framework, mysql and sqlite3 for storage, django-rest framework for api's. so i can work on CRUD projects. i guess next step will be hosting. for hosting aws services is in market. by going through google, i believe in documentations for every new updates, their uses and future scope. at this point i know how to use boto3 library for aws services in python language but i don't have any hands-on experience on that. on basis of above short description about my self, can company offers me a job? if offers then what will be "the questions" for python-aws developer. if company offer's me a job, i'm capable for first technical round. think i cleared first technical round of job post like python-aws developer, now my question is, if their is an second interview round by client for python-aws developer then what will be "The Questions" by the client Panel? any guess ? suggest me!!. thank you for your time and suggestions!! -
Django look up foreign-key form field (Newbie Question)
This is a basic question, but for some reason I cannot seem to find a straight answer, neither in the docs, nor in this forum. I am sure there must be a simple answer, but then again, I am new to Django (I know Python and databases pretty well) Scenario: 2 classes connected with a foreign key: Order --(foreign key)--> Order-approver (approver pk, fullname, title, etc.). Approver to Order is one-to-many relationship In the order entry form, I want to be able to pick/enter the approver by the full name (Django should presumably translate it into the approver id behind the scene). Ideally, there should be a look up form so I can select an approver by the name from the list How do I do that? What am I missing? -
I wanna use other backend to authenticate my backend
I'm building an app server-side on Django. There is a Laravel server with the authentications of my user. I need authenticate my user with Laravel, because I dont want to make other db on Django with the same users. How can I customize the django to authenticate this way ? -
How can I send a file with python websockets?
I need to transfer a file to a server (Django Channels) via websockets. How can I implement this in Python? -
Django: How do you compare a QuerySet with fields on a ForeignKey objects property?
I am trying to query a model against a field on a foreignkey objects property. I have the following models: class Song(models.Model): name = models.CharField(max_length=20) limit = models.IntegerField() class Recording(models.Model): song = models.ForeignKey(Song, on_delete=models.CASCADE) status = models.CharField( max_length=1, choices=STATUS_CHOICES, default=OPEN ) I would like to query Songs that have Recordings with status OPEN with a count of more than 'limit' (the field on Song). Looking over the django aggregation docs I tried something along the lines of: # View get(self): songs_count = Count('recording', filter=Q(recording__status='O')) songs = Song.objects.annotate(songs_count=songs_count) results = songs.filter(songs_count__gt=< each song.limit... >) Can someone point the way on how to build such a query? I greatly appreciate any and all feedback. -
How to fetch a field class from a specific form in Django?
I'm trying to write a test for the username field and I want to use SimpleTestCase.assertFieldOutput(). The problem is that I cannot get the fieldclass from the field of my form: import django from django.test import TestCase class UserRegistrationTest(TestCase): """Tests for the user registration page.""" def test_username_field(self): data = {'username': 'павел25', 'password1': 'njkdpojv34', 'password2': 'njkdpojv34', 'email': 'pav294@mail.ru', 'first_name': 'Pavel', 'last_name': 'Shlepnev'} f = RegistrationForm(data) self.assertFieldOutput(f.fields['username'], {'pavel25': 'pavel25'}, {'павел25': ['Имя пользователя должно содержать только символы ASCII.']}) When I run the test it raises TypeError: 'UsernameField' object is not callable -
Why is context not passed in formview django get method? Django, python
Error in the browser 'NoneType' object is not callable context = super().get_context_data(**kwargs) … ▼ Local vars Variable Value __class__ <class 'orders.views.OrderAddView'> args () kwargs {'tag': 'fast'} request <WSGIRequest: GET '/orders/add/fast'> self <orders.views.OrderAddView object at 0x00000000056EA430> Why isn't context passed to get? if accept context as self.get_context_data (** kwargs) same error views.py class OrderAddView(FormView): template_name = 'orders/order_add.html' formOne = SimpleOrderAddForm() formTwo = FastOrderAddForm() def get(self, request, *args, **kwargs): self.formOne.prefix = 'one_form' self.formTwo.prefix = 'two_form' context = super().get_context_data(**kwargs) context.update({'formOne': self.formOne, 'formTwo': self.formTwo}) return self.render_to_response(self.template_name, {'context':context}) def post(self, request, *args, **kwargs): formOne = SimpleOrderAddForm(self.request.POST, prefix='one_form') formTwo = FastOrderAddForm(self.request.POST, prefix='two_form') if formOne.is_valid() and formTwo.is_valid(): return HttpResponseRedirect('orders_home') else: return self.form_invalid(formOne, formTwo, **kwargs) def form_invalid(self, formOne, formTwo, **kwargs): context = self.get_context_data() formOne.prefix = 'one_form' formTwo.prefix = 'two_form' context.update({'formOne': formOne, 'formTwo': formTwo}) return self.render_to_response(self.template_name, {'context':context}) -
Django - Textchoices and admin.site.register
I have a choice class TextChoices: class Category(models.TextChoices): vegetable = 'VEG', 'vegetable' fruit = 'FRT', 'fruit' carbs = 'CRB', 'carbs' fish = 'FSH', 'fish' meat = 'MT', 'meat' sweet = 'SWT', 'sweet' dairy = 'DRY', 'dairy' ready = 'RDY', 'ready' # def __str__(self): # return self.name def __str__(self): return self.choices Used in: class Fooditem(models.Model): name = models.CharField(max_length=200) # category = models.ManyToManyField(Category) category = models.CharField(max_length=3, choices=Category.choices, default=Category.vegetable) Now, I would like to make Category editable by admin: admin.site.register(Category) But I have the following error: File "PycharmProjects\Calories_New\Fityfeed\admin.py", line 14, in <module> admin.site.register(Category.choices) File "PycharmProjects\Calories_New\venv\lib\site-packages\django\contrib\admin\sites.py", line 106, in register if model._meta.abstract: AttributeError: 'tuple' object has no attribute '_meta' I am relatively new in Django and would appreciate your help, also in understanding how I can solve these problems myself (struggling with reference documentation) Many Thanks! D -
How to update multiple images in django?
I'm trying to develop a post feauture with multiple images related to it and I have encoutered some problems I can't solve. So, in my models.py I have a Post model and PostImages model with one to many relationship: class PostImages(models.Model): post_id = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, null=True, blank=False) I upload multiple images like this: def addpost(request): if request.method == 'POST': form = CreatePostForm(request.POST) images = request.FILES.getlist('images') if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() for i in images: PostImages.objects.create( post_id = post, image = i, ) return redirect('index') else: return redirect('addpost') else: context = {'formpost': CreatePostForm} return render(request, 'addpost.html', context=context) addpost.html: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formpost.as_p }} <input required name="images" type="file" multiple> <input type="submit" value="Submit"> </form> And I can't figure out how to edit multiple images: I tried something like this in my views.py def update_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.user != post.author: return redirect('index') context = {} images = post.postimages_set.all() count = 0 for i in images: count += 1 imagesformset = formset_factory(UpdateImagesForm, extra=count) context['formset'] = imagesformset if request.method == 'POST': form = UpdatePostForm(request.POST, instance=post) formset = imagesformset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): form.save() for form in formset: if form.is_valid(): … -
What is the best authentication method in django rest framework?
I want my website authentication to be strong For that purpose I have found the following things Combination of Base authentication with CSRF validation for session based authentication JSON Web Token Authentication support for Django REST Framework Which one is better among them? Or is there any other better method out there