Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template Does Not Exist at / cms_wizard /create/ INHERIT
The issue > https://i.stack.imgur.com/0mbDr.png Here is one solution I tried: "os.path.join(SETTINGS_PATH, 'templates'), "(I substituted SETTINGS_PATH with BASE_DIR, and the setting.py terminated without any errors but still the problem isn't solved. how am I supposed to inherit the template, it has to be in a folder which I should make? also, the directory of cms_wizard/create isn't making sense as shown in the image above how do I fix it. Here is my setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'sekizai.context_processors.sekizai', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'cms.context_processors.cms_settings', 'django.template.context_processors.i18n', ], }, }, ] -
Django makemigrations models conflict apps extensions
I'm trying to extend 2 apps in django. While I'm trying to apply manage.py makemigrations I'm recieving the following error: File "Desktop\ipam\ipam_extension\openwisp_ipam_extension\models.py", line 3, in <module> from openwisp_ipam.base.models import AbstractIpAddress, AbstractSubnet File "Desktop\ipam\venv\lib\site-packages\openwisp_ipam\base\models .py", line 10, in <module> from openwisp_users.models import Organization File "Desktop\ipam\venv\lib\site-packages\openwisp_users\models.py" , line 18, in <module> class User(AbstractUser): File "Desktop\ipam\venv\lib\site-packages\django\db\models\base.py" , line 113, in __new__ raise RuntimeError( RuntimeError: Model class openwisp_users.models.User doesn't declare an explicit app_label and isn't in an application in INSTA LLED_APPS. My 2 apps are: openwisp_users_extension extends openwisp_users openwisp_ipam_extension extends openwisp_ipam The problem is probebly that in openwisp_ipam_extension.models I have this line: from openwisp_ipam.base.models import AbstractIpAddress, AbstractSubnet Which internally using openwisp_users extended app. I assume this conflict shouldn't happend because I saw it is possible to extend both apps together -
django oauth2 Session value state missing error
there is my social auth setting and it works correctly in local-host but on server it returns session value state missing error. i have tested similar questions in stack overflow but the answers didn't solved my problem. SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = '' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = '' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/' SOCIAL_AUTH_LOGIN_URL = '/' SOCIAL_AUTH_REDIRECT_IS_HTTPS = True LOGIN_URL = '/auth/login/google-oauth2/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SOCIAL_AUTH_FIELDS_STORED_IN_SESSION = ['state'] SESSION_COOKIE_SECURE = False AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) white_list = ['http://localhost:8000/accounts/profile'] DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': white_list, 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy', 'SERIALIZERS': {}, } SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
Order by nested objects date
I am building a chat application and have the following models representing the chat room, chat message and the counter of unread messages class ChatRoom(BaseModel): name = models.CharField(max_length=255, default='', blank=True) participants = models.ManyToManyField('accounts.User', related_name='chat_rooms') class ChatMessage(BaseModel): text = models.TextField(default='', blank=True) owner = models.ForeignKey('accounts.User', on_delete=models.CASCADE) room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='messages') class ChatRoomUnreadMessagesCounter(BaseModel): room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='unread_counters') owner = models.ForeignKey('accounts.User', on_delete=models.CASCADE) messages_count = models.IntegerField(default=0) class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False) class Meta: abstract = True I would like to make an API view that would return a list of ChatRoom objects that are ordered in the following manner: ChatRoom objects that have unread messages ordered by messages count -> ChatRoom objects that have messages in them by the latest message created_at last in first out -> ChatRoom objects that are sorted alphabetically. How would I construct my queryset properly? Here's an expected result output | Room Name | Unread Messages | Last Message | | Rean | 2 | 09.11.2021T12:00:00 | | Ash | 1 | 09.11.2021T12:00:24 | | Altina | 0 | 09.11.2021T12:15:00 | | Juna | 0 | 09.11.2021T12:14:00 | | Kurt | 0 | 09.11.2021T12:13:00 | | Musse | 0 | 09.11.2021T12:12:00 | … -
Django send multiple responses
Disclaimer: New to Django, don't know all the advanced stuff here so may be quoting my question in a misleading way. I have set up a Django web server that does some numerical calculation with some network data on the server-side and returns the data to the client. Now, the tasks requested by users have multiple results and they are generated sequentially. For now what I'm doing (1) User send a task request from frontend---> (2) calculation is done in the backend sequentially and all the result is generated ---> (3) django sends all the result in a single response to the frontend to update the result. Now the 2nd step that is the calculation part takes a lot of time about 1-2 seconds which spoils the user experience on the client-side. As multiple results are generated sequentially, I can show the result one by one to the client as they are generated. But I can't understand how can I send multiple responses against a single client request. I guess this is not possible with HTTP? Can anyone help me how do I tackle this problem? Is it possible to that? -
Django searching multiple models and removing duplicates
I am trying to build a search function for my blog that searches through the two models Articles and Spots. The two models are connected via the pivot table ArticleSpots. My blog is structured so that there are multiple spots in each article. When a query is searched I want the query to be searched within both models but only display clickable articles. I have a html page for each article but not for each spots, so all the spots that resulted from the search have to be shown as the article which contains the spot. Hope that makes sense! This is the code that I came up with but the problem is that I get a lot of duplicates in the variable results. There are duplicates within each articles_from_spots and articles_from_query, and there are also overlaps between them. Is this the right way to accomplish this ? How can I remove the duplicates from the results? Any help would be appreciated! views.py def search(request): query = request.GET.get("q") articles_from_query = Articles.objects.filter( Q(title__icontains=query) | Q(summary__icontains=query) ) spots_from_query = Spots.objects.filter( Q(title__icontains=query) | Q(summary__icontains=query) | Q(content__icontains=query) ) articles_from_spots = [] for x in spots_from_query: article = Articles.objects.filter(articlespots__spot=x) articles_from_spots.extend(article) results = chain(articles_from_spots, articles_from_query) context … -
Django: custom storage system with incremental number
I'm trying to creare a custom storage file system in python to have the duplicate files that are uploaded to be different by a number that increment. The code is kinda working, my only problem is that instead having this kind of results: nameofthefile_1.txt nameofthefile_2.txt nameofthefile_3.txt I get this nameofthefile_1.txt nameofthefile_1_2.txt nameofthefile_1_2_2.txt This is my code class CustomStorage(FileSystemStorage): def get_available_name(self, filename, max_length=None): number_1 = filename.split('_')[19] plus_one = int(number_1.split('.')[0]) if self.exists(filename): plus_one += 1 dir_name, file_name = os.path.split(filename) file_root, file_ext = os.path.splitext(file_name) filename = os.path.join(dir_name, '{}_{}{}'.format(file_root, plus_one, file_ext)) return filename def user_directory_path(instance, filename): extension = filename.split('.')[-1] filename = "file_%s_1.%s" % (instance.identification, extension) return 'folder/{0}/{1}'.format(instance.user, filename) -
Adding a panel black behind a form
I currently have a form in my app that looks like this: However I would like to add a white panel behind the form, the panel must still show the background behind it When I use the <div class="panel panel-default" style="color: white "> it does not add this Does anyone know how I can add this with HTML / CSS Please see the below code for assistance: {% extends "main/base.html"%} {% block content %} <div class="opacity-50"> <body id="bg" style="background-size: cover; background-repeat: no-repeat;background-image: url('https://images.unsplash.com/photo-1518334792104-db78a16ac8b8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80')";> </body> </div> <div class="panel panel-default" style="color: white "> <from> <div style="text-align: center"> <h1>Sign Up with Shiftly</h1> <p>Please complete the form below carefully, ensure you provide the correct information and documents to avoid your application being delayed.</p> </div> <h2 style="text-align: left; padding-left: 250px">PERSONAL INFORMATION</h2> <br> <div style="text-align: Left; padding-left: 255px"> <div class="row mb-2" style="width: 100%"> <div class="col-6 col-sm-2"> Title {{ form.title }}</div> <div class="col-6 col-sm-3"> Initials {{ form.initials }} </div> <div class="col-6 col-sm-3"> First Name(s) {{ form.firstname }} </div> <div class="col-6 col-sm-3"> Surname {{ form.surname }} </div> </div> <div class="row mb-2" style="width: 100%"> <div class="col-6 col-sm-3"> Preferred Name {{ form.prefferedname }}</div> <div class="col-6 col-sm-2"> Gender {{ form.gender }} </div> <div class="col-6 col-sm-3"> Date Of Birth{{ form.dob }} </div> … -
How can gunicorn handle hundreds of thousands of requests per second for django?
From the docs - How many workers, DO NOT scale the number of workers to the number of clients you expect to have. Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second. Generally we recommend (2 x $num_cores) + 1 as the number of workers to start off with. From threads, The number of worker threads for handling requests. Run each worker with the specified number of threads. A positive integer generally in the 2-4 x $(NUM_CORES) range. You’ll want to vary this a bit to find the best for your particular application’s workload. Now the question is what no of threads and workers can serve hundreds or thousands of requests per second? Let's say I have a dual-core machine and I set 5 workers and 8 threads. And I can serve 40 concurrent requests? If I am going to serve hundreds or thousands of requests, I'll need a hundred cores? this line is very hard to understand: Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second. -
Filter products using Category Model in Django
I'm building an ecommerce website and want to filter products using categories but I don't know how to render the products. And add the categories in the navigation bar from where people can navigate to different categories. Here's my views.py file: from django.shortcuts import render from django.views import View from .models import Product, Category class ProductView(View): def get(self, request, *args, **kwargs): products = Product.objects.filter(is_active = True) context = { 'products': products, } return render(request, 'Product/products.html', context) class ProductDetailView(View): def get(self, request, slug): product = Product.objects.get(slug = slug) context = { 'product': product } return render(request, 'Product/productdetail.html', context) class CategoryView(View): def get(self, request): category = Category.objects.all() products = Product.objects.filter(category__slug = slug) context = { 'category': category, 'products':products, } return render(request, 'Product/category.html', context) And this is my models.py from django.db import models from Seller.models import Seller class Category(models.Model): category = models.CharField(max_length = 255) slug = models.SlugField(max_length = 255) def __str__(self): return self.category class Product(models.Model): product = models.ForeignKey(Seller, on_delete = models.CASCADE) title = models.CharField(max_length = 255) image = models.ImageField(upload_to = 'images', null = True, blank = True) file = models.FileField(upload_to = 'files', null = True, blank = True) actual_price = models.PositiveIntegerField(default = '0') selling_price = models.PositiveIntegerField(default = '0') slug = models.SlugField(max_length = 255, … -
How to keep a property value in django.values()?
I have my model as: .... created_at = models.DateTimeField(auto_now_add=True, db_column="order_date", null=True, blank=True) @property def created_date(self): return self.created_at.strftime('%B %d %Y') I want to get created_Date in my views.py data = Subs.objects.values('somevalues','created_date') It throws an error. How to access created_date so that i can use it here. -
Django model allow only once in many
Please excuse the title but I'm not sure howto put this into words. I have a model "card" and a model "computer": class card(models.Model): name=models.CharField( verbose_name = 'Name', max_length=50, null=True, blank=True, ) serial=models.CharField( verbose_name = 'Serial', max_length=50, null=True, blank=True, ) class computer(models.Model): name=models.CharField( verbose_name = 'Name', max_length=50, null=True, blank=True, ) slot1 = models.OneToOneField( 'card', related_name='cardslot1', on_delete=models.SET_NULL, null=True, blank=True, verbose_name = 'Slot 1', ) slot2 = models.OneToOneField( 'card', related_name='cardslot2', on_delete=models.SET_NULL, null=True, blank=True, verbose_name = 'Slot 2', ) (Of course that this computer model is invalid) The cards are unique and should only be allowed to be used in one slot - of any computer. What's the best way to achieve this? I was thinking about a in-between table, something like card n-1 cardcomputer n-1 computer but I'm hoping there's a better way I'm not seeing right now. Thanks -
Override User's check password in Django
I am migrating a PHP backend to Django and I don't wanna make users change their passwords. In PHP I'm using Bcrypt, which uses version 2y, while Django uses 2b, making it incompatible. I've read other solutions where people write a whole new hasher, but that seems too difficult. My solution was to override the check_password() function of my User model: def check_password(self, raw_password): alg_prefix = 'bcrypt_php' if self.password.startswith(alg_prefix): return bcrypt.checkpw(bytes(raw_password, 'utf-8'), bytes(self.password[len(alg_prefix):], 'utf-8')) else: return super().check_password(raw_password) And to save old passwords adding bcrypt_php in the beginning. The question is: Is it dangerous to do this? Am I putting my passwords or my system in danger? -
DRF Can't get data for restricted URLs
I'm using simple_JWT and I have a view that requires logged-in users. When I try to send a request (tested with postman, curl, ...) I get 'Authentication credentials were not provided'. views.py : class CurrencyDetailAPIView(generics.RetrieveAPIView): serializer_class = CurrencyDetailSerializer lookup_field = "slug" permission_classes = [IsAuthenticated] settings.py : REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ], } -
× Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'access')
I'm using react and redux to create simple user authentication. When I click on the login button the user get's authenticated, yet the user remails null. Below is the code for auth action and reducer Auth Acction _____________ import axios from 'axios'; import { LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED_SUCCESS, USER_LOADED_FAIL,} from './types'; export const load_user = () => async dispatch =>{ if(localStorage.getItem('access')){ const config = { headers: { 'Content-Type':'application/json', 'Authorization': `JWT ${localStorage.getItem('access')}`, 'Accept': 'application/json' } }; try{ const res = await axios.post(`${process.env.REACT_APP_API_URL}/account/login`, config) dispatch({ type: USER_LOADED_SUCCESS, payload: res.data }) } catch (err){ dispatch({ type: USER_LOADED_FAIL, }) } }else { dispatch({ type: USER_LOADED_FAIL, }) } }; export const login = (email, password) => async dispatch => { const config = { headers: { 'Content-Type':'application/json' } }; //const body = JSON.stringify({email, password}); const body = {email, password}; const data = JSON.stringify(body); try{ console.log(data) const res = await axios.post(`${process.env.REACT_APP_API_URL}/account/login`, data, config) dispatch({ type: LOGIN_SUCCESS, payload: res.data }) dispatch(load_user()); } catch (err){ dispatch({ type: LOGIN_FAIL, }) } } Auth Reducer import { LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED_SUCCESS, USER_LOADED_FAIL,} from '../actions/types' const initialState = { access: localStorage.getItem('access'), refresh: localStorage.getItem('refresh'), isAuthenticated: null, user: null }; const authReducer = (state = initialState, action) => { const { type, payload } = … -
How to specify camera capture in input tag using Django?
I'm currently developing an application using Django. I want to open up camera capture directly when specified as follows in HTML5 tag using Django. <input type="file" accept="image/*" capture="camera"/> In this case, how can I make a field in a model? Thanks in advance. Django 3.2.9 -
django queryset values() to string or json
I'm trying to convert my dict to a list of string. this is what generated by django froms list of student I want to have a list without the {''} My forms : students= ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple( attrs={'class': 'displaynone'}), queryset=Student.objects.exclude(present=True).order_by( 'name').values('name'), required=False, label="Choice Students" ) and template {% for i in form.students %} {{ i }} {% endfor %} and I know I can juste do queryset=Student.objects.exclude(present=True).order_by('name') without the values() but I juste want to retreive the name. It will optimize the load of my page. -
Django system always logged user A out when user B logged in
I developed an lite web system with django2.2. When i deployed the project on a server,it ran well when only one user using the web system. while another user(not the same user)logged in the system,the previous one was logged out immediately. The settings about the session in the setting.py file is like below: SESSION_COOKIE_AGE = 518400 SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_SAVE_EVERY_REQUEST = True SESSION_ENGINE = 'django.contrib.sessions.backends.db' Currently, I have no ideas about the issues.Thanks in advance if anybody could help. -
Unable to send data to database in Django
I am an absolute beginner in Django development & I am unable to send the data to my database via the POST method. Please guide me on what is wrong with my approach. My model worked perfectly and I can now access my desired table on my Django admin. The function that I have created in views.py always executes the else condition. From views.py: from django.shortcuts import render, HttpResponse, redirect from app.models import Tbl_Feedback def myform(request): return render(request, 'form.html') def getfeedback(request): if request == "POST": a = request.POST.get('a') objTbl_Feedback = Tbl_Feedback(a="a") objTbl_Feedback.save() return redirect("/") else: return HttpResponse('Form Not Submitted') From models.py: from django.db import models # Create your models here. class Tbl_Feedback(models.Model): fdbk = models.CharField(max_length=120) From urls.py(app): from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('',views.myform,name="form"), path('getfeedback', views.getfeedback, name="feedback") ] From urls.py(project): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include("app.urls")) ] Html: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form</title> {% load static %} <link rel="stylesheet" href="{%static 'css.css'%}"> </head> <body> <form action="getfeedback" method="post" > {% csrf_token %} <div class="frame"> <div class="frame-header">FeedBack Please !</div> <div … -
saving foreign key relations using DRF
I am trying to save foreign key relations using serializer , i don't know where i am wrong here i have spend hours thinking about his now , don't seem to understand where the error lies class Catalogs(viewsets.ModelViewSet): queryset = Catalog.objects.all() serializer_class = CatalogSerializer def create(self, request, *args, **kwargs): if request.data: serialized_data = self.get_serializer( data = request.data ) serializer class CatalogSerializer(serializers.ModelSerializer): catalog_products = CatalogProductsSerializer(source = 'catalogproducts_set',many=True) def create(self,validated_data): client_id = validated_data.pop('id') catalog_obj = Catalog.objects.create( client = User.objects.get(id=client_id), ) CatalogProducts.objects.create( catalog = catalog_obj, **validated_data ) return catalog_obj class Meta: model = Catalog fields = ['created_by','client','catalog_products','created_datetime','is_active'] -
How to access the request in models.py, django
@property def get_maca(self, request): if request.user.name == "example": return self I want to do something like this. If the user name is example return that object. How to access the request like this? -
Django+MongoDB: API to populate a collection with data from other collection
I'm trying to create an API in django rest-framework service to perform the following: Whenever the API is called (GET), I need to check all documents in old collection say OldCollection. Go through the OldCollection for relevant fields say ID, Field1, Field2. If Field2 is more than 100, then create a document in new collection with fields NewID, NewField1, NewField2. These fields are not dependant on old collection. API to return how many records got created on the new collection. I'm just getting started with rest framework. Looking for ways to achieve the above mentioned. Can anyone show how view function looks like? -
connection limit exceeded for mongo from aws
When I am trying to put requests from AWS cloud9 environment to Mongo DB Atlas, connectivity with MongoDB is slowed down. To add, while putting query on MongoDB, python code is taking time to fetch the data from database and even hanged. Ours is a free tier and I think the concurrent connection limit is 500. The problem arise after 2-3 weeks. Can we buy some connections? Or how to increase the connection limit. -Amar -
Inputs of form don't show anything
I use Nicepage to generate the html code. Here I have a grid with 3 columns and in each one there is a table then in each table I want to put a Django form. First I could not write anything in the inputs until I added style="display: block;z-index: 1" in first td of table. Now I can write inside the inputs and form works fine but inputs do not show anything; when I write a word inside it, it remains blank but actually word is there and form detects it . here the code : <section class="u-clearfix u-image u-section-1" id="sec-bf5a" data-image-width="640" data-image-height="480"> <div class="u-clearfix u-sheet u-sheet-1"> <div class="u-clearfix u-expanded-width u-gutter-22 u-layout-wrap u-layout-wrap-1"> <div class="u-gutter-0 u-layout"> <div class="u-layout-row"> <div class="u-container-style u-effect-fade u-hover-box u-layout-cell u-opacity u-opacity-60 u-radius-30 u-shape-round u-size-20 u-layout-cell-1" data-animation-name="" data-animation-duration="0" data-animation-delay="0" data-animation-direction=""> <div class="u-back-slide u-container-layout u-opacity u-opacity-60 u-palette-3-dark-2 u-container-layout-1"> <h2 class="u-text u-text-default u-text-white u-text-1">Login Here </h2> <h5 class="u-text u-text-default u-text-white u-text-2">Already a member&nbsp;</h5> <div class="u-table u-table-responsive u-table-1"> <table class="u-table-entity"> <colgroup> <col width="100%"> </colgroup> <tbody class="u-table-body"> <tr style="height: 26px;"> <td class="u-border-6 u-border-palette-3-dark-1 u-table-cell" style="display: block;z-index: 1"> <p style="color:{{color}};font-size:14PX;background-color:LightYellow;text-align: center">{{ER}}</p> <p> <form action="{% url 'docs:login' %}" method="post"> {% csrf_token %} {{form.as_p}} <input style="background-color: #675e39" type="submit" value="ENTER"> </form> </td> </tr> </tbody> </table> … -
Django Formset Required fields in formset validation
I have problems with formset, where I don't know why, can't prefill initial values and formset throws back errors "This field is required.". I thought that when I give queryset to filter forms, they will be prefilled with values given. So how to make this right? Thank you for answers. forms.py class CompositionForm(ModelForm): positionId = PositionsChoiceFields(queryset=Position.objects) class Meta: model = Players fields = ("positionId", ... ) labels = {"positionId": "Nas", ... } widgets = {} for i, f in enumerate(fields[1:]): widgets[f] = forms.TextInput( attrs={"disabled": True, "class": "show-input-as-text form-control flex-fill", "required": "false"}) def __init__(self, *args, **kwargs): super(CompositionForm, self).__init__(*args, **kwargs) PlayersFormSet = modelformset_factory(Players, form=CompositionForm,) views.py class CompositionView(BaseView): template_name = "..." def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def get(self, *args, **kwargs): # context = self.get_context_data(**kwargs) context = {} team = Teams.objects.get(userId=self.request.user.id) formset = PlayersFormSet(queryset=Players.objects.filter(teamId=team, ), ) context["formset"] = formset return render(self.request, self.template_name, context=context) def post(self, *args, **kwargs): context = self.get_context_data(**kwargs) team = Teams.objects.get(userId=self.request.user.id) form = PlayersFormSet(data=self.request.POST, queryset=Players.objects.filter(teamId=team)) form.clean() print(form.errors) print(self.request.POST) print(form.is_valid()) return render(self.request, self.template_name, context=context) [{'positionId': ['This field is required.'], ... <QueryDict: 'form-TOTAL_FORMS': ['5'], 'form-INITIAL_FORMS': ['4'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-2-positionId': ['1'], 'form-3-positionId': ['1']}> False