Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is Firebase and Django possible?
I want to use Firebase database in place of django's default database ( i.e. Sqlite3 ) for production to store all data including authentication and data of each model. If possible please tell me some library to implement it with its docs or code snippet. -
Do we need to write the translations manually when translating django templates?
I am at a point of a project where I have to use Internationalization and for that, I just added trans to the template strings that I want to translate. I also performed "Django-admin.py make messages".Now it just created the .po file where I have to fill my translations into but the question is I have almost 40 strings that need to be translated. Do I have to manually do that? I mean literally just finding out the translation for a string and then copy-pasting that or is there in automation tool I could use? -
How to get fields from Serializer into ListView for filtering
the model in question: class CustomerPrices(models.Model): url = models.OneToOneField('CustomerProductUrls', models.DO_NOTHING, db_column="url", primary_key=True) written = models.DateTimeField() reseller = models.CharField(max_length=250) price = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'customer_prices' unique_together = (('url', 'written', 'reseller'),) the serializer (and one related serializer) in question: class CustomerProductUrlsSerializer(serializers.ModelSerializer): ean = CustomerProductsSerializer() url = serializers.CharField(max_length=255, required=False) class Meta: model = CustomerProductUrls fields = '__all__' class CustomerPricesSerializer(serializers.ModelSerializer): written = serializers.DateTimeField(format='%Y-%m-%d %H:%M:00', required=False) reseller = serializers.CharField(max_length=250, required=False) url = CustomerProductUrlsSerializer() name = serializers.SerializerMethodField('get_name') ean = serializers.SerializerMethodField('get_ean') url = serializers.SerializerMethodField('get_url') price = serializers.FloatField() class Meta: model = CustomerPrices fields = '__all__' def get_name(self, obj): return obj.url.ean.name def get_ean(self, obj): return obj.url.ean.ean def get_url(self, obj): return obj.url.url and the ListAPIView for the CustomerPrices class: class CustomerPricesListView(generics.ListAPIView): serializer_class = CustomerPricesSerializer filter_backends = (DjangoFilterBackend, OrderingFilter) fields = ('written', 'url', 'price') filter_fields = fields search_fields = fields def get_queryset(self): """ This view should return a list of all the products where price >= 70 """ return CustomerPrices.objects.filter(price__gte=70) Inside my CustomerPricesSerializer I've got a field named ean as well as name the values for these two come through the related CustomerProductUrlsSerializer (and corresponding model). The code is working so far, I get a response looking like this: "results": [ { "url": "https://www.example.com/p/12345678", … -
Show numpy array as image in Django
I am new to Django framework. I am building a website that take an image from user, then process the image and return to a numpy array (processed image). I want to show the numpy array as image. How can I do that? Thank you for reading and helps? index.html <form name="image" method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> Index view def index(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): model = MyDeepLearningModel.get_instance() file_name = request.FILES['file'] processed_image = model.run_png(file_name) #processed_image is an numpy array #how to show the processed_image in index.html? return render(request, 'lowlighten/index.html') else: form = UploadFileForm() return render(request, 'lowlighten/index.html', {'form': form}) -
Django: Include Duplicates in id__in query
How can I include duplicates when using an id__in query through an intermediary model? Example: inventory = InventoryItem.active_objects.filter(owner=self) if not inventory: return None return Item.objects.filter(id__in=list(inventory.values_list("item_id", flat=True)) In this example, a user might have 3 of the same InventoryItem (which is the intermediary model), but only one item will be returned from the following queryset. -
Django not applying full CSS to html
I currently have an HTML and CSS file made. Both display the website the way I want it to (picture). Now what I want to do is have a Python script running as well so I setup django. The problem I am currently encountering is that the CSS is only being applied to the button and not the entire index.html I have {% load static %} as well as my settings to include the static folder of the CSS. Can someone explain where I went wrong to not have it apply the CSS to the entire file? It is currently rendering like this decreased the size of the picture so it could be shown. Card wont display properly neither would the background color. HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Card layout</title> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"/> <link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet"> </head> <body> <h1 class="StorySpinner"><u>Story Spinner</u></h1> <main> <section class="cards"> <div class="card"> <div class="card__image-container"> <img src="https://images.unsplash.com/photo-1528561156510-aba26bedef10?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80"/> </div> <div class="card__content"> <p class="card__title text--medium"> Watermelon Bicycle </p> <div class card="card__info"> <button><p class="card__price text--medium">Select</p></button> </div> </div> </div><div class="card"> <div class="card__image-container"> <img src="https://images.unsplash.com/photo-1528561156510-aba26bedef10?ixlib=rb-1.2.1&auto=format&fit=crop&w=1200&q=80"/> </div> <div class="card__content"> <p class="card__title text--medium"> Watermelon Bicycle </p> <div class card="card__info"> … -
Correct if/else statement syntax for django templates
I have a dating app and I need to create a link that is underneath each profile that a user matches on. Then, that link should pass their user id into the template so that messages are only displayed between the current user and that particular user based on the user id. I am having trouble here with the syntax of if/else statements within the Django template. How would I go about doing this? messages.html <div id="msg-list-div" class="panel-body"> <ul id="msg-list" class="list-group"> <br><br><br> {% for obj in messages %} {% if obj.sender == request.user and obj.receiver == profile%} {% if obj.sender == request.user%} <li class="text-right list-group-item">{{obj.message}}<br>{{ obj.date }}<li> {% elif obj.receiver == profile %} <li class="text-left list-group-item">{{obj.message}}<br>{{ obj.date }}<li> {%endif%} {%endif%} {% empty %} <li class="text-right list-group-item">No messages yet...Keep mingling!</li> {% endfor %} </ul> </div> matches.html/ href link for messages.html <p><a href="{% url 'dating_app:messages' profile.id %}">chat</a></p> views.py/messages def messages(request, profile_id): messages = InstantMessage.objects.all() profile = get_object_or_404(Profile,id=profile_id) return render(request, 'dating_app/messages.html', {'messages': messages,'profile':profile,}) models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You … -
djongo with rest_framework_simplejwt.token_blacklist gives create table error
Currently I started a project to learn more of django + jwt and react. Instead of using sql I used mongodb with django instead by using djongo. It works pretty well setting things up, creating new model to test out. So I started looking for django + jwt tutorials and come upon this tutorial https://hackernoon.com/110percent-complete-jwt-authentication-with-django-and-react-2020-iejq34ta Everything works fine up until the end about blacklisting tokens I have my settings.py as suggested SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=14), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } by making the BLACKLIST_AFTER_ROTATION to True, I need to do a migration by python manage.py migrate This is where the error happens, error I got is djongo.sql2mongo.SQLDecodeError: FAILED SQL: CREATE TABLE "token_blacklist_blacklistedtoken" ("id" int32 NOT NULL PRIMARY KEY AUTOINCREMENT, "blacklisted_at" date NOT NULL) I was poking around and couldn't get a solution so I tried changing db back using mysql instead, then the migration worked like a charm. Does anyone know if I do keep using mongodb instead of mysql, is there a workaround for this migration and functionality to work? Thanks in advance for any advices. -
Django: view drop-down-box selection in admin
I have a drop down box as follows: <form action="PageObjects" method="post"> <select name="size"> <option value ="Small">Small</option> <option value ="Medium">Medium</option> <option value ="Large">Large</option> </select> </form> I want to receive the user's input from this selection and collect it in admin.py, such as: class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'size'] How do I save each user's selection? -
Apply filter to nested reverse Foreign Key using queryset
Context I am trying to filter a list of objects based on the value of a reverse foreign key attribute. I was able to solve it at the view level but, but other attempts to solve using ORM feature result in additional queries. The outcome I want to is queryset with all objects, but related fkey objects are filtered inside each object. Sample Models class Student(models.Model): name = models.CharField(max_length=128) class Subject(models.Model): title = models.CharField(max_length=128) class Grade(models.Model): student = models.ForeignKey("Student", related_name="grades", on_delete=models.CASCADE) subject = models.ForeignKey("Subject", related_name="grades", on_delete=models.CASCADE) value = models.IntegerField() Given the Fixtures +------+------------------------+ | name | subject | grade_value | +------+----------+-------------+ | beth | math | 100 | | beth | history | 100 | | beth | science | 100 | | mark | math | 90 | | mark | history | 90 | | mark | science | 90 | | mike | math | 90 | | mike | history | 80 | | mike | science | 80 | +------+----------+-------------+ Desired Outcome Let's say I want to render a list of students, but only include math and history grades. eg. GET students/grades/?subjects=math,history subject might be provided through request or hard coded. not sure yet, but … -
django-tables2 table is not displayed anymore when e-mail form is added
I face a problem that my django-tables2 disappears when I add an e-mail form to my website. I think the problem lies in urls.py but I really can't figure out what is causing the problem (I'm learning django). urls.py urlpatterns = [ path('',PersonListView.as_view()), path('', views.email, name='email'), ] models.py class Person (models.Model): name = models.CharField(max_length=100, verbose_name="full name") views.py class PersonListView(SingleTableView): Person.objects.all().delete() CSV_PATH = 'data/names.csv' with open(CSV_PATH, newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar=',') for row in spamreader: Person.objects.create(name=row[0]) author=row[2]) model = Person table_class = PersonTable template_name = 'blog/people.html' def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['youremail@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, "blog/email.html", {'form': form}) def thanks(request): return HttpResponse('Thank you for your message.') forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) people.html {% extends 'blog/base.html' %} {% load render_table from django_tables2 %} {% block people %} <div> {% render_table table %} </div> {% endblock %} Could anyone help me to figure out how I could get a django-tables2 and an e-mail form on the same main page? Thank you in advance! -
Django - object is not creating after form.save()
In my django application there are some tasks, and users can write solutions or feedbacks. I'm doing this with form.save(), but this feedback object is not creating in database. My views.py codes are like: def task_details(request, slug): if slug: task = get_object_or_404(Task, slug=slug) form = CreateFeedbackForm() if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = CreateFeedbackForm() messages.info(request, 'Feedback uğurla göndərildi.') context = { 'task': task, 'form': form, } return render(request, 'task-details.html', context) What is not correct in my code, help please. -
Django - Cannot assign "2": "Wallet.coin" must be a "Coins" instance
This my code and i see error "Django - Cannot assign "2": "Wallet.coin" must be a "Coins" instance." , please help. I’ve been looking for a reason for 10 hours, I can’t decide. And maybe there are still mistakes? Thanks views.py def load_user_balance(request, wallet_id, imei): try: user = User.objects.get(imei=imei) except ObjectDoesNotExist: create = User.objects.create(imei=imei, wallet_mx=wallet_id) create.save() url_wallet = f"https://explorer-api.minter.network/api/v1/addresses/{wallet_id}" response_wallet=requests.get(url_wallet).json()['data'] for coin in response_wallet['balances']: coin_w = coin['coin'] amount_w = coin['amount'] coin_id_1 = Coins.objects.get(symbol=coin_w) coin_id = coin_id_1.id user_id = User.objects.get(imei=imei) user_id_1 = user_id.id obj, created = Wallet.objects.update_or_create(user_id_id=user_id_1, coin=coin_id, amount_w=amount_w, defaults={'user_id_id': user_id_1, 'coin': coin_id, 'amount_w': amount_w}, ) obj.save() models.py class Coins(models.Model): name = models.CharField(max_length=150) symbol = models.CharField(max_length=45) crr = models.CharField(max_length=3) class User(models.Model): imei = models.CharField(max_length=100) wallet_mx = models.CharField(max_length=50) class Wallet(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) coin = models.ForeignKey(Coins, on_delete=models.CASCADE) amount_w = models.DecimalField(max_digits=19, decimal_places=4) amount_d = models.DecimalField(max_digits=19, decimal_places=4) cap_w = models.DecimalField(max_digits=19, decimal_places=4) cap_d = models.DecimalField(max_digits=19, decimal_places=4) -
Django problem , loss filter data in view
I have a problem. When I send an email in my control view I lost the filter data in this view. I use python Thread to send the mail, but when the thread executes his function, returns a empty filter parameters. Any solutions? In views.py def enviarmail(request,pk): d = Donador.objects.get(pk=pk) subject = 'DONAR SANGRE' message = 'mensaje' email_from=settings.EMAIL_HOST_USER recipient_list=[d.user.email] send_mail(subject,message,email_from,[recipient_list,]) return redirect('lista_donante') def hilo(request, pk): t = Thread(target=enviarmail,args=(request,pk)) t.start() return redirect("lista_donante") class DonadorLista(ListView): model = Donador template_name = 'donante/donante_list.html' queryset = Donador.objects.order_by('-activo') success_url = reverse_lazy('lista_donante') def get_queryset(self): queryset = super(DonadorLista, self).get_queryset() filter1 = self.request.GET.get("grupo") filter2 = self.request.GET.get("factor") if filter1 == 'A' or filter1 == 'B' or filter1 == 'AB' or filter1 == '0': queryset = queryset.filter(grupo_sanguineo=str(filter1)) if filter2 == '+' or filter2 == '-': queryset = queryset.filter(factor_sanguineo=str(filter2)) return queryset -
Accessing values of multiple lists using an index in Django template tags
So I have three list of the same length a, b and c and another list d that are just numbers from 0 to len(a). I want to display the first three lists in an html table. So I wrote: {% for i in d %} <tr> <td>{{a.i}}</td> <td>{{b.i}}</td> <td>{{c.i}}</td> </tr> {% endfor %} For some reason this doesn't work but if change i to any number (like 0) it correctly display the first item of each list in every row. How do I use indexes in template tags to show what I want? -
HTTP code 500 on Django when I try to put a queryset on context
I'm trying to get a queryset on my IndexView on Django, when I try it, I have a HTTP code 500. I checked my template and it's path, and it's ok. Django: 3.0.5 Python 3.8.1 My views.py: from django.shortcuts import render from django.views import generic from .models import * from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from django.core.mail import EmailMessage from datetime import datetime class IndexView(generic.ListView): template_name = "index.html" def get(self, request, **kwargs): domain = get_current_site(request) v = Visits(domain_name=domain, date=datetime.now()) v.save() def get_queryset(self): return Domains.objects.all().only('domain').order_by('domain') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['domains'] = Domains.objects.all().only('domain').order_by('domain') return context When I remove the get_queryset,def_context function and put redenring return, it's works fine. Probably I'm doing something wrong on context and queryset jobs. But, I don't know what. Somebody can help me. Thank you and Stay home! -
ckeditor Youtube plugin.js returns 404 error on not display when extraPlugins add?
youtube plugin installed location is /static/ckeditor/ckeditor/plugins/youtube/youtube/ i get this error when i run that configurations 'extraPlugins': ','.join(['youtube']), if returns "GET /static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=JB9C HTTP/1.1" 404 1863 error and ckeditor is not display models.py from ckeditor_uploader.fields import RichTextUploadingField from django.db import models class Article(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(blank=True) def __str__(self): return self.title settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) CKEDITOR_UPLOAD_PATH = 'article/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'width': 'auto', 'extraPlugins': ','.join(['youtube']), # return "GET /static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=JB9C HTTP/1.1" 404 1863 error and ckeditor is not display 'toolbar': [ ['Bold', 'Italic', 'Underline'], ['Font', 'FontSize', 'TextColor', 'BGColor'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source', 'Image', 'Youtube'] ], } } config.js CKEDITOR.editorConfig = function (config) { config.extraPlugins = 'youtube'; }; -
django get dropdown value on change
in django admin i have a thre models first model have city field from type char second model have feild country from type char every city have many countries third model have person_name field from type char and have field city forgin key and contry field forgin key the problem that is in admin panel when i create person i choose city from cities but it show all countries i want only to show countries for choosen city and on change dropdown change countries not on submit Note i add person from admin not form from html page code example pls -
Getting Attribute error on using icontains
my two model class: class Bank(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Branch(models.Model): ifsc = models.CharField(max_length=200) name = models.CharField(max_length=200) address = models.TextField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=200) bank = models.ForeignKey(Bank, on_delete=models.CASCADE,max_length=200) def __str__(self): return f"{self.name}" serializer classes, class BankSerializer(serializers.ModelSerializer): class Meta: model = Bank fields = '__all__' class BranchSerializer(serializers.ModelSerializer): bank = serializers.CharField(source='bank.name', read_only=True) class Meta: model = Branch fields = ["ifsc","name","address","city","state","bank"] and Views.py class CityBankNameView(APIView): def get_object(self, bank_name, city_name): try: bank = Bank.objects.get(name=bank_name) branches = Branch.objects.filter(bank__icontains=bank, city=city_name) #<-- icontains return branches except: return HttpResponse(status=status.HTTP_404_NOT_FOUND) def get(self,request, bank_name, city_name): branches = self.get_object(bank_name, city_name) serializer = BranchSerializer(branches, many=True) return Response(serializer.data) I am getting attribute error when using bank__icontains exact error: AttributeError at /branches/DELHI/AXIS BANK Got AttributeError when attempting to get a value for field ifsc on serializer BranchSerializer. The serializer field might be named incorrectly and not match any attribute or key on the bytes instance. Original exception text was: 'bytes' object has no attribute 'ifsc'. I am trying for hours but cannot find any solution to it. I seen various answers but none of them helps solve this one -
What should be returned by the view function to display a newly created object instance in DetailView
I'm new to Django. I'm trying to modify this example. What should be retured by the create_book_wiht_authors to the DetailView to display newly created Book with Author? views.py class BookCreateView(CreateView): model = Book form_class = BookModelForm def get_success_url(self): return reverse('store:create_book_with_authors', kwargs={'pk': self.object.pk}) class BookDetailView(DetailView): model = Book context_object_name = 'book' def create_book_with_authors(request, pk): template_name = 'store/create_with_author.html' if request.method == 'GET': bookform = BookModelForm(request.GET or None) formset = AuthorFormset(queryset=Author.objects.none()) elif request.method == 'POST': bookform = BookModelForm(request.POST) formset = AuthorFormset(request.POST) if formset.is_valid(): book = Book.objects.get(pk=pk) for form in formset: author = form.save(commit=False) author.book = book author.save() return redirect(reverse('store:book_detail', kwargs={'pk':book})) return render(request, template_name, { 'bookform': bookform, 'formset': formset, }) This gives me the NoReverseMatch error. -
Cannot import function from mysite.views in Django
mysite is the app name i created in my django project. below is the hierarchy of my app. mysite --- views.py --- tasks.py --- urls.py I have a normal function(there is no request parameter, hence no entry in urls.py as well) in views.py as shown below. def function1(param1,param2): return something I am trying to import this function1 in tasks.py by using from .views import function1 but its throwing an error saying ImportError: cannot import name 'function1' from 'mysite.views' Is there any way to get rid of this error. -
Why is the current user not being passed to my template?
Ok, so I am querying 'messages' and attempting to display 'request.user' messages on the right side of the page and the messages of the user who messaged the request.user on the left side of the page. However, request.user is not being passed to the template and it's displaying ALL the messages on the left side of the page. What am I doing wrong here? Also, I specified a custom user model called Profile for user. views.py/messages def messages(request): messages = InstantMessage.objects.all() return render(request, 'dating_app/messages.html', {'messages': messages}) messages.html <div id="msg-list-div" class="panel-body"> <ul id="msg-list" class="list-group"> {% for obj in messages %} {% if obj.user == request.user %} <li class="text-right list-group-item">{{ obj.message }}</li> {%else%} <li class="text-left list-group-item">{{ obj.message }}</li> {%endif%} {% empty %} <li class="text-right list-group-item">No messages yet...Keep mingling!</li> {% endfor %} </ul> </div> models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), … -
AttributeError: 'str' object has no attribute 'decode' || related to django user creation
*i am getting AttributeError: 'str' object has no attribute 'decode'* from django.utils.http import urlsafe_base64_encode seld.uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()``` -
Django - Multi Model Search
I am working on a search app that queries data from multiple tables. I can search for the fields of the model Post, but when I try to query the username from a user of a post, I get this error: sub-select returns 19 columns - expected 1 This is what I have: class PostQuerySet(models.QuerySet): def search(self, query=None): qs = self if query is not None: profile = UserProfile.objects.select_related('user', 'user__profile') or_lookup = (Q(title__icontains=query) | Q(genre__icontains=query) | Q(user__username__icontains=profile)) qs = qs.filter(or_lookup).distinct() return qs Thank you for any suggestions -
How to save formset data
I try to save a formset data, I have the see() method with slug parameter to get the client contacts, after that, i display the contacts using a formset, but the issue is how to edit and save the displayed data, so how to call the see method again so that the request.POST will be true and i can edit the formset data ?? views.py def see(request,slug): data = dict() print(request.POST) ProductFormSet = modelformset_factory(Contact, fields=('Nom','post','Tel','email','contact_type','client'), extra=0) client = get_object_or_404(Client_Data, slug=slug) attig = request.POST or None formset = ProductFormSet(data=attig, queryset=Contact.objects.filter(client=client)) for form in formset: form.fields['client'].queryset = Contact.objects.filter(client=client.id) if request.method == 'POST': print('hello') print(formset.is_bound) if formset.is_valid(): formset.save() context = {'form': formset} template_name = 'Client_Section/partial_client_contact.html' data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) form.py class Contact_Form(forms.ModelForm): class Meta: model = Contact fields = ('Nom','post','Tel','email','contact_type','client') def __init__(self,*args, **kwargs): super(Contact_Form, self).__init__(*args, **kwargs) self.fields['client'].queryset = Client_Data.objects.all() parital_client_contact.html if i add action="{% url 'see' form.instance.slug %}" i get an error ("NoReverseMatch: Reverse for 'see' with arguments '('',)' not found. 1 pattern(s) tried: ['client/see/(?P[-a-zA-Z0-9_]+)$'] ") <form method="post" class="js-book-create-form"> {% csrf_token %} <div class="modal-body" > {% include 'Client_Section/partial_client_contact_form.html' %} </div> <br><br> <div style="pos"> <button style="float : right" type="submit" class="btn btn-primary ">Update Contacts</button> <button style="float : right" type="button" class="btn btn-default" data-dismiss="modal">Close</button> …