Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RESTful API (Django) best practices for admin and normal user access
hello i am working on mobile app that is show for the users to invest on properties and my question is when i implement the APis for the normal user and the admin am i need to make separate APIs for each app because the admin can see and make all operations in the admin dashboard and the normal user can also see the list of all the properties ,get the payment methods and so on.. but on the mobile app not on the admin dashboard example : 1-admin dashboard :http://127.0.0.1:8000/dashboard/api/properties-list/ http://127.0.0.1:8000/dashboard/api/cart-list/ http://127.0.0.1:8000/dashboard/api/cart-update/ and the rest of the APIs 2-mobile app :http://127.0.0.1:8000/mobile/api/properties-list/ http://127.0.0.1:8000/mobile/api/cart-list/ http://127.0.0.1:8000/mobile/api/cart-update/ and the rest of the APIs is that is the best practice for ensuring that the normal user can access the list of the properties from the admin dashboard ? am i try to solve problem that facing me and my expected to have result for my question -
How to fill all input fields automatically from database by entering input in one textbox using django?
I am trying to create a form, where the form details can be autofill from the database by inputting a field in the form using django I was able to see it done in javascript, but i don't know how to connect it to my views.py in django -
Django Object id's passed to the template are not the same inside the view
When I am submitting the form, the question id's that are inside the view do not match with the question id's from the request.POST. When submitting the from, the print statements from the view below are: <QueryDict: {'csrfmiddlewaretoken': ['token here'], 'question_15': ['option1'], 'question_17': ['option1']}> question_4 question_5 Inside the request.POST the id's are 15 and 17, and inside the view 4, 5. Everytime i am submitting the form, the id's do not match. View: @login_required def quiz_view(request): questions = QuizQuestion.objects.order_by('?')[:2] user = request.user if request.method == 'POST': print(request.POST) for question in questions: input_name = f"question_{question.id}" print(input_name) option_selected = request.POST.get(input_name) if option_selected: # Check if the user has already responded to this question existing_response = QuizUserResponse.objects.filter(user=user, question=question).first() if existing_response: # Update existing response existing_response.response_text = getattr(question, option_selected) existing_response.save() else: # Create new response QuizUserResponse.objects.create(user=user, question=question, response_text=getattr(question, option_selected)) return redirect('users:gaming_quiz') else: context = { "questions": questions, } return render(request, 'general/quiz_template.html', context) HTML: <form method="post"> {% csrf_token %} {% for question in questions %} <div> <label class="question">{{ question.question_text }}</label> <ul class="errors"> {% for error in form.errors %} <li>{{ error }}</li> {% endfor %} </ul> <div> <label class="form-check-inline"> <input type="radio" name="question_{{ question.id }}" value="option1"> {{ question.option1 }} </label> <label class="form-check-inline"> <input type="radio" name="question_{{ question.id }}" … -
how to fix SMTPServerDisconnected at /accounts/register/ Connection unexpectedly closed in django
I am working on a project using django where the user needs to register and get the activation link on email and login. everything is working fine user can register but not able to see activation link on email instead it brings the error: SMTPServerDisconnected at /accounts/register/ Connection unexpectedly closed in django here is part of my settings.py i have my .env file where i kept my MAIL = rukiaselemani360@gmail.com and PASSWORD i put the password generated by App Password after two-factor authentication enabled on Gmail account. # settings.py mail = os.environ.get("MAIL") mail_pass = os.environ.get("PASSWORD") EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = mail EMAIL_HOST_PASSWORD = mail_pass DEFAULT_FROM_EMAIL = mail # views.py from .forms import RegistrationForm from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes, force_str from .tokens import account_activation_token from django.core.mail import EmailMessage from django.contrib import messages from django.shortcuts import redirect, render from django.contrib.auth import get_user_model, login from django.urls import reverse def index(request): messages_to_display = messages.get_messages(request) return render(request, "index.html", {"messages": messages_to_display}) def register_user(request): form = RegistrationForm() # Initialize the form instance if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = … -
Django mysql icontains not working for small case
When I type Travel exactly same as my database it's working but when type travel it's working even I tried icontains for ignore case sensitivity. my code: similar_titles_query = Q(title__icontains=search_query) & Q(parent_product__isnull=True, domain_name=domain_name,is_published=False) similar_titles_results = Product.objects.filter(similar_titles_query).order_by('?')[:5] -
Django: Select multiple random ids and insert to database
I'm generating schedules and it will automatically choose from RoutePoint class. I wanted to POST all these ids and create # of rows based on how many id's the user wants. This is how I select random ids. no_of_route = request.POST.get('time') items = list(RoutePoints.objects.all()) random_route = random.sample(items, no_of_route)[0] So the problem is, I don't know how to insert these ids. Like bulk insert? If the user choose 3 no_of_route, there should be 3 rows inserted to 'Schedule' table. Schedule.objects.create(route=random_route, report_time=report_time) This is my first time, so I'm not sure how to do it exactly. Thank you for your help. -
Setting AUTH_USER_MODEL for user app within a v1 folder
My django project structure looks like this /api manage.py poetry.lock /api /v1 __init__.py /users __init__.py models.py ... /properties __init__.py ... I'm trying to set up a custom User model by setting AUTH_USER_MODEL within settings.py. However, I'm getting this error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.User' that has not been installed I've tried values AUTH_USER_MODEL = "api.v1.user.User" AUTH_USER_MODEL = "v1.user.User" AUTH_USER_MODEL = "user.User" But none of them fixed the issue I also have these INSTALLED_APPS INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "api.v1.users", "api.v1.reservations", "api.v1.properties", ] and my User model currently looks like this class User(AbstractUser): pass -
issues when installing an existing DRF react app on pythonanywhere
What i need ? Install and run given app code from link below on pythonanywhere https://github.com/veryacademy/YT-Django-DRF-Simple-Blog-Series-JWT-Part-3.git pre requisite is install npm, npx. For this I referred to page https://help.pythonanywhere.com/pages/React/ what i am trying ? CMIIAW. I presume that "react" folder in the git is already a create-react-app ( minus node_modules ) So to create node_modules folder I can create a new react app called "frontend" and copy node_modules into "react" folder npm install -g react create-react-app npx create-react-app frontend what i am getting ? (.myenv) 04:01 ~/YT-Django-DRF-Simple-Blog-Series-Part-1/react (master)$ npx create-react-app frontend --force Creating a new React app in /home/nightly/YT-Django-DRF-Simple-Blog-Series-Part-1/react/frontend. Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts with cra-template... npm ERR! code Unknown system error -122 npm ERR! syscall write npm ERR! errno -122 **npm ERR! Unknown system error -122: Unknown system error -122, write ** npm ERR! A complete log of this run can be found in: /home/nightly/.npm/_logs/2024-04-20T04_01_57_768Z-debug-0.log Aborting installation. npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed. Deleting generated file... node_modules Deleting generated file... package.json Deleting frontend/ from /home/nightly/YT-Django-DRF-Simple-Blog-Series-Part-1/react Done. Even a --force option does not help here. How to solve this issue, so that I can … -
How to upload React-Django project on GitHub
enter image description here My website Backend on Django and the Frontend on React Backend enter image description here Frontend enter image description here When me try to upload the project on backend folder push to the GitHub -
Django: Get values as list from annotate queryset
I used annotate to compute the total entry per month. How can I get the values as a list? stats = EntryMonitoring.objects.filter(student_id=user).annotate(month=TruncMonth('date')).values('month').annotate(total=Count('id')) With this line, I got this: <QuerySet [{'month': datetime.date(2024, 3, 1), 'total': 25}, {'month': datetime.date(2024, 4, 1), 'total': 2}]> How can I get the values of 'total' as list like this [25, 2, ...] ? Cause when I tried to get the value using this {% for obj in stats %}{{ obj.total }}{% endfor %} in html, it shows 252. -
What methods are possible to deploy an app that uses Django and Vue?
I have recently started to develop a web application, with Django as my backend and Vue.js as my frontend. In the project folder, the Django backend exists as the app 'api'. Whereas the frontend is simply referred to as 'frontend'. I'm slowly starting to consider deployment, but I seriously have no idea how to go around it. My only guess is to deploy two separate apps on a platform like heroku, where I would be communicating with the API from the frontend. Tutorials really lack the detail in using specific frameworks, which is why I would be so grateful if someone could point me into the best direction for deploying the web-app. I'm inclined to use heroku due to it's simplicity, but I'm also open to suggestions. -
how to add autocomplete on foreign key in django admin?
I try to add autocomplete on foreign key in django admin but unfortunately it doesn't work and I can't do search and filter data for foreign key in django admin panel here is my Participants Model `class Participants(models.Model): title = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) session = models.ForeignKey(Sessions, on_delete=models.CASCADE, related_name='participants', null=True, blank=True) day = models.ForeignKey(Days, on_delete=models.CASCADE, related_name='participants', null=True, blank=True) price = models.IntegerField(blank=True, null=True) datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='participants', blank=True, null=True) startDay = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='participants', blank=True, null=True) endDay = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='end_participants', blank=True, null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='participants', null=True, blank=True) created = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='participant', blank=True, null=True) authority = models.TextField(unique=True, blank=True, null=True) success = models.BooleanField(blank=True, null=True)` here is my Participants admin. `from django.contrib import admin from .models import * class ParticipantsAdmin(admin.ModelAdmin): autocomplete_fields = ['user',] admin.site.register(Participants, ParticipantsAdmin)` here is my User admin. `from django.contrib import admin from User.models import User class UserAdmin(admin.ModelAdmin): list_display = ('name', 'number') search_fields = ('name', 'number') admin.site.register(User, UserAdmin) ` django admin panel I will be thankful for your help sorry for my bad english. I try this doc https://medium.com/@vigneshun/how-to-create-autocomplete-fields-for-user-selection-in-django-admin-efa12833cab7 but still not working. -
What is the best way to make changes to my django postgres database in production?
I have a django app on heroku with postgres db. If I try to do any changes now locally nothing works because I put environmental variables in. So i need to take all of that out of my settings.py and put the correct values in. Then after I make changes I need to take it all out again before commiting it back. Also i seem to get connection errors with the postgres database when changing it from production back to development. I'd like to be able to make changes to models, views and html templates locally and then just commit it back up. Is it possible to just commit the models.py up to github and then run the migrations on heroku? I see there is a heroku console in my app dashboard. Can this be used to run commands like manage.py? -
django rest framework AttributeError: 'function' object has no attribute 'get_extra_actions' when accessing from react
I seem to be getting the following error, but seemingly only when I access from React. 2024-04-19 18:30:28 File "/app/config/urls.py", line 29, in <module> 2024-04-19 18:30:28 path('api/', include(router.urls)), 2024-04-19 18:30:28 ^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 77, in urls 2024-04-19 18:30:28 self._urls = self.get_urls() 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 338, in get_urls 2024-04-19 18:30:28 urls = super().get_urls() 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 236, in get_urls 2024-04-19 18:30:28 routes = self.get_routes(viewset) 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 File "/usr/local/lib/python3.12/site-packages/rest_framework/routers.py", line 152, in get_routes 2024-04-19 18:30:28 extra_actions = viewset.get_extra_actions() 2024-04-19 18:30:28 ^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-04-19 18:30:28 AttributeError: 'function' object has no attribute 'get_extra_actions' urls.py: router.register(r'hello', views.HelloViewSet, 'hello') views.py: @api_view(['GET']) @permission_classes([AllowAny]) class HelloViewSet(viewsets.ModelViewSet): #dummy serializers and queryset for now serializer_class = SomeDummyDetailSerializer queryset = SomeDummyObject.objects.all() permission_classes = [DjangoObjectPermissions] def list(self, request): #get list return Response({'message': 'Hello, worlds!'}) def retrieve(self, request, pk=None): #get detail return Response({'message': 'Hello, worlds!'}) Am I missing something here? Most errors I see with this seem to be using views instead of ViewSets with router. I also seemingly need to set the @api_view to override 401 denied errors, but I assume that's a separate issue with token authentication or soemthing. -
base_profile not creating/migrating to SQLite
I am able to migrate base_post to the database but for some reason I do not get any errors relating to base_profile but it is not a table in the database. migration filemodels.pyviews.pydatabase I tried to makemigrate, migrate, migrate base zero(which gives me the error of no base_profile as well so it wont delete all the migration files). -
Send api key from a django template
I have a backend application with django, hosted in lightsail and using api gateway to manage it. The entire backend application is protected by the API key, this means I need to send an api key on each request, this is only for post opperations, for GET the api key is not necessari. so, in my urls.py i set an index view which serves my template, a simple form with a send button. this send button will actually send a request to the backend application, but as this is a POST, it needs an api key. I cannot load the api key as a context because if I console.log() the api key will be exposed, tearing down all the protection for POST operations. is there a way to send a POST operation with the API key avoiding it to be seen from the index? both the index and the backend operations live in the same django project. I have tried sending it as context api_key = settings.API_KEY context = {'api_key': api_key} return render(request, "index.html", context) but printing it from the browser's console it actually prints the api key, it should be hidden but still able to be sent. -
Unable to send data to the web server. "Not found: /api/posts", 404
I'm new to Django REST framework and I'm still trying to wrap my head around it. I'm trying to develop a desktop app and a forum website, where the desktop app would be able to send data to the forum website, resulting in creation of new posts/threads. Currently, when I try to send data with the desktop app to the website, I get the following message in my cmd: "POST /api/posts HTTP/1.1" 404 4155 Not Found: /api/posts I have this in my urls.py from django.urls import path, include from .views import ThreadListView, ThreadDetailView, CreateThreadView, CreatePostView, PostViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'posts', PostViewSet) urlpatterns = [ path('', ThreadListView.as_view(), name='thread_list'), path('thread/<int:pk>/', ThreadDetailView.as_view(), name='thread_detail'), path('thread/create/', CreateThreadView.as_view(), name='create_thread'), path('thread/<int:pk>/post/', CreatePostView.as_view(), name='create_post'), path('accounts/', include('accounts.urls')), ] # include the urls generated by the router urlpatterns += router.urls serializers.py: from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' views.py: class CreatePostView(CreateView): model = Post fields = ['content'] def form_valid(self, form): # Get the thread object base on the url parameter 'pk' thread = Thread.objects.get(pk=self.kwargs['pk']) # Set the thread for the post form.instance.thread = thread form.instance.author = self.request.user # Save the post form.instance.save() # update the … -
Referencing a foreign key field attached to another model in a Django filter
I have a Profile model which is related to the Django User model via a 1:1 relationship. In the profile model is a field "nickname." I am filtering a table with a foreign key to the User model but want to display the nickname in the filter. Is it possible to do this, and if so, how? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) nickname = models.CharField(max_length=20,blank=False) class MyCourse(models.Model): instructor = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=False) [other stuff] class MyCourseFilter(django_filters.FilterSet): sorted_nicknames = <WHAT GOES HERE?> nickname = django_filters.ModelChoiceFilter(queryset=sorted_nicknames, label='Nickname') -
Django + Frontend Framework: SEO, rendering strategy, user experience and familiarity
I'm a new full-stack developer comfortable with Django and looking to build a few new web applications this year. While Django offers templating, I'm considering using a separate frontend framework like Vue.js for enhanced user experience. However, I'm unsure about the best approach for SEO and rendering strategy, would love to hear from more experienced devs what you think about it I could separate backend from frontend entirely and use Django Rest Framework to implement APIs for my frontend. I'm quite new to Vue.js so I'm also open to other strategies like using Django templating and only integrate Vue.js selectively within my templates for specific functionalities. Would I need DRF then as well? I also want to you Stripe to handle payments and Auth0 for authentication but looks like both should integrate quite well with my backend and frontend Any recommendations, explanations, and best practices related to SEO, SSR, CSR, and integrating Vue.js with Django would be greatly appreciated! Bonus points for mentioning specific libraries or tools that could be helpful for this setup (like Axios) Tech stack: Backend: Python + Django Potential Frontend Framework: Vue.js + Tailwind CSS Database: PostgreSQL -
How to properly use TailwindCSS with Django forms
I'm trying to use TailwindCSS in my Django project and can't find a way to cleanly style forms. There are a ton of ways on the internet, but all of them seem a little bit dirty. The way styling is implemented in Django docs is through widgets, but adding custom attrs to each field of each form doesn't look great, especially with large Tailwind classes. Or maybe I misunderstood how it supposed to be done? And about crispy-tailwind, it's great, but I wanted a little bit more control over styles than it gives. -
Django save override only if anything other than a single field is updated?
I realize a version of this has been asked and answered, but I believe my question is slightly different enough where I could not find an answer. I have a model with a version that I want to increment by 1 any time the object is updated/saved. But I only want to increment the version if any field values were changed other than the program. Put another way, a training's version should not be incremented if the only change was adding or removing a program. There are times where the program will be changed along with other fields, in which case it should increment. models.py class Training(BaseTeamModel): title = models.CharField("Title",max_length=254) description = models.TextField("Description", blank=True) program = models.ManyToManyField(Program,related_name='programs') version = models.IntegerField(default=0) def save(self, *args, **kwargs): # How to increment the version only if fields were changed # other than program. self.version = self.version + 1 super(Training, self).save(*args, **kwargs) I could compare each value with the previous value for each field, but that is not scalable and would result in some messy models. -
request.user.is_authenticated does not work in templates
when using {%if request.user.is_authenticated%} or {%if user.is_authenticated%}, nothing happens because of what it can be? And for some reason, the check for user.is_admin or user.is_staff does not work. footer.html: {% if request.user.is_authenticated %} <li class="footer__widget--menu__list"><a class="footer__widget-- menu__text" href="#">My Account</a></li> {% else %} <li class="footer__widget--menu__list"><a class="footer__widget-- menu__text" href="{% url "users:login" %}">Login</a></li> {% endif %} {% if user.is_admin or user.is_staff %} <li class="footer__widget--menu__list"><a class="footer__widget- -menu__text" href="{% url "admin:index" %}">Admin Panel</a></li> {% endif %} it is used in main.html: {% include "includes/footer_section.html" %} Maybe because of this I redefined the usermodel to my own usermodel? I found a similar question, but it didn't help -
how can I render tag set in my django template
I'm trying to render tags from a many to many relationship but I'm missing something These are my models: class Post(models.Model): date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='posts', null=True, blank=True) title = models.CharField(max_length=200) content = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='post/images/', null=True, blank=True) slug = models.SlugField(max_length=200, unique=True, null=True, blank=True) tag = models.ManyToManyField('Tag', related_name='posts', blank=True) def save(self, *args, **kwargs): if self.image: ext = os.path.splitext(self.image.name)[1] filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}{ext}" self.image.name = filename if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) class Tag(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, blank=True) post = models.ManyToManyField(Post, related_name='tags', blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name This is my template snippet {% for post in posts %} <div class="news-card"> <img src="{{post.image.url}}" class="news-img" alt="News" /> <div class="news-listing"> <ul class="tags"> {% for tag in post.tag.all %} <li class="tag">{{tag.name}}</li> {% endfor %} </ul> <h3 class="news-title"> <a href="{{post.slug}}" >{{post.title}}</a this is my view and context I'm passing form = MessageForm() context = { 'posts': posts, 'events': events, 'introductorys': introductory, 'products': products, 'form': form, 'authors': 'authors', } return render(request, 'app/index.html', context) I expect a list of tags to generate but the template is not generating any tags -
Uploading a python file in a django admin dashboard to excecute an excel file
i'm a beginner working on a django project, django admin dashboard, using mysql database, one of the tasks is uploading an excel file and execute it with a python file then showing the result. there are 3 types of python files and 3 types of excel files. i should use type1 of python file to execute type1 of excel file, type2 of python file to execute type2 of excel file and type3 of python file to execute type3 of excel file. as it showsenter image description here the images uploading the files is easy butthe main problem is in the executing part it always shows a lot of errors and i'm just a beginner and this is my graduation year i need your help please ! -
Django Autocomplete Light Foreign Key not rendering
I believe I have tried everything but still my field is not rendering. My objective is to be able to find products writing their names. I tried to followed this tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#tutorial My diferent files are like this: models.py: # Product class class Product(models.Model): name = models.CharField(max_length=100) sku = models.CharField(max_length=50, unique=True) category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=get_default_category) availability = models.CharField(max_length=20, choices=[('E', 'Existent'), ('O', 'On demand')]) price = models.IntegerField(default=0) def __str__(self): return self.name # Sales orders class class SaleID(models.Model): date = models.DateTimeField() class Sale(models.Model): ID = models.ForeignKey(SaleID, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() total_price = models.PositiveIntegerField() def __str__(self): return f"Sale of {self.quantity} {self.product.name} for {self.total_price}" forms.py: from dal import autocomplete # Add Product Form to add products class SaleForm(forms.ModelForm): product = forms.ModelChoiceField(queryset=Product.objects.all(), widget=autocomplete.ModelSelect2(url='product-autocomplete')) quantity = forms.IntegerField(required=True, widget=forms.NumberInput(attrs={"placeholder":"Enter quantity", "class":"form-control"}), label="") class Meta: model = Sale fields = ("product", "quantity") # Define the fields to include from the Product model exclude = ("user", "ID", "total_price") SaleModelFormSet = modelformset_factory(Sale, form=SaleForm, extra=1, can_delete=False) views.py: # SALES ADD def add_sale(request): if request.user.is_authenticated: if request.method == "POST": saleid_instance = SaleID.objects.create(date=timezone.now()) sale_formset = SaleModelFormSet(request.POST) # Create instance of SaleFormSet if sale_formset.is_valid(): saleid_instance.date=timezone.now() for sale_form in sale_formset: if sale_form.cleaned_data.get('product') and sale_form.cleaned_data.get('quantity'): # Check it has product and …