Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form filter a class object by a foreign key
I have these models in models.py class Teacher(models.Model): Gym = models.ManyToManyField(Gym) class Student(models.Model): ... Gym = models.ForeignKey(Gym, on_delete=models.CASCADE) Teacher= models.ForeignKey(Teacher, on_delete=models.CASCADE) ... When creating a Student I have to choose a gym and a teacher, a teacher teaches on a gym, a Student has a Teacher from the Gym that the Student goes When creating a new Student in the forms, how do I select a Gym and filter only the Teachers of that Gym selected? -
Editing Django Wagtail Context
I am trying to add additional context to a home page model pulling from a separate app. The function already in the model is already handling a contact form on the page. I want to add blog posts from a portfolio app. Here is my function within my model: def serve(self, request, *args, **kwargs): from contact.forms import ContactForm from portfolio.models import PortfolioDetailPage context = super().get_context(request) context['posts'] = PortfolioDetailPage.objects.live().public() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): //form stuff try: //more form stuff except Exception as e: //more form stuff return render(request, 'contact/contact_page_landing.html', { 'page': self, 'contact': contact }) else: form = ContactForm() return render(request, 'home/home_page.html', { 'context': context, 'page': self, 'form': form }) In my template, I have the following: {% for post in posts %} <div class="row"> <div class="col-lg-4 col-md-4 col-sm-6"> {% image post.gallery_main_image fill-250x250 as blog_img %} <div class="latest__item"> <img src="{{ blog_img.url }}" alt=""> <h4><a href="{{ post.url }}">{{ post.gallery_name }}</a></h4> </div> </div> {% endfor %} </div> However, I am not getting any posts in my context. The form works properly. It seems this is an issue with the serve function in Wagtail already pulling my context and somehow I am not returning it properly but I cannot … -
Django: limit on permission_required size for TestCase? (PermissionRequiredMixin)
My test case raises a django.core.exceptions.PermissionDenied exception even though permission_required and user permissions seem to be set right. Here is the test case: def test_create(self): """ Test view for creating a new category """ response = self.client.get(reverse('category-create'), {'category': 1}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) Here are the relevant views: class AjaxMixin(PermissionRequiredMixin): """ AjaxMixin provides basic functionality for rendering a Django form to JSON. """ # By default, allow *any* permissions permission_required = '*' def has_permission(self): """ Override the default behaviour of has_permission from PermissionRequiredMixin. """ if self.permission_required == '*': return True else: return super().has_permission() class CategoryCreate(AjaxMixin, CreateView): """ Create view to make a new PartCategory """ # The problem is with 5 or more permissions, TestCase fails... no idea why! permission_required = ('part.add_part', 'part.add_bomitem', 'part.add_partcategory', 'part.add_partattachment', 'part.add_partsellpricebreak', # 'part.add_parttesttemplate', # 'part.add_partparametertemplate', # 'part.add_partparameter' ) If I comment 'part.add_partsellpricebreak', in the CategoryCreate view, the get request response code is 200 and no exception is raised by the test case. If I re-enable it, the test case breaks as stated above. The CategoryCreate view works exactly as intended though the project's UI (eg. permissions are well managed, independently of the size of permission_required). Any leads why is the test case failing when permission_required has … -
Django - Cannot locate images through '/media/'
I cannot seem to get images to work on my django project. I have created a "profile" model that is 1:1 with each user, and one of the profile fields is a profile picture. I have added the following to my settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have added the following to my project urls.py: from django.conf import settings from django.conf.urls.static import static and the following after all my urlpatterns: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The image is saved in my root directory/media/profile_pics When I open the missing image in a new tab, I get a 404 error saying that no image could be found at, "http://localhost:8000/profile/profile_pics/ProfilePic.jpg" However, when I change MEDIA_URL = '/media/' to MEDIA_URL = '/profile/' the picture WILL load on my profile page, profile.html page with the 'profile/' url path, but the picture will not load on any other page. What am I missing? -
Creating Virtual environment issues
Im trying to create my virtual environment and I keep getting a permission denied getting sent back to me from git. im not sute if i understand how to bypass this and im working on windows, i tried some things but i still cant create my first venv. has anyone else has this issue? i figure it was because im not seen as the admin but idk now to establish myself as the admin to be able to do things like that. I just reset git but i can try everything again to take a screencap of the issues. Any help is appreciated! -
Django, how do I create a method that saves records from multiple "model" tables?
They help me understand. I have a model with two linked classes. I have two html views, one of them searches and in the other I save two data. Then in the html search view. I search for cod_pro, and then I can register the two new data in "var". Now what is my question, consult. First: What I understand is to fill the records from the html Record view. But: What I DO NOT understand is. How do I perform the method, to query the data from the view "camp", to register it in the view "var", in addition to the 2 new records.? Is there a method?. Please. Django, Python -
How to generate Django slugs on the fly
My question is, is there a way to generate Django slugs on the fly WITHOUT storing them in the DB? I have been tinkering with get_absolute_url but no luck yet. def get_absolute_url(self): randstr = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest() return reverse(args=[randstr]) Yea I know, why not use uuid, right? Not the point, the question is how to generate slugs on the fly WITHOUT storing them in the DB? I would my urls to change that's the point. -
How in 2020 make dropdown with images in Django Admin?
I spent two hours trying to find out how to customize select2 widget in Django admin to implement the simple feature. I have a model (Article) that may contain many other objects (Pictures). Every picture is a set of FileFields representing the original image file, the thumbnail, post-processed (using Pillow) preview and some meta stuff. What I'm going to achieve is to be able to upload new images on the Article change page, and select/deselect them in the fancy Select2 dropdown widget. How can I achieve that? Should I use ImageField instead of FileField? Should I use inlines and through for ManyToMany relation between Article and Pictures? Should I make my own widget? How do Django admin uses Select2 and how could I pass parameters like "templateResult" to be able to change the look of dropdown items? Thank you in advance. -
Django Authentication not working as expected
I've recently started working on a Web application with Django but I am having troubles with the authentication. I am using Insomnia to test my Rest APIs and everything works fine: I can make a POST request to /api/auth to log in, and then I can access to every login_required route in my api. But the same thing does not happen in the browser: (I'm using simple html pages to replicate the problem) login.html <script> fetch('http://localhost:8000/api/auth', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: "myusername", password: "********" }), }) .then(response=>{ if(response.status === 200) return response.json() else return null }) .then(data=>console.log(data)) </script> private.html <script> fetch('http://localhost:8000/api/privateRoute') .then(response=>{ if(response.status === 200) return response.json() else return null }) .then(data=>console.log(data)) </script> Expected result: Since login.html console logs the response from the api for being successfully logged in, I tought that private.html would had authorization to fetch data from /api/privateRoute (which is decorated with @login_required) Why do the same behaviour works with Insomnia and not with the browser? Can someone help me understand this concept? -
How to Delete a profile picture in Django
I have created a page where a user can upload a profile picture:[![Page][1]][1] But I also want to give the ability to remove the profile picture completly without uploading another image. That should happen when a user clicks on the button "Delete". This is my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) This is my views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserUpdateForm, ProfileUpdateForm from dashboard.models import Notification from .models import Profile @login_required(login_url='account_login') def dashboard_profile(request): n = Notification.objects.filter(user=request.user, viewed=False) if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('dashboard-profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'full_name' : request.user.username, 'notifications': n } return render(request, 'users/profile.html', context) @login_required(login_url='account_login') def delete_image(DeleteView): #delete the image of the users Profile return redirect('dashboard-profile') -
How to populate Django foreign key with a temporary default value?
In my Django web application, when the user creates an account, a record for their account is created in the auth_user table. Now there is one required field on the signup form, a dropdown box, that they will use to select what type of user they are. This value is used to populate a foreign key field in a second 'profile' table. The problem is that this profile table has numerous other required foreign key fields that also need to be populated and I need to create an initial record for the user in that profile table before they fill out the rest of their profile (and thus setting these other foreign key fields). This may not happen for some time after the account is created. Is there a way to do this in Django? I know you can set FK fields to blank=True, null=True if the field is optional, but this field really is required. I'd like to trick Django into designating it as required with a temporary value, perhaps by adding a record like "TBD" to the table pointed to by the FK. But putting a "TBD" field in the other table seems "unclean" to me. How do … -
How to add additional info when registering a proxy User?
I've followed this youtube video to implement the below. A Player is a User, proxied. I created a PlayerMore model to add additional info to Player, and I was hoping to add info to PlayerMore at the same POST request in which a Player is created. But the fields for PlayerMore don't even show in my DRF apiRoot page. models.py class User(AbstractUser): class Types(models.TextChoices): PLAYER = "PLAYER", "Player" MANAGER = "MANAGER", "Manager" type = models.CharField(_('Type'), max_length=50,choices=Types.choices,default=Types.PLAYER) def get_absolute_url(self): return reverse("users:details", kwargs={"username": self.username}) class PlayerManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(type=User.Types.PLAYER) class PlayerMore(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) player_info = models.CharField(max_length=256) class Player(User): base_type = User.Types.PLAYER objects = PlayerManager() @property def more(self): return self.playermore class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.PLAYER return super().save(*args, **kwargs) serializers.py User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email') extra_kwargs = {'passwords': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) token = Token.objects.create(user=user) return user class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = '__all__' -
How to return a excel file back to a user using Django and Pandas
I am currently taking an excel file from the user on my home.html page, passing it to my python, using the values to do some logic, and wanting to returned a excel file back to the user after the logic has edited the data. I had this working as an .exe on my computer already but wanted to move it to a web page. I am not currently getting any errors. Does anyone know how to do this, or know of a walkthrough that might can help me? def page_objects(request): Area = request.POST["Area"] Output = request.POST["Output"] FilePath = request.FILES['myfile'] if Output == 'List': zone = pd.read_excel(FilePath, sheet_name= "Form", header=0, usecols=list(range(7))) WC = zone.iat[3,4] data = pd.read_excel(FilePath, sheet_name="Form", header=0, usecols=list(range(7)), skiprows=8) data2= pd.read_excel(FilePath, sheet_name="Form", header=0, usecols=list(range(7)), skiprows=8) Then I do some logic writer = ExcelWriter(FilePath) data.to_excel(writer, 'Sheet1', index=False) data2.to_excel(writer, 'Sheet2', index=False) writer.save() When I was using the .exe ExcelWriter("location where I saved the new file") was how I returned the edited data to myself. -
unsupported operand type(s) for /: 'NoneType' and 'int' [closed]
I have some classes in django class Computer(models.Model): SerialNumber = models.CharField(max_length=30,primary_key=True) Name = models.CharField(max_length=50,unique=True,blank=False) ComputerPicture = models.CharField(max_length=150,blank=True) Details = models.ManyToManyField('Detail',blank='True',related_name='Computers') def sum(self): a = self.Details.all().aggregate(Sum('Price'))['Price__sum'] return a/2 class Detail(models.Model): SerialNumber = models.CharField(max_length=30, primary_key=True) Name = models.CharField(max_length=50, unique=True, blank=False) DetailPicture = models.CharField(max_length=150, blank=True) Price = models.FloatField(blank=False) later i try to use fucntion in shell: pc - element of Computer class >>> type(pc.Details.all().aggregate(Sum('Price'))['Price__sum']) <class 'float'> >>> pc.Details.all().aggregate(Sum('Price'))['Price__sum'] 82500.0 >>> type(pc.Details.all().aggregate(Sum('Price'))['Price__sum']) <class 'float'> >>> pc.Details.all().aggregate(Sum('Price'))['Price__sum']/2 41250.0 it works! but then i try this in code: def sum(self): a = self.Details.all().aggregate(Sum('Price'))['Price__sum'] return a/2 i get an error: unsupported operand type(s) for /: 'NoneType' and 'int' -
How can I have Django serve React using Apache2 on Ubuntu 18.04?
I am trying to deploy a Django application with a React frontend using Apache2 on Ubuntu 18.04. The React application is being served by Django through the staticfiles app. For context, let's start off with how Django is serving React. The following code is from nerd-rich-django-back-end/nerdrich/urls.py. from homepage.views import index url_patterns = [ path('', index, name=index), ] Next we have nerd-rich-django-back-end/homepage/views.py from django.views.generic import TemplateView from django.views.decorators.cache import never_cache index = never_cache(TemplateView.as_view(template_name='build/index.html')) With this configuration Django will serve the React application when the user hits the root endpoint. This works in development, but when I try to replicate this in production I run into some problems. Namely... Here is the site I am using in Apache2 - /etc/apache2/sites-available/000-default-le-ssl.conf <Directory /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerdrich> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerd-rich-front-end/build> Require all granted </Directory> The DocumentRoot directive was deleted and the Django application works fine as there are other endpoints to test like the API endpoints using DRF. But when a request to https://nerdrich.net/ is made, there is only a blank page. If you navigate to https://nerdrich.net/jakuta you will get the browsable API. For additional context, here are some of the settings in Django nerd-rich-django-back-end/nerdrich/settings.py CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' 'http://localhost:5000' ] … -
How to understand following nested function where function passed as argument?
How to understand the following code? nested function function as an argument def check_password(self, raw_password): """ Returns a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) -
Django Rest Framework upload file and in response show the url without database ref
I am trying to upload file directly to server with my expected name and trying to give the file url send in response without saving its ref database field. This is my views: class DocumentUploadView(APIView): parser_classes = [MultiPartParser] def post(self, request, format=None): file_obj = request.data['file'] return Response( status=204 ) I tried to upload with postman and i see no data is saved in my server media folder. Can anyone help me in this case? I dont want to save the url of the file in database imageField or or FileField, i just want to upload it to save it directly in server and in response, it should send me the url. Can anyone help me in this case? -
how to define dependent IntegerField
I'm a beginner with Django and have a model class myModel(models.Model): XYZ = ( (1, "X"), (2, "Y"), (3, "Z"), ) ABC = ((1, "xA"), (2, "xB"), (3, "xC"), (4, "yA"), (5, "yB"), (6, "yC"), (7, "yD"), (8, "zA"), (9, "zB"), ) xyz = models.IntegerField(_('XYZ_Field'), choices=XYZ) abc = models.IntegerField(_('ABC_Field'), choices=ABC) I want to define abc as a dependent field. for example, if the user selects "X" for xyz, valid values for choosing abc are just < xA or xB or xC > or if the user chooses "Z" for xyz, he can just choose zA or zB as right values of abc field. how can I define it in models.py I tried to define XYZ as a dictionary , but I didn't know how to use it for defining choices parameter of abc. XYZ = { (1, "X"): ((1, "xA"), (2, "xB"), (3, "xC")), (2, "Y"): ((4, "yA"), (5, "yB"),(6, "yC"), (7, "yD")), (3, "Z"): ((8, "zA"), (9, "zB"))} xyz = models.IntegerField(_('XYZ_Field'), choices=XYZ) abc = models.IntegerField(_('ABC_Field'), choices=**?????**) Some say it must be handled in forms.py, but I want to do it once in models.py . So all forms which uses this model doesn't need to implement the specific criteria. Any … -
Login not working with react and Django Rest APIs
This is my first time building a React / Django Web App and I am experiencing troubles with the authentication of my platform. I am using Insomnia to test out my Django APIs. Everything works fine so far: I can make a POST request to api/auth and log in. After that I can access to every @login_required route of my APIs. @csrf_exempt def auth(request): if request.method == "POST": # Attempt to sign user in body = json.loads(request.body) username = body["username"] if body["username"] else None password = body["password"] if body["password"] else None user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request,user) return JsonResponse(user.serialize(),status=200) else: return JsonResponse({"error":"Invalid username and/or password."},status=403) if request.method == "GET": if request.user in Users.objects.all(): return JsonResponse(request.user.serialize(),status=200) else: return JsonResponse({"error":"Not logged in."},status=404) return JsonResponse({"error":"Wrong method."},status=405) Here comes the tricky part: when I log in through the Login page ( created with react-router-dom ) it just works and I get my user object from the APIs. But then I go to my home page and everything acts like I'm not logged in. It seems like that the server doesn't recognise that the request on the home page comes from the same client that … -
It is a best practice use a Primary Key in a serializer who do not represent a Model Object?
I'm creating an endpoint in Django for a post REST API. I put the parameters of the post body on a class, to handle it internally, but the senior developer says it is better to use a serializer. I create a serializer and everything worked perfectly until the same senior says I have to add a PrimaryKeyRelatedField. That is when my confusing started because this serializer is not for a Model, but for the body of the request object (who has 3 parameters, one mandatory and two optional), and when I added the mandatory parameters as PrimaryKeyRelatedField, I start to receive on the validated_data an empty OrderedDict() My questions are: It makes sense to have a PrimaryKeyRelatedField in a serializer who does not represent a Model? In case it makes sense, how I can make it work (or why when I make one of the fields primary key, I receive an empty dict?) PS: I make sure to send the right data to the endpoint, so this is not a case of receiving an empty OrderedDict because I did not send the mandatory field -
How to start Django models auto increment key from a certain number like 2456?
In mysql if you want to start your auto-increment key from 2456 you can write AUTO_INCREMENT=2456 Also in PostgreSQL we can do this by using Sequence CREATE SEQUENCE serial START 2456; INSERT INTO distributors VALUES (nextval('serial'), 'nothing'); But in Django Rest Framework or Django by default auto-increment starts from 1. If I have a model like this class Content(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) How can I make sure that the first Content starts from 2456? -
Stack advice for a data visualization project
Since I'm not familiar with all the frontend and backend technologies, I wanted to ask here to get some "best possible approach" ideas. So here is what I wanna do: I have a couple of scripts written in python that do some scientific calculations and modellings by using source and target data in csv formats. Then outputs the results as a text file. 1-) I want to create private user profiles that has custom UI, something like Bootstrap admin dashboard templates with charts, maps and graphs that attached to the user's database. 2-) An admin interface where I can implement and run my python scripts, print the results to a spesific user's database where the charts&graphs recieves their data from. 3-) It will be a commercial platform, so a CMS feautures are needed for tracking orders and etc. I initially thought going with Vue & Django but I'm not so sure it's the best and easiest way of up and run such a project. I appreciate the experienced user's opinions. Thanks in advance. -
Problem with hyperlink in django project in templates html
I have a problem with the hyperlink in my django project. I use python 3.8.5 django 3.1.1. I created 2 applications: blog and pages (with many subpages). https://github.com/Charnel2500/blog_ai_py385_django311 This is my base.html <!DOCTYPE html> <html lang="en"> <link> <meta charset="UTF-8"> <title>Strona startowa</title> <link rel="stylesheet" href="base.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> </head> <body> <div w3-include-html="base.html"></div> <div class="container"> <h1>Witaj użytkowniku w świecie sztucznej inteligencji</h1> <section> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="">Strona Główna</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="blog/"> Newsy <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="history/"> Historia </a> </li> <li class="nav-item active"> <a class="nav-link" href="present/"> AI obecnie <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="philosophy/"> Filozofia AI <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="chatbot/"> Chatbot <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="talk/"> Rozmowa z moim chatbotem <span class="sr-only">(current)</span></a> </li> </div> </nav> </section> {% block content %} {% endblock %} <img src="AI.jpg" alt="Nie znaleziono obrazu"> </div> </body> </html> Here you can see my hyperlinks <li class="nav-item active"> <a class="nav-link" href="blog/"> Newsy <span class="sr-only">(current)</span></a> </li> … -
Django, same file at the output of two different loaded files on one page
model.py: class InJPG(models.Model): file_path = models.FileField(upload_to="media",unique=True) #in forms.py I am taking only this file_path in meta class views.py from model import InJPG def get_name(request): if request.POST: file1=InJPG(request.POST or None) file2=InJPG(request.POST or None) if file1.is_valid(): file1.save() print(file1) if file2.is_valid(): file2.save() print(file2) return redirect(get_name) return render(request,'files.html',{'file1':file1,'file2':file2}) files.html ... {% block page %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{file1}} {% csrf_token %} {{file2}} <button type="submit">upload file2</button> </form> {% endblock %} Situation: As you can see I have page where I am uploading two separate files using browse option in Django, and then to Upload them I'm using submit button, in same form in html file. Problem: I don't know why, but after submit, when I am checking which file has been uploaded, (using print(file1) and print(file2) ) I am receiving ONLY file2. In models.py I have parameter unique=True so names are not identical but, they are coming from same file (file2) How to solve it, and receive file1 and file2 in same method inside view.py ? -
How to leverage Django forms in Next.js frontend application?
I am developing an application which has backend written in Django (Django REST Framework API) and frontend written in Next.js. I am now facing a situation where I need to implement a form that is highly correlated with my Django models. Is there a way to leverage Django's own form system instead of re-implementing it from scratch in Next.js?