Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I get error raise ImproperlyConfigured
I want to add info in database using django-seed. seed.py from django_seed import Seed from models import Employee seeder = Seed.seeder() seeder.add_entity(Employee, 5) inserted_pks = seeder.execute() When I try to start command: python3 seed.py I've got this error: Traceback (most recent call last): File "seed.py", line 2, in <module> from models import Employee File "/home/kaucap/test/myproject/app_worker/models.py", line 4, in <module> class Employee(models.Model): File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/kaucap/test/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 67, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can anyone explain why I have this error and how I can fix it? -
Render Django Template after AJAX POST
I'm using django and ajax to build a small app. I send some data by ajax: // send search post when clicking the button $("#search-button").click(function(){ $.post( "{% url 'search-index' %}", { query: $("#query").val() }, function(data, status){ console.log("success") } ) }) And I generate some new data according to the query, which I'd like to display in the html template: def view(request): if request.method == "POST": query = request.POST["query"] hits = search(query) return render(request, "search/index.html", {"hits": hits}) {% if hits %} <div class="container"> {% for hit in hits %} <div> <a href="">{{ hit.title }}</a> </div> <div> <p>{{ hit.abstract }}</p> </div> {% endfor %} </div> {% endif %} However, I find django is not rendering the template, I got an empty html page after this post request. I don't want to append the data using jquery. I prefer to modify the html in the template. Any solution? Thanks in advance. -
Where to store dictionary in Django
I have a dictionary that I get from the local delivery company API. I want to use it in my app to populate the city select field. I don't want to get this data every time when a user loads the page. So I need to store it somewhere and update it once a day. What is the best way to do this using Django? url = 'https://api.novaposhta.ua/v2.0/json/' data = { "apiKey": "apiKey", "modelName": "Address", "calledMethod": "getCities", "methodProperties": {} } city_list_json = requests.post(url, json=data).text city_dict = {d['Ref']: d['Description'] for d in json.loads(city_list_json)['data']} -
TimeoutError while sending mails
I have a Django project where the users can launch a task that's executed using Celery, and then they receive a mail when this task is finished. My issue lays in my mails that are not sent everytime. Some emails are not sent and in the console I have a TimeoutError: [Errno 10060] WSAETIMEDOUT. I don't know if that can help but I noticed that when I start trying to send mails, the first ones raise this error, and after some time of trying to send mails, like maybe 15mn, the mails are sent successefully and I get no error afterwards. I've tried every solution I was able to find here on SO as well as on GitHub, but none of the solutions provided seemed to work for me. I'm using gmail with a double authentication. I have this in my settings.py file : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my-email-account' EMAIL_HOST_PASSWORD = 'my-password' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'emaildetest81@gmail.com' My email sending function : from django.core.mail import EmailMessage from django.conf import settings def send_output_file(mail): header = "Result of task execution" body = "Your task has finished executing !" email = EmailMessage(header, body, settings.DEFAULT_FROM_EMAIL, [mail,],) … -
Django rest framework APIView Pagination EmptyPage
Successfully made pagination work and here is my code: from rest_framework import pagination class CustomPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 10 page_query_param = 'p' class PaginationHandlerMixin(object): @property def paginator(self): if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() else: pass return self._paginator def paginate_queryset(self, queryset): if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self, data): assert self.paginator is not None return self.paginator.get_paginated_response(data) and this my view class: class OrderOntrackViewPaginated(APIView, PaginationHandlerMixin): queryset = Order.objects.filter(~Q(staged__iexact="offtrack")).values().order_by('-id') serializer_class = OrderSerializer pagination_class = CustomPagination permission_classes = (permissions.AllowAny,) http_method_names = ['get'] def get(self, request): results = self.paginate_queryset(self.queryset) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) my question is if I can handle EmptyPage so if max page is for example 3 and user puts ...?p=4 in the request, I could return a valid response. -
Django best way to communicate between two domain servers
I have a requirement in which an admin domain for example 'domainA' where the admin can login and he can restrict the user access to domainB,domainC.... What is the best way to achieve this. Current functionality is that each users are created in each domain and assigned in respective groups.So my question is from domainA how can I add or remove users from domainB,domainC.. from domainA -
Getting this error when i am run migrate i check in below path but i don't what to change there
File "C:\Users\shubham\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\dateparse.py", line 116, in parse_datetime return datetime.datetime.fromisoformat(value) TypeError: fromisoformat: argument must be str PS E:\Django\login> -
how to send an email verification from admin when an email is updated
I joined a project where the code is written on django 2+. It's a system for patient and doctors. When a doctor registered a patient, this one gets an email confirmation with a link. Once he clicks on it she can use the platform. On her user interface in settings, a patient can update her email and she will get a new link to her new email to confirm that it is her email. Before she clicks on the confirmation link, the email attribute is not changed. only the email candidate is updated and to this one the email is sent. (if I change the email attribute to the email_candidate one so if she made a mistake on the her email_candidate she won't be able to log in anymore) Then after the click, the patient email will become the email candidate one. All this works on the Patient Support Admin interface, an agent can help patients to update their email also. But when the action is requested of send an email confirmation the email candidate is not chosen. only the user email is chosen and to it the email confirmation is sent. I really don't understand how to call maybe … -
Field 'codigo_cad' expected a number but got <Customer: 1>
I have no idea how to fix this: I'm having problems when pulling the costumer.codigo_cad, because I have the str functionality that only sends a string, and the object is requesting an int, whenever I try to move this part the error becomes bigger, like the location reads as if was a table object, and not an int, thanks in advance to anyone who helps me *my models return str(self.codigo_cad) def get_aniversario(self): return f'{self.aniversario_cad.strftime("%d/%m/%Y") if self.aniversario_cad != None else "30/12/1899"}' # clica na pessoa e retorna os detalhes dela def get_customer_url(self): return f'/customer/{self.codigo_cad}' # clica em vendas e retorna as vendas da pessoa def get_sale_customer_url(self): return f'/venda/?customer_sale={self.codigo_cad}' ** my views ** order_forms = Venda() item_order_formset = inlineformset_factory(Venda,ItemVEN,form=ItemVenForm,extra=0,can_delete=False,min_num=1,validate_min=True) venda = get_object_or_404(Venda,pk=pk) # recupera venda #desconto = f'{venda.desconto_ven:,}' # formata desconto cliente = get_object_or_404(Customer,pk=venda.cliente_ven) # para recuperar os dados do cliente da venda clientes = Customer.objects.all().order_by('pk') # para o modal clientes produtos = Produto.objects.all().order_by('pk') # para o modal produtos itens = ItemVEN.objects.filter(num_ven_ite=pk) # recupera itens venda itens_venda = []``` -
Use viewset and serializer without model
I want to return the CPU usage and Memory usage by viewset. class StatusViewSet(viewsets.ViewSet): serializer_class = StatusSerializer def list(self, request): // get CPU/Memory usage here somehow. below line is dummy. status_data= {"memory":80,"cpu":80} serializer = StatusSerializer( instance=status_data, many=True) return Response(serializer.data) class StatusSerializer(serializers.Serializer): cpu = serializers.IntegerField(read_only=True) memory = serializers.IntegerField(read_only=True) What I have done is like this below. I just want to return {"memory":80,"cpu":80} however it returns blank value. [ {}, {} ] I suspect I should return the data to serializer in another way instance=status_data, however how can I do this? -
AttributeError: 'Settings' object has no attribute 'STRIPE_PUBLIC_KEY'
stripe.api_key = settings.STRIPE_SECRET_KEY I am using dgango and its my first project and shows error after adding the above line in views.py file: File "C:\Users\iamab\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf_init_.py", line 80, in getattr val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'STRIPE_PUBLIC_KEY' -
How can I create fake db using django-seed with code?
I need to create fake database. If I use command: python3 manage.py seed api --number=15 it works fine. But how can I create fake DB using with code? There some example of code: from django_seed import Seed seeder = Seed.seeder() from myapp.models import Game, Player seeder.add_entity(Game, 5) seeder.add_entity(Player, 10, { 'score': lambda x: random.randint(0, 1000), 'nickname': lambda x: seeder.faker.email(), }) inserted_pks = seeder.execute() How can I run it after start my server? -
Django and Javascript ReferenceError: function is not defined at HTMLButtonElement.onclick
So I have index.js in static/network/index.js and I would like the functions I define there to run in Django templates. The file is linked by and {% load static%} but unfortunately after adding a button with the onliclick parameter in the console to any place in the template, it appears error "ReferenceError: function is not defined at HTMLButtonElement.onclick" layout.html {% load static %} // This is where static files should be loaded. <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" rel="stylesheet"> <script src="{% static 'network/index.js' %}"></script> // And this is where the static files should also be loaded. </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Network</a> <div> <ul class="navbar-nav mr-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'profile' user.username %}"><strong>{{ user.username }}</strong></a> </li> {% endif %} <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}" >All Posts</a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'followers_view' %}">Following</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> … -
How do I change FilePathField to FileField in a Django Model dependant on the instance of a related Model?
I am trying to create a directory based on the instance of a created participant. This directory will be used to upload files for that participant. I'm trying to convert a desktop app into a Django web app and I'm new to Django. Any help will be greatly appreciated. Thanks in advance. My code: def processed_path(report_folder_name): s_id = report_folder_name processed_file_path = os.path.join(settings.MEDIAFILES_DIR, 'processed', s_id) processed_file_path = str(processed_file_path) if not os.path.exists(processed_file_path): os.mkdir(processed_file_path) return processed_file_path class Participant(models.Model): id = models.BigAutoField(primary_key=True, unique=True, editable=False) participant_id = models.CharField(default="Participant", max_length=100) location = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True, null=True) # isansys_file_upload = models.FileField(null=True, blank=True, upload=isansysFilePath) def __str__(self): return str(self.participant_id) class ProcessedDataFile(models.Model): participant = models.ForeignKey(Participant, on_delete=models.CASCADE) processed_folder_name = Participant.participant_id processed_file_upload = models.FileField(null=True, blank=True, upload_to='processed/') processed_file_path = models.FilePathField(null=True, blank=True, path=processed_path) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.processed_file_path) -
Can Django see in inner directories 'management/commands' a commands
Whether can Django see a command which is situated like management/commands/other_directory/my_command.py? I just wanna sort them by their actions. -
Django request.body format
When I try to print request.body, the below is printed b'----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="release_date"\r\n\r\n2003-06-01\r\n----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="fanmodel"\r\n\r\nfan234code\r\n----------------------------914826831994362856243559\r\nContent-Disposition: form-data; name="country_code"\r\n\r\nAO\r\n----------------------------914826831994362856243559--\r\n' My post request data is available here but along with a lot other data. I want to understand what is that other data and how can I format it ? -
how can I create a category for ungrouped data?
I'm trying to create a category for scraped data that isn't grouped but I get this error. I'm wondering if there is a way I can get around it. Traceback (most recent call last): File "C:\Users\MUHUMUZA IVAN\Desktop\JobPortal\test.py", line 128, in <module> the_category = Category.objects.get(title="Others") File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 397, in get raise self.model.DoesNotExist( jobapp.models.Category.DoesNotExist: Category matching query does not exist. for test_job in final_jobs: if 'Manager' in test_job['title']: the_category = Category.objects.get(title='Manager') elif 'Engineer' in test_job['title']: the_category = Category.objects.get(title= 'Engineer') elif 'Architect' in test_job['title']: the_category = Category.objects.get(title='Architect') else: the_category = Category.objects.get(title="Others") I know it says there is no query matching Others, how can I correct this. -
Django - separated settings by environment. Not finding variable from base settings
I've split my django environment as per this post. In settings/base.py I have BASE_DIR specified: BASE_DIR = Path(__file__).resolve().parent.parent.parent In settings/__init__.py I have: from .base import * env = os.environ['ENV'] ... if env == 'test': from .test import * ... In settings/test.py I have DATA_VOLUME_BASE_DIR = BASE_DIR / 'scanned_images'. I expect that Django loads the settings module, imports settings/base.py, checks the environment ('test'), imports settings/test.py (which works) and the variable is available (which isn't). My stacktrace: sid_test_web | Traceback (most recent call last): sid_test_web | File "/code/manage.py", line 22, in <module> sid_test_web | main() sid_test_web | File "/code/manage.py", line 18, in main sid_test_web | execute_from_command_line(sys.argv) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_ sid_test_web | utility.execute() sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 363, in execute sid_test_web | settings.INSTALLED_APPS sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ sid_test_web | self._setup(name) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup sid_test_web | self._wrapped = Settings(settings_module) sid_test_web | File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__ sid_test_web | mod = importlib.import_module(self.SETTINGS_MODULE) sid_test_web | File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module sid_test_web | return _bootstrap._gcd_import(name[level:], package, level) sid_test_web | File "<frozen importlib._bootstrap>", line 1050, in _gcd_import sid_test_web | File "<frozen importlib._bootstrap>", line 1027, in _find_and_load sid_test_web | File "<frozen importlib._bootstrap>", … -
add to cart button is not responding
my add to cart button is not responding. I have applied javascript on my add to cart button, In cart button I have assigned attribute i.e data-product the value that is {{product.id}}. <div class="card-body"> <h5 class="card-title fw-bold text-uppercase">{{product.name}}</h5> <p class="card-text"><h4 style="font-size: 1rem; padding: 0.3rem; opacity: 0.8;">$ {{product.price}} </h4></p> <button data-product={{product.id}} data-action="add" class = "btn btn-outline-secondary add-btn update-cart">ADD TO CART</button> </div> </div> above is my code for products.html and this my code for javascript. var updateBtns = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) }) } The console is not showing any thing even though I click on Add to Cart button several times -
When will the "raise_exception=True" pass through the is_valid() function?
My Serializer.py in this MovieSerializer I will check if "name" and "description" is same or not, if same then raise an error. class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=80) description = serializers.CharField(max_length=300) def create(self, validated_data): return Movie.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() return instance # object level validation def validate(self, data): if data['name'] == data['description']: raise serializers.ValidationError("Name and Description can not be Same.") else: return data My views.py in serializer.is_valid() not pass raise_exception=True, when 'name' and 'description' is same it return a formated error message. output : class MovieListAV(APIView): def post(self, request): serializer = MovieSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My another serializer validate "password" and "confirm_password" same or not, if different then raise an error. class UserPasswordChangeSerializer(serializers.Serializer): password = serializers.CharField(write_only=True, style={'input_type':'password'}) confirm_password = serializers.CharField(write_only=True, style={'input_type':'password'}) class Meta: fields = ['password', 'confirm_password'] def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('confirm_password') if password != password2: raise serializers.ValidationError({'password':'Password and Confirm Password Should be Same!'}) user = self.context.get('user') user.set_password(password) user.save() return attrs My other view serializer.is_valid() not pass raise_exception=True, when "password" and "confirm_password" is dirrerent it can't return any formated error message. but when I use "raise_exception=True" as a … -
How to add data dynamically to specific column in jQuery DataTable which is already initialised?
In jQuery DataTable, i want to add data to specific columns dynamically after table is initialised, I don't want to reinitialise table again, just want to add row data to specific columns dynamically. -
SuspiciousFileOperation at /file/upload/ Detected path traversal attempt in '/app/media/Resume/Lal.pdf'
I am trying to upload a file to dropbox using django restframework. I am getting the following error : SuspiciousFileOperation at /file/upload/ Detected path traversal attempt in '/app/media/Resume/Lal.pdf' This is first time I am using dropbox with django and I have tried my best to find the issue but I couldn't. TIA. Traceback: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/app/file_app/views.py", line 14, in post file_serializer.save() File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/app/.heroku/python/lib/python3.10/site-packages/rest_framework/serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 739, in save self.save_base(using=using, force_insert=force_insert, File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 776, in save_base updated = self._save_table( File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 881, in _save_table results = … -
Is VAPID keys are unique to each server for web push notifications?
While implementing push notification (in Django framework), I have used VAPID keys which generated by a website (https://vapidkeys.com/). Can I use any random dummy text for these keys instead of generating using any other platforms ? Or does these VAPID keys being checked with any server during push notification process ? -
Migrations conflicts in Django, CircularDependencyError
I have a fresh new Postgres DB for my Django app. After applying the initial migrations with python3 manage.py migrate I run python3 manage.py makemigrations to create the tables for my models but no change is detected and no migrations created. This is weird but running python3 manage.py makemigrations app_name for each individual app in my project seems to work. When I try to python3 manage.py migrate I got an error: django.db.migrations.exceptions.CircularDependencyError: hub.0001_initial, crm.0001_initial where hub and crm are the names of 2 of the apps in the projects. This happens because some models in my hub app have relationships with some models in the crm app and viceversa. An effective solution would be to comment out all the relationship fields in my models, migrate, un-comment and makemigrations and migrate again to create the relationships tables. I don't want to go through all my models commenting out fields, is anyone aware of a more elegant solution? Thanks in advance. -
Django get_form results in unbound form (or what is the best way to get url parameters into a model form using CBV createview?)
I'm using a model form and a CBV (createview) to build a form. I needed to get url parameters into the form so I could access details from the previous view that sent the user to the form. To achieve this I initially tried overriding get_form as follows: def get_form(self): form = AddDataForm(key_a=self.request.GET['a'], key_b=self.request.GET['b']) return form This didn't work. The form wouldn't save (even when all fields were correctly completed). It would result in an unbound form. I eventually got a positive result by using get_form_kwargs as follows: def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'key_a': self.request.GET['a'], 'key_b':self.request.GET['b']}) return kwargs My question is, what about get_form (or my lack of understanding of it) results in this behaviour? My forms.py is below too. class AddDataForm(forms.ModelForm): class Meta: model = MiningTech fields = '__all__' exclude = ('user',) def __init__(self, key_a, key_b, *args, **kwargs): # key_a comes from the view's get_form. super(AddDataForm, self).__init__(*args, **kwargs) if len(key_a) > 3: for field_name in self.fields: if not field_name.startswith(key_a[0:3]): # If field_name doesn't start with first 3 characters of key_a, hide it. self.fields[field_name].widget = forms.HiddenInput() print("__init__ args", kwargs) else: self.fields[field_name].required = True self.fields['slug'].initial = key_b else: print("All fields Hidden")