Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Docker Volumes?
I am completely new to Docker, right now I am using an open-source tool, which is a Docker application, I need to make some changes to the existing application for my requirement and it should reflect the changes, I did a lot of searching, then I found that we can do this with the help of Docker Volumes, but I am unable to follow any of the articles on the web as well as documentation? Any suggestions will be appreciated. docker-compose.yml: version: "3.3" services: cvat_db: container_name: cvat_db image: postgres:10-alpine networks: default: aliases: - db restart: always environment: POSTGRES_USER: root POSTGRES_DB: cvat POSTGRES_HOST_AUTH_METHOD: trust volumes: - cvat_db:/var/lib/postgresql/data cvat_redis: container_name: cvat_redis image: redis:4.0-alpine networks: default: aliases: - redis restart: always cvat: container_name: cvat image: cvat/server restart: always depends_on: - cvat_redis - cvat_db build: context: . args: http_proxy: https_proxy: no_proxy: nuclio,${no_proxy} socks_proxy: USER: "django" DJANGO_CONFIGURATION: "production" TZ: "Etc/UTC" CLAM_AV: "no" environment: DJANGO_MODWSGI_EXTRA_ARGS: "" ALLOWED_HOSTS: '*' CVAT_REDIS_HOST: "cvat_redis" CVAT_POSTGRES_HOST: "cvat_db" volumes: - cvat_data:/home/django/data - cvat_keys:/home/django/keys - cvat_logs:/home/django/logs - cvat_models:/home/django/models cvat_ui: container_name: cvat_ui image: cvat/ui restart: always build: context: . args: http_proxy: https_proxy: no_proxy: socks_proxy: dockerfile: Dockerfile.ui networks: default: aliases: - ui depends_on: - cvat cvat_proxy: container_name: cvat_proxy image: nginx:stable-alpine restart: always depends_on: - cvat … -
django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint
I want to create a process whereby when a user registers by default he/she is just an ordinary user, then if the user wants additional privileges thereby becoming a "vendor", they have to register with another form (this form should update their already created profile). I tried what i could to this point but i keep getting "null value in column "user_id" violates not-null constraint" when i register with the second form. the UserCreationForm works well, here's the Vendor form: from django import forms from .models import Profile from blog.models import Category from django.db import transaction class VendorRegisterForm(forms.ModelForm): class Meta: model = Profile fields = ['bvn', 'company', 'description', 'address'] @transaction.atomic def save(self): profile = super().save(commit=False) profile.is_vendor = True profile.save() profile = Profile.objects.create(user=user) # student.interests.add(*self.cleaned_data.get('interests')) return profile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=245, null=True) image = models.ImageField(default='default.png', upload_to='profile_pics') interests = models.ManyToManyField(Category, related_name='interests_user') is_vendor = models.BooleanField(default=False) # vendor bvn = models.CharField(max_length=10, null=True, blank=True) description = models.TextField(null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' @property def followers(self): return Follow.objects.filter(follow_user=self.user).count() @property def following(self): return Follow.objects.filter(user=self.user).count() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width … -
Django best practice for scripts organizing
I had the project on Django 3.1 with the following layout: . ├── app │ ├── app │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── core │ │ ├── admin.py │ │ ├── apps.py │ │ ├── fixtures │ │ │ ├── Client.json │ │ │ └── DataFeed.json │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20201009_0950.py │ │ │ └── __init__.py │ │ ├── models.py │ │ └── tests │ │ └── __init__.py │ └── manage.py I want to add 2 scripts to this project: download_xml.py - to check and download .xml files from external sources by schedule (every ~30 min) update_db_info.py - to be invoked by download_xml.py and transfer data from downloaded xml to the database What is the best django practice for organizing a placement for this kind of scripts? My ideas: just create scripts folder inside of an app/core and put scripts there. Invoke them using cron run python manage.py startapp db_update so the new app in django will be created. I will remove migrations, views, models etc from it and put scripts … -
Photos for each post in django
I have created a blog website and I want to display images for every post like YouTube thumbnails. I created an image field in my Post Class but it is not saving my image in the media folder when I create a post. Post class in models.py: class Post(models.Model): name = models.CharField(default='Concert', max_length=100) invite = models.ImageField(default='invite.jpg', upload_to='invite_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) This is my CreatePost class in views.py: class PostCreateView(LoginRequiredMixin, CreateView): model = Post template_name = 'home_page/post_form.html' fields = ['name', 'invite'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I have set the MEDIA_ROOT and MEDIA_URL in settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' So as I have said earlier, the image is not getting saved to media/invite_pics what should I do? -
Wagtail: Filter Page model by a field on the child
I have two models, ParentPage and ChildPage. I want to find the set of ParentPages where a field is_completed is True on the ChildPage. Normally in Django, I could do something like ParentPage.objects.filter(child_page__is_completed=True) However, I don't think there is a join here for the Wagtail/Treebeard hierarchy. I also thought you might be able to filter ChildPages by multiple ParentPages, e.g. ChildPage.objects.children_of([parent_ids]), but I can't see a way to do that either. Is there a simpler way? -
What are the differences between using serializers and for loop to return a json response?
I am trying to create an API to return some JSON responses with Django. The app is just doing some CRUD operations and integration with Shopify API. From my understanding, I know that I can use Django Rest Framework (DRF), plain Django serializer, or return JSON response on my own. From this thread, I know that DRF can give me a better JSON format than Django serializer. However, is it simpler to just loop the Model and return the JSON Response on my own? For example, for product in products: if 'node' in product: returnProduct = {} node = product['node'] returnProduct['id'] = node['id'][22:] returnProduct['updated_at'] = node['updatedAt'].split('T', 1)[0] returnProduct['title'] = node['title'] returnProduct['short_title'] = node['title'][0:48] + "..." if len(node['title']) > 48 else node['title'] returnProducts.append(returnProduct) data = { "products" : returnProducts} return JsonResponse(data) Is it because it's faster to use serializers than looping on my own? Or am I mixing up different scenarios? -
DJANGO - AudioField - problem with make migration - [ERROR (auth.E005)]
I tried make AudioField with django-audiofield My project settings: INSTALLED_APPS = [ ... 'audiofield', ] MIDDLEWARE = [ ... 'audiofield.middleware.threadlocals.ThreadLocals', ] STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') AUTH_USER_MODEL = 'user.Profile' in my models.py I have: class Beat(models.Model): name = models.CharField(max_length=120) audio_file = AudioField(upload_to='/music', blank=True, ext_whitelist=(".mp3", ".wav", ".ogg"), help_text=("Allowed type - .mp3, .wav, .ogg")) def audio_file_player(self): """audio player tag for admin""" if self.audio_file: file_url = settings.MEDIA_URL + str(self.audio_file) player_string = '<ul class="playlist"><li style="width:250px;">\ <a href="%s">%s</a></li></ul>' % (file_url, os.path.basename(self.audio_file.name)) return player_string audio_file_player.allow_tags = True audio_file_player.short_description = _('Audio file player') I cant make migrations. There is some error: ERRORS: audiofield.AudioFile: (auth.E005) The permission codenamed 'view_audiofile' clashes with a builtin permission for model 'audiofield.AudioFile'. -
ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv
Actually, I wanted to create my first django project. After I did some coding in the cmd then I opened the code using visual studio code. I selected the python interpreter on the status bar, then I changed it to the python interpreter installed in my digital environment. After that, I got message that linter pylint is not installed. After I installed that, these errors occurred. enter image description here -
Electron + React as frontend and Django Rest as backend, would it work?
I have built an API using Django Rest Framework which acts as the backend. As of now, I'm using React JS as frontend, just like any other web application. Now I want to get into building a native desktop app using Electron Js. Is there a way to combine Electron and React as one whole desktop app, which throws request to Django API hosted online? A guideline would be much appreciated. Django also throws a CORS error, which when called from a non-listed url. Usually, when calling from React js as a normal application, we'll list out the port number/base URL as whitelist. How exactly things work when calling it from a desktop app? -
starting with N froms in django modelformset where N = len(initial)
I'm using a formset in django to save multiple instances of the same Model. I don't intend to use the formset to edit existing instances of that model, I only intend to create multiple new instances using this formset. However, the formset will take a list of initial form values which can vary in size. I want the formset to be rendered with exactly N instances of my modelform, where N is equal to the len of the initial list passed. I don't want to create the instances in the database and pass them as a queryset, because i could end up making 40 instances of the model when only 4 are required. From the docs on formsets: If the number of items in the initial data exceeds max_num, all initial data forms will be displayed regardless of the value of max_num and no extra forms will be displayed. For example, if extra=3 and max_num=1 and the formset is initialized with two initial items, two forms with the initial data will be displayed. from docs on modelformsets As with regular formsets, it’s possible to specify initial data for forms in the formset by specifying an initial parameter when instantiating the … -
how to use Django Hitcount in a function based view rather than a class?
The documentation covered only the usage of Django-Hitcount in a class-based view. from hitcount.views import HitCountDetailView class PostCountHitDetailView(HitCountDetailView): model = Post # your model goes here count_hit = True # set to True if you want it to try and count the hit Is there any way to use it in a function? -
Filtering one model based on another model's field
I have the following models: class User(AbstractUser): pass class Post(models.Model): post_user = models.ForeignKey(User, on_delete=models.CASCADE) post_content = models.TextField() post_date = models.DateTimeField(default=timezone.now) class Follow(models.Model): follow_user = models.ForeignKey(User, on_delete=models.CASCADE) follow_target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follow_target') I'm trying to create a queryset of all posts that were created by users I follow (me being the currently logged in user). My queryset currently looks like this but I keep getting NameError: field not found: postresult = Post.objects.all().filter(post_user=follow__follow_target, follow__follow_user=request.user) Any help will be greatly appreciated! -
Enable and Disable a request paramaters in Django drg-yasg swagger
I'm trying to customize my API documentation build with drf-yasg. I'm using Django=3.0.3, djangorestframework==3.11.0 and drf-yasg==1.17.1 Here in the Get method, I want to disable broadcast_week param if the user chooses adhocRequirementName param value other than valid_actual_runs. I'm not sure this is possible or not because I don't find anything like this in the documentation. Anyone pls let me know if any way to do this or let me know this is possible or not. PFA for your reference Thanks -
DJANGO - DISPLAY ONLY LOGGED USER PROJECTS
i'm working on a django project that manages some projects. In a view I have to show only the projects of the logged in user, but everything i do doesn't work and i really don't know what else to try. I'm new to programming. Basically my application has a Worker Model that has only a field: worker = models.ForeignKey(User) Then it has a Responsable Model that has only one field: responsable = models.ForeignKey(User) I have these 2 models because i need to separate the users in workers and responsables. This is my project Model: class Project(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=1000) client = models.ForeignKey(Cliente, on_delete=models.CASCADE) complete = models.BooleanField(default=False) urgent = models.BooleanField(default=False) deadline = models.DateField() worker = models.ForeignKey(Worker, on_delete=models.CASCADE) responsable = models.ForeignKey(Responsable, on_delete=models.CASCADE) This is in my views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login/') def projectsWorkers(request): user = request.user user_projects = Project.objects.filter(worker=user).order_by('deadline') template = 'projects/projects-worker-home.html' return render(request, template, {'user_projects': user_projects, 'user': user}) but i get an error: Cannot query "Simone": Must be "Worker" instance. I think that the problem is the fact that in my Project Model the worker field has a foreign key to Worker and not to User, but i can't change that, so what … -
Commiting new changes to Gunicorn + Nginx + Django dockerized application in server
Docker novice here. I have committed new changes inside the application. These changes where copied from my local to host machine, and then to docker container. So I created a new image sudo docker commit old_container_id new_image_name(djangotango-on-docker_web) Then I spin the docker container by using new image created. sudo docker run --name djangotango-web -d --expose 8000 djangotango-on-docker_web gunicorn djangotango.wsgi:application --bind 0.0.0.0:8000 Here djangotango-on-docker_web is my new image created. But my application gives 502 error after this. My new container is not synced properly. dockerfile version: '3.8' services: web: build: context: . dockerfile: Dockerfile.prod command: gunicorn djangotango.wsgi:application --bind 0.0.0.0:8000 volumes: # - .:/home/app/web/ - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.prod db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db depends_on: - web pgadmin: image: dpage/pgadmin4 env_file: - ./.env.prod.db ports: - "8080:80" volumes: - pgadmin-data:/var/lib/pgadmin depends_on: - db links: - "db:pgsql-server" environment: - PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org - PGADMIN_DEFAULT_PASSWORD=root - PGADMIN_LISTEN_PORT=80 nginx: build: ./nginx ports: - 1337:80 volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media depends_on: - web volumes: postgres_data: pgadmin-data: static_volume: media_volume: How to do it in correct way? I'm running my production application on my domain name. -
Django - Prefetch filter does not work on Many to Many model
I want an endpoint for Group that filters Credits objects on week and year. Group has a Many to Many relation with 'through' arg to Membership. Membership ForeignKey to User. Credits ForeignKey to User. I have the following Models: class Group(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="memberships", through='Membership') class Membership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="membership", on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) class Credits(models.Model): credits = models.IntegerField() year = models.IntegerField(default=date.today().isocalendar()[0]) week = models.IntegerField(default=date.today().isocalendar()[1]) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="credits", on_delete=models.CASCADE) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = NameField(max_length=25, unique=True, is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) My Group view is: class GroupSet(generics.ListAPIView): lookup_field = 'name' serializer_class = GroupSerializer def get_queryset(self): year = self.request.query_params.get('year', None) week = self.request.query_params.get('week', None) name = self.request.query_params.get('name', None) if name and week and year is not None: prefetchCredits = Prefetch('members__credits', queryset=Credits.objects.filter(year=year, week=week)) group = Group.objects.filter(name__iexact=name).prefetch_related(prefetchCredits) return group The filter on Credits doesn't work. I've used this view structure before where the filter on Prefetch does work but the Models did not have a Many to Many relation. I've tried to iterate over prefetchCredits to filter out the correct objects but I get an error: 'Prefetch' object is not iterable -
how to add an authorization check on django template with djoser
before that, my project was working with DRF and Vuejs. For authorization i used Djoser and cheking user authorized or not working by Front page or Backend API. Now add my project new app exam and exam app working with partial DRF partial Django templates. Problem was when i trying get new exam getting error <django.contrib.auth.models.AnonymousUser object at 0x7f395d567cd0>>": "Exam.user" must be a "User" instance although I logged in. Sorry i'm newbie in Django template and don't know how to fix this error exam/models.py class Exam(models.Model): # additional_1 = models.IntegerField() # additional_2 = models.IntegerField() subject_1_variant_id = models.IntegerField() subject_2_variant_id = models.IntegerField() subject_3_variant_id = models.IntegerField() subject_4_variant_id = models.IntegerField() subject_5_variant_id = models.IntegerField() end_time = models.DateTimeField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class SelectedAnswer(models.Model): answer_id = models.IntegerField() is_correct = models.BooleanField() user_id = models.IntegerField() exam_id = models.IntegerField() exam/views.py def new_exam(request): if request.method == "GET": return render(request, "new_exam.html") else: first_additional = request.COOKIES["first_additional"] second_additional = request.COOKIES["second_additional"] exam_bd = new_exam_back(first_additional, second_additional, request.user) return HttpResponseRedirect(f"http://localhost:8000/exam/{exam_bd.id}/") exam/api.py def new_exam_back(first_additional, second_additional, user): now = dt.datetime.now() duration = dt.timedelta(seconds=12600) exams_end = now + duration subjects = [first_additional, second_additional] variants = dict() variants['subject_1_variant_id'] = choice(Variant.objects.filter(subj=ExamSubject.objects.get(id=1))).id variants['subject_2_variant_id'] = choice(Variant.objects.filter(subj=ExamSubject.objects.get(id=2))).id variants['subject_3_variant_id'] = choice(Variant.objects.filter(subj=ExamSubject.objects.get(id=3))).id variants['subject_4_variant_id'] = choice(Variant.objects.filter(subj=ExamSubject.objects.get(id=subjects[0]))).id variants['subject_5_variant_id'] = choice(Variant.objects.filter(subj=ExamSubject.objects.get(id=subjects[1]))).id Exam(**variants, end_time=exams_end, user=user).save() exam = Exam.objects.get(**variants, end_time=exams_end, user=user) … -
Django SQL Windows Function with Group By
I have this MariaDB Query SELECT DAYOFWEEK(date) AS `week_day`, SUM(revenue)/SUM(SUM(revenue)) OVER () AS `rev_share` FROM orders GROUP BY DAYOFWEEK(completed) It will result in a table which show the revenue share. I tried the following by using RawSQL: share = Orders.objects.values(week_day=ExtractIsoWeekDay('date')) \ .annotate(revenue_share=RawSQL('SUM(revenue)/SUM(SUM(revenue)) over ()')) This results in a single value without a group by. The query which is executed: SELECT WEEKDAY(`orders`.`date`) + 1 AS `week_day`, (SUM(revenue)/SUM(SUM(revenue)) over ()) AS `revenue_share` FROM `orders` And also this by using the Window function: share = Orders.objects.values(week_day=ExtractIsoWeekDay('date')) \ .annotate(revenue_share=Sum('revenue')/Window(Sum('revenue'))) Which results into the following query SELECT WEEKDAY(`order`.`date`) + 1 AS `week_day`, (SUM(`order`.`revenue`) / SUM(`order`.`revenue`) OVER ()) AS `rev_share` FROM `order` GROUP BY WEEKDAY(`order`.`date`) + 1 ORDER BY NULL But the data is completely wrong. It looks like the Window is not using the whole table. Thanks for your help in advance. -
ValueError: Number of features of the model must match the input. Model n_features is 25 and input n_features is 76
I am using MLPClassifier to train my model and then will be deploying it in an app/Website.But I am getting this error as the input from user will not be fixed ,using get_dummies is throwing an error.here is my code. Thanks in advance! import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder df = pd.read_csv("nikita_attrition.csv") df_o= pd.read_csv("nikita_attrition.csv") print(df.info()) df=df.drop('StandardHours',axis=1) df_o=df_o.drop('StandardHours',axis=1) features_in = pd.get_dummies(df, columns=['Education','JobSatisfaction', 'WorkLifeBalance', 'EnvironmentSatisfaction', 'StockOptionLevel', 'JobInvolvement', 'PerformanceRating', 'JobLevel'], dummy_na=False) features_out=pd.get_dummies(df_o,columns=['Attrition'],drop_first=True) features_in.shape I am taking input from user via App and coverting it into dataframe and then giving it to my model which is used through pickel file but I am getting the above error. -
Quit Django Celery worker from within task
From within a celery task (ie a Python function) I wish to be able to shutdown the entire celery worker - how can I do this? (Platform us Ubuntu.) -
Django - how to search multiple keywords with "AND" in a list?
Currently I have a list in which there are some keywords. For example: testList = ['apple', 'banana', 'orange'] Now I want to use django Q() to search items which have all the keywords above. Let's say Tom likes apple and orange, but Jerry likes all of these three fruits. When I use this testList, it will return Jerry from the database. Does anyone know how to realize this function? the example model.py is: class FruitInfo(models.Model): Name = models.CharField('Name', max_length=100) Fruits = models.CharField('Favourite fruits', max_length=200) ## here if a person have multiple favourite fruits, the "Fruits" will be "A,B,C" -
null value in column "user_id" violates not-null constraint DRF
I am new to django. I tried to implement registration of several types of users but ran into a problem. I have two models AbstractUser and Participant. Participant is associated with OneToOnefield with AbstractUser, I wrote a serializer for them following the drf documentation, but when sending a post request, an error occurs null value in column "user_id" violates not-null constraint. As far as I understand, the participant model cannot communicate with AbstractUser. What could be the problem Models.py class AbstractUser(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', ) email = models.EmailField(_('email address'), blank=True) created = models.DateTimeField(_('date joined'), default=timezone.now) class Participant(models.Model): user = models.OneToOneField(AbstractUser, related_name='participants', on_delete=models.CASCADE, primary_key=True) first_name = models.CharField( _('first name'), max_length=50 ) last_name = models.CharField( _('last name'), max_length=50, ) device_reg_token = models.TextField( _('text mobile token'), ) is_participant = models.BooleanField( _('participant status'), default=True ) serializers.py class AbstractUserSerializer(serializers.ModelSerializer): class Meta: model = AbstractUser fields = ('id', 'phone_number', 'email', 'password') class ParticipantSerializer(serializers.ModelSerializer): participants = AbstractUserSerializer() class Meta: model = Participant fields = ('participants', 'first_name', 'last_name', 'device_reg_token') def create(self, validated_data): participants_data = validated_data.pop('participants') participant = Participant.objects.create_participant( **validated_data ) for participant_data in participants_data: AbstractUser.objects.create_user(participant=participant, **participant_data) return participant views.py class CreateUserView(generics.CreateAPIView): queryset = Participant.objects.all() permission_classes = [ permissions.AllowAny ] … -
Dynamically set the 'default' DB in Django Project
I am using Postgres DB and I have two databases that I am using. Consider this example as I have to make two version of the software. In one version there is the main DB used for real data and second DB for test version of the software for trainee person. Now how do I change the default DB according to the logged in User. P.S: I know I can use 'using(db_name)'. But I don't want that. I want to change the default DB in settings.py dynamically. The puspose is to provide a test version to the client with a seperate DB. -
How to dynamicaly rename and query a field with Django?
I'm trying to queryset a character field symbol in which values contain a / like in A/B. My problem is that the string AB I would like to query doesn't contains the / and I can't add it because / may be placed at different positions in the string. How can I query AB on the fly when field value is A/B? class Market(models.Model): symbol = models.CharField(max_length=50, null=True, blank=True) What I would like is a dynamic field with the renamed string in it. Something like this but Django complains that the F() object has no attribute 'replace'. Market.objects.annotate(symbol_renamed=F('symbol').replace('/', '')).get(symbol_renamed='AB') -
django modelform: only last form gets into db table
I am building a modelform to let the user enter several rows at once in the db table. I managed to get it all up and running but there is one issue. Only one row gets saved in the database table. here is what my view looks like: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount'), extra=10) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) elif request.method == 'POST': formset = form(request.POST) if formset.is_valid(): formset.save() for check_form in formset: quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) return redirect('/dash2.html') #else: #form = form(queryset= historical_recent_data.objects.none()) return render(request, 'new_sale.html', {'formset':formset}) and here is what my code look like: <form method="POST" class="form-validate"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ …