Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Checkout form not being saved
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, proceed to checkout but for some reason, my checkout form is not being saved. I made sure that I have registered my models, and ran migrations, but everytime I fill out my form and go to check in my admin panel, it says: 0 user addresses. Also after clicking the submit button, it's not getting redirected to checkout, rather it's being redirected to: http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=a8vjroAuxAcGFjQmwZ6CdBL5DhYui0vKVnANaoi8lxY33uqjmLXaT90tze6Anyun&address=123+Main+Street%2C+234+Irvine&address2=234+Irvine&state=MA&country=United+States&zipcode=55525&phone=8773140742&billing=on What is the problem? Can anyone please help me out? My views.py: @login_required def checkout(request): if request.method == 'POST': address_form = UserAddressForm(request.POST) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() return redirect(reverse("checkout")) else: address_form = UserAddressForm() context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action=''> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> My urls.py: from orders import views as orders_views path('checkout/', orders_views.checkout, name='checkout'), -
How to addd Content Security policy to heroapp?
I created a Python Heroku app. I want to put Content-Security-Policy to the header. I did some google search, but I still very confused. Some people said to add "headers": { "/**": { "Content-Security-Policy": "default-src 'self'; script-src https://static.ads-twitter.com https://www.google-analytics.com; img-src 'self' https://s3.amazonaws.com https://twitter.com https://pbs.twimg.com; font-src 'self' https://fonts.gstatic.com; style-src 'self' https://fonts.googleapis.com; frame-ancestors 'none';" } } into static.json. However, I don't have this file in my project. How should I link it? Thanks! -
How to correctly use MongoDB client connections
I'm building a simple test web application that stores info users enter in a mongo database. No errors come up, but I always get the following warning (Im using django) when using the client. /home/<User>/.local/share/virtualenvs/<Name>/lib/python3.7/site-packages/pymongo/topology.py:155: UserWarning: MongoClient opened before fork. Create MongoClient only after forking. See PyMongo's documentation for details: http://api.mongodb.org/python/current/faq.html#is-pymongo-fork-safe "MongoClient opened before fork. Create MongoClient only " After checking out the API docs, it seems that the warning pops up when using fork() which im not explicitly using. Maybe something that I'm doing is actually triggering the fork. I create my mongo client at __init__ and then import the variable to my mongoDB handler. Then, that client that I imported is used inserting or updating items in the DB. What is the correct way of creating and then using a mongo client to prevent this warning from appearing? -
Confused by Django Rest Framework Permissions
I have a complex set of permissions that I want to apply to my views, but I'm having a hard time understanding where to put them. Here are my basic permissions. List all projects: If the user is the owner and if their account is active Or if they are a superuser And the object is not private to a different user Or they are a member of the assigned group Problem is that when I add this logic to the permissions classes of the ModelApiViewset, it returns every project. How do I get it to show only the ones that meet the above criteria? To further illustrate the example, I have 2 accounts right now: my superuser, and a test_user. test_user is not an admin or staff account, and is not part of the manager group. The test_user account is an owner of project 2, but not project 1. But if I use the test_user credentials, I see both project 1 and 2: [ { "id": 1, "name": "Test Private Project", "slug": "test-private-project", "description": "Just testing the super private project", "group": { "name": "manager", "id": 1 }, "created_date": "2020-04-20T18:04:20.666564Z", "modified_date": "2020-04-20T18:04:20.666594Z", "owner": { "username": "admin", "full_name_display": "Administrator", "photo": null, … -
Why I cannot update my heroku app via gitlab CI
I have started messing around with Heroku docker and Django. I have followed the instructions of a tutorial and everything works great. My app is on Heroku, but I cannot update my App. According to the tutorial, when I push my new code to Gitlab the pipeline is run and it deploys the new code to my app in Heroku. Although the pipeline passes nothing changes on my Heroku app, what am I doing wrong? Here is my .gitlab-ci.yml: image: docker:stable services: - docker:dind variables: DOCKER_DRIVER: overlay2 HEROKU_APP_NAME: myapp HEROKU_REGISTRY_IMAGE: registry.heroku.com/${HEROKU_APP_NAME}/web stages: - build_and_deploy build_and_deploy: stage: build_and_deploy script: - apk add --no-cache curl - docker login -u _ -p $HEROKU_AUTH_TOKEN registry.heroku.com - docker pull $HEROKU_REGISTRY_IMAGE || true - docker build --cache-from $HEROKU_REGISTRY_IMAGE --tag $HEROKU_REGISTRY_IMAGE --file ./Dockerfile "." - docker push $HEROKU_REGISTRY_IMAGE - chmod +x ./release.sh And this is the release.sh #!/bin/sh IMAGE_ID=$(docker inspect ${HEROKU_REGISTRY_IMAGE} --format={{.Id}}) PAYLOAD='{"updates": [{"type": "web", "docker_image": "'"$IMAGE_ID"'"}]}' curl -n -X PATCH https://api.heroku.com/apps/"${HEROKU_APP_NAME}"/formation \ -d "${PAYLOAD}" \ -H "Content-Type: application/json" \ -H "Accept: application/vnd.heroku+json; version=3.docker-releases" \ -H "Authorization: Bearer ${HEROKU_AUTH_TOKEN}" Last but not least here are the last messages of the pipeline, as I think that the rest of them are irrelevant to my question. Successfully built dbd1d36dea04 … -
Initial value does not appears as selected value in my form?
I have a form and I want to set initial value does not appears as selected PAYS is a list like [(None, ''), (2, 'Ivory coast'), (1, 'France')] self.user_country = 1 I tought it was a problem of field format (charfield in my model) and try to manage with str() but it does not change forms.py class RandomizationEditForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(RandomizationEditForm, self).__init__(*args, **kwargs) self.user_country = request.session.get('user_country') self.language = request.session.get('language') self.user_site_type = request.session.get('user_site_type') PAYS = Pays.options_list(self.user_country,self.user_site_type,self.language) self.fields["pay_ide"] = forms.ChoiceField(label = "Patient's country code", widget=forms.Select, choices=PAYS, initial = self.user_country, disabled=True) self.fields["ran_dem_dat"] = forms.DateField( label = "Date of demand", initial = timezone.now(), required = True, ) self.fields['ran_dem_dat'].widget.attrs.update({ 'autocomplete': 'off' }) class Meta: model = Randomisation fields = ('pay_ide','ran_str_num','ran_bra','bra_lib','ran_act','pat','ran_nai','ran_sex','ran_st1','ran_st2','ran_bug','ran_dem_nom','ran_dem_dat',) models.py class Pays(SafeDeleteModel): """ A class to create a country site instance. """ _safedelete_policy = SOFT_DELETE_CASCADE pay_ide = models.AutoField("Code number", primary_key = True) pay_nom_eng = models.CharField("Nom", max_length = 150) pay_nom_fra = models.CharField("Nom", max_length = 150) pay_abr = models.CharField("Code lettre", max_length = 3) pay_ran = models.IntegerField("Randomization opened in the country? (y/n)",default=0, null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'adm_pay' verbose_name_plural = 'Pays' ordering = ['pay_nom_fra', 'pay_ide'] permissions = [ ('can_manage_randomization','Can activate randomization'), ] @classmethod def options_list(cls,pays,type,language): if type == 'International' or … -
django radio button on request.POST is not working
i am trying to read the value from the radio.input in the form below using def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk = quiz_id) que = Question.objects.get(pk = question_id) count = q.question_set.count() try: selected_choice = que.answer_set.get(pk=request.POST['choice']) except(KeyError, Answer.DoesNotExist): come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) return render(request, 'app/question_detail.html',{'que': que, 'count': count, 'later_question': later_question}) else: if selected_choice.correct is True: try: come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) except: come = que.rank came = come later_question = q.question_set.get(rank=came) else: come = que.rank later_question = q.question_set.get(rank=come) return render(request, 'app/question_detail.html',{'count': count, 'que': que, 'later_question': later_question}) but when i try to access the webpage,it throws an Keyerror,please help <form action="{% url 'app:detail' quiz_id=que.quiz.id question_id=later_question.id%}" method="post">{% csrf_token%} {% for choice in que.answer_set.all %} <input type="radio" name='choice' value="{{choice.id}}"> <label>{{choice.answer}}-{{choice.correct}}-{{choice.rank}}</label><br> {% endfor %} -
How to unpack dictionary into models.TextChoices atributes in Django models?
Here is new option in Django 3.0 for choices in models by using ENUM library: https://docs.djangoproject.com/en/3.0/ref/models/fields/#enumeration-types I have been trying to use it to create countries choices for AbstractUser model: class User(AbstractUser): """ Custom user model based on AbstractUser model. """ class Countries_ISO3166(models.TextChoices): # This code should run when class is initialized. Instead of cls should be class object for country_code, country_name in countries.COUNTRIES_DICT.items(): setattr(cls, country_name, country_code) username = None email = models.EmailField(verbose_name='email address', unique=True) first_name = models.CharField(null=True, blank=False, max_length=30, verbose_name='first name') last_name = models.CharField(null=True, blank=False, max_length=150, verbose_name='last name') user_country = models.CharField(max_length=2, choices=Countries_ISO3166.choices, null=True, verbose_name='user country of origin') USERNAME_FIELD = 'email' # https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS REQUIRED_FIELDS = [] #default_manager = BaseUserManager() objects = users_managers.CustomUserManager() class Meta: unique_together = ( ('first_name', 'last_name', ), ) index_together = unique_together verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return f'pk - {self.pk}, full name - {self.get_full_name()}, email - {self.email}' Problem is I dont know how to unpack countries dictionary in order to create Countries_ISO3166 class atributes like in Django documentation example. I have tried to do it in init, new but it doesn't work. COUNTRIES_DICT is a counties dict according ISO3166 format: COUNTRIES_DICT = { "AF": "Afghanistan", "AX": "Åland Islands", "AL": "Albania", "DZ": "Algeria", "AS": "American … -
Update foreign key related table field while inserting new record in first table django
I have two tables Table Tour class Tour(BaseModel): statuses = [ ('DRAFT', 'Draft'), ('ACTIVE', 'Active'), ('PAID', 'Paid'), ('COMPLETED', 'Completed') ] status = models.CharField(max_length= 100, choices=statuses, default="DRAFT") Table Billing class Billing(BaseModel): tour=models.ForeignKey(Tour, on_delete=models.PROTECT) total=models.FloatField(null=True) views.py class BillingViewSet(viewsets.ModelViewSet): queryset = Billing.objects.all() serializer_class=Billlingerializer serializers.py class Billlingerializer(serializers.ModelSerializer): class Meta: model = Billing fields ='__all__' whenever a new record is added to Billing table we need to change status to PAID in Tour table, I have other tables too, which is like Billing if any record is added there also need to change the status to complete or active etc.So we need common method that is defined in Tour model which can be called from serialiazers or views .Please help me, thanks in advance. -
Fetch rows field = true by BooleanFilter
I am making very simple booleanfilter I have model which has boolean column named 'is_show'. I want to fetch the items is_show is true. I accessAPI like this /api/items?is_show=true class Text(models.Model): is_show = models.BooleanField() class TextFilter(filters.FilterSet): is_show = filters.BooleanFilter(is_show=True) However it still returns all rows. -
Django HTML templates can't load CSS files
In my Django project I added a new 404 page, that gets called when I enter an invalid url. But, the CSS file is not loaded with page, so it appears mis-formatted. The browser gives me this error: "Refused to apply style from because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." The point is, There are other CSS files in the 'static' folder that are loaded correctly without this error, like the bootstrap.css file... My settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] My urls.py urlpatterns = [ ... ] handler400 = 'utils.views.error_400' handler403 = 'utils.views.error_403' handler404 = 'utils.views.error_404' handler500 = 'utils.views.error_500' My utils.views.py def error_400(request, exception): data = {} return render(request, 'utils/mv_admin_400.html', data) def error_403(request, exception): data = {} return render(request, 'utils/mv_admin_403.html', data) def error_404(request, exception): data = {} return render(request, 'utils/mv_admin_404.html', data) def error_500(request): data = {} return render(request, 'utils/mv_admin_500.html', data) My 404.html {% load static %} <!DOCTYPE html> … -
Delete model objects involved in ManyToMany relationships in postgres
I am using postgres and have two very simple models in Django: class VariantTag(ModelWithGUID): saved_variants = models.ManyToManyField('SavedVariant') class SavedVariant(ModelWithGUID): xpos_start = models.BigIntegerField() xpos_end = models.BigIntegerField(null=True) Now, I want to delete SavedVariant but getting an error Key (id)=(24) is still referenced from table "seqr_varianttag_saved_variants". How to correctly delete SavedVariant objects in this case? In dbshell I mean, in postgres using SQL. -
Different time intervals creations
I have datetime objects for start_time and end_time. Both of these from user comes in 24 hours. for eg: 14:00hrs and 16:00hrs. I have an interval of 12 minutes per hour. dateTimeA = datetime.datetime.strptime(start_time, '%H:%M') dateTimeB = datetime.datetime.strptime(end_time, '%H:%M') I need to create slots in the following manner: Diff_in_time = dateTimeB - dateTimeA diff_in_hours = Diff_in_hours.total_seconds() / 3600 So, diff_in_hours gives me a time difference in hours. Here, diff_in_hours = 2.0 Now, the slots to be created should be. slots_interval = 60/12(interval) = 5 slots/hour with interval of 12 minutes. 14:00 - 14:12 14:12 - 14:24 14:24 - 14:36 14:36 - 14:48 14:48 - 15:00 15:00 - 15:12 15:12 - 15:24 15:24 - 15:36 15:36 - 15:48 15:48 - 16:00 Total slots = 10 However, I am unable to perform this operation. I need to keep a tally of both from_time and end_time here to create slots. Can anyone suggest some help? -
how to check whether user after login has submitted the form one , if yes again if he login he should redirect to form 2 not one again in django
I have an app where user login and after he logins he get redirect to dashboard where appears a form and user fill the form , once user fill the form he redirect to next page where it shows the progress of the form. So if user login again he should automatically redirect to the progress page he should not get the form page again if he has filled it . Can any one suggest me how to achieve these. views.py def create(request): if request.method == 'POST': post = AccountProfile() post.user = request.user post.name = request.POST['name'] post.email = request.POST['email'] post.mobile = request.POST['mobile'] post.date = request.POST['date'] post.sex = request.POST['sex'] post.save() return render (request,'posts/dashboard-post-a-job.html') These is the views where user get redirect after login and fill form. -
Custom user model - 'Group' object has no attribute 'user_set'
I am fairly new to Django and set up a custom user model with token authentication. Now I am trying to add the possibility of adding users to user groups from the backend in order to specify permissions. However, I dont seem to be able to get past this error. I am using Python 3.7 and Django 2.2.6. Appreciate your help! The error: File "/Users/.../Dev/.../account/models.py", line 114, in save_m2m self.instance.user_set.set(self.cleaned_data['users']) AttributeError: 'Group' object has no attribute 'user_set' my models.py: from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django import forms from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.admin.widgets import FilteredSelectMultiple from django.contrib.auth.models import Group class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") user = self.model( email=self.normalize_email(email), username=username, ) group = Group.objects.all() group.user_set.add(user) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined … -
Form coming back with <django.db.models.query_utils.DeferredAttribute object at 0x044C5C28>
Newbie here. I tried to create a Todo app.When I try to display this object as a form , form fields displays some gibberish like "django.db.models.query_utils.DeferredAttribute object at 0x04455C28" inside the textbox. This is my form how looks like views def viewtodo(request,todo_pk): todo=get_object_or_404(Getitdone,pk=todo_pk,user=request.user) if(request.method=='GET'): form=GetitdoneForm(instance=Getitdone) return render(request,'viewtodo.html',{'todo':todo,'form':form}) else: try: form=GetitdoneForm(request.POST,instance=Getitdone) form.save() return redirect('currenttodos') except ValueError: return render(request,'viewtodo.html',{'todo':todo,'form':form,'error':'bad value passed in'}) Template {{ error }} {{ todo.title }} <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">save</button> </form> forms.py from django.forms import ModelForm from .models import Getitdone class GetitdoneForm(ModelForm): class Meta: model=Getitdone fields=['title','memo','important',] -
No formatting supported by TextField in django admin panel
I have Post model and have it registered in admin. It has description of TextField() but while adding new post from admin panel, description area does not support newline or <br> or any kind of formatting. I have no usage of forms and only way to add post is through admin panel. -
i need to get 40 boxes in django output but i am getting only 2 boxes
from django.shortcuts import render import random Create your views here. def home(request): l=[] for i in str(random.randint(1,40)): l.append(i) return render(request, 'check/web.html', {'list':l} ) templates: {% for i in list %} {{i}} {% endfor %} I am getting only two boxes instead of 40 boxes -
how can i pass Form values to particle.io
Im using django,raspberry pi3, particle.io,relay I want to pass on\off value from Form to particle.io so that i can control lightbulb. <form action="https://api.particle.io/v1/devices/{{value1}}/relay?access_token={{value2}}" method="POST"> The code given above works perfectly fine but when i try to apply the same thing for a pop-up window , Particle.io is not able to receive the value on\off. The code is given below {% if user.is_authenticated %} <div class = "container"> <div class="wrapper"> <form action="javascript:my_c()" class="form-signin" method="POST"> <hr class="colorgraph"> <br> <p style="color:black; font-family:helvetica; font-size:20px;">Welcome to your home automation system.</p><br> <br> <h style="color:black; font-family:helvetica;">Greetings {{request.user.get_short_name}} </h><br> {% for Profile in UserD|slice:":1" %} <h style="color:black; font-family:helvetica;">Access {{value1}} </h><br> <h style="color:black; font-family:helvetica;">Device ID {{value2}} </h><br> <p style="color:black; font-family:helvetica; font-size:20px;">Tell your device what to do!</p> <center> <div id="donate"> <a style="color:black; font-family:helvetica; font-size:15px;">Lights:</a> <label class="green"><input type="radio" name="arg" value="on"><span>ON</span></label> <label class="red"><input type="radio" name="arg" value="off"><span>OFF</span></label> </div> </center> <center> <input class="btn btn-primary btn-xl js-scroll-trigger" type="submit" value="Do it!"> </center> <br> <br> <script type="text/javascript"> function my_c(){ var win = window.open('https://api.particle.io/v1/devices/{{value1}}/relay?access_token={{value2}}', '1366002941508','width=500,height=200,left=375,top=330'); setTimeout(function () { win.close();}, 6000); } </script> </form> {% endfor %} also is there anyway the instead of using setTimeout(function () { win.close();}, 6000); this , the window is closed automatically closed once the site is fully loaded eg. using onload or something … -
Delete 'Server' response header in Django framework - V3.0.5
Before I begin my question, I have referred the stackoverflow post - Delete header in django rest framework response. Please find the middleware code and settings.py below (referred to the django middleware docs): middleware.py: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) response.__setitem__('Server', '') return response settings.py MIDDLEWARE = [ ...., ...., 'middleware_demo.middleware.SimpleMiddleware', ] With the above code, I get the server response with the server header set to empty string as below. Which is as expected and doesn't disclose the server header details: HTTP/1.1 200 OK Date: Tue, 21 Apr 2020 12:55:25 GMT Content-Type: text/html Server: X-Frame-Options: DENY Content-Length: 16351 X-Content-Type-Options: nosniff My goal is to remove the header altogether and tried 2 ways for the same in middleware.py: Method 1 - official docs class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) response.__delitem__('Server') return response Method 2 - referred stackoverflow blog - Delete header in django rest framework response class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) del response['Server'] return response But the response still has … -
Django don't render if regex match?
I have pseudo coded what I would like but cant see anything in the docs for using if statements alongside a regex? Any help is appreciated. <!-- if window.name includes Before|After dont render--> {{window.event_id}}-{{window.name}} <!-- end if --> the regex is easy: /(Before|After)/g -
How to reflect changes on both One-To-Many-Relationship instances when updating one of them at once in Django?
I have two tables connected with a Foreignkey. I have a field in the main model, its value depends on the child instances. For example, if I have a Library model and a Book model, Book has Foriegnkey to Library. And we have a field in the Library model which is equal to the "total_price" of all the books in the library. How I can update that field "total_price" whenever I increase the quantity of a certain book or decrease it. Note that I have to save each instance separately in order to get the value right. I have the Books as a TabularInline inside Library, so I make the change to the quantity and save the changes, and then I have to press save one more time to change the "total_price" field. -
Show month name instead of month number in django model choice field
Column acct_per_num in table SAPAdjustment contains the month number. The following code gives a dropdown with month number (1,2,3) but I want month name (January, February, March) instead. forms.py class SAPReconForm(forms.Form): month = forms.ModelChoiceField(queryset=SAPAdjustment.objects.values_list('acct_per_num',flat=True).distinct(), empty_label=None) models.py class SAPAdjustment(models.Model): acct_per_num = models.IntegerField( blank=True,null=True, verbose_name =_('Month'),help_text=_('Month')) -
How can we return multiple SQL table in a single postgre function?
How can we return multiple SQL table in a single postgre function I want something like this: postgrefuction('some parameters') RETURNS refcursor ... ... ... AS $BODY$ DECLARE ... ... ... BEGIN SQL:='some queries'; SQL2:= 'some queries'; RETURN SQL,SQL2 $BODY$ -
Model Formset showing error wen updating my form
The form is creating perfectly but when I am trying to update the form the model formset is not updating as it is showing the data but wen when i change the data and submit it the lecture_content fliefield is showing empty.`def content_edit_view(request, id): course = get_object_or_404(Course, id=id) LectureFormset = modelformset_factory(Lecture, fields=('lecture_title', 'lecture_content'), extra=0) if course.user != request.user: raise Http404() if request.method == 'POST': content_edit_form = ContentEditForm(request.POST or None, request.FILES or None, instance=course) formset = LectureFormset(request.POST or None, request.FILES or None) if content_edit_form.is_valid() and formset.is_valid(): content_edit_form.save() print('course is saved') data = Lecture.objects.filter(post=post) # give index of the item for a formset item strting form 0 and (f)the item itself for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content')) video.save() else: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content')) d = Lecture.objects.get(id=data[index].id) #get slide id which was uploaded d.lecture_title = video.lecture_title, # changing the database tiitle with new title d.lecture_content = video.lecture_content # changing the database content with new content d.save() return redirect('teacher-profile') else: print("form invalid") else: content_edit_form = ContentAddForm(instance=course) formset = LectureFormset(queryset=Lecture.objects.filter(course=course)) context = { 'contentForm': content_edit_form, 'course': course, 'formset': formset, } return render(request, 'apps/contentAdd.html', context) `