Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a page to add related instances?
for example, i have 2 models: Link and LinkCollection. LinkCollection have a title, user etc, and will be used to group instances of links. Ex: Django Links -> Link to page 1, Link to Page 2..., Python Packages -> Link to pckg page 1... I thought about doing something like: links/collections/<slug:link_collection>/add_link/ and in the views: def form_valid(self, form): kwargs = super().get_context_data(**kwargs) collection_slug = kwargs["link_collection"] collection = LinkCollection.objects.get(slug="collection_slug") form.instance.collection = collection form.instance.user = self.request.user return super().form_valid(form) this would add the instance link, which is handled by Django's CreateView, and would get the collection from the slug. But I think there are some problems with that. For example, the user may try to add getting the slug from a collection of another user etc, since the application will be used with authentication. What is the best way to do this? -
"Mixed Content" caused by end user's firewall software
Only end user I've come across this issue with. They are trying to upload and submit a file through our secure portal which is triggering a "Mixed Content" error causing the upload to fail. There is nothing in our app that is making a request to http://alert.scansafe.net, so it is something on their network intercepting internet traffic and scanning it. The error is pretty clear per the image: our app is running on HTTPS and this service they are using is over HTTP generating an error. There are a number of workarounds they can do on their end: https://kb.iu.edu/d/bdny https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content/How_to_fix_website_with_mixed_content I just want to know: is there anything I can do on my end in a Django/React app to resolve this issue? -
My Django server is not responding anything
Basically when I enter this command :- $- python manage.py runserver In command prompt it's shows my server address which is usually http://127.0.0.1:8000/ But when I enter this in Chrome it's doesn't showing me anything just showing "This site can't be reached" Please help me out because I am new to Django.. I also typed the command like $- python manage.py runserver 0.0.0.0.8000 And this $- python manage.py runserver [::] :8000 But still I can't see Django "Rocket".. !! And also I thing I want to tell that I am using WiFi for internet . So it's OK or else using Django server we need lan connection. -
In production Page not Found Error when trying to access Django /admin on deployed Heroku app
Friends - I have a django app (build with cookiecutter) and I have it deployed on Heroku, following these steps here: https://cookiecutter-django.readthedocs.io/en/latest/deployment-on-heroku.html Everything works fine and I can also create instances in the database. Now, when I try to enter the admin-page with /admin I get an 404 Page not found error. When deploying I had this error: (which I ignored) remote: Invalid input of type: 'CacheKey'. Convert to a byte, string or number first. remote: --> Continuing using default collectstatic. I ignored this error because I everything was working. Now, could that be connected or am I just missing something here? I assume I after deployment I should be able to login to the django admin section, or am I mistaken? Locally everything runs perfectly.... Any help or hints are very much appreciated! -
Why is my view not sending POST requests to the DB
I cannot seem to POST data to the DB. I'm using forms.Models and form.save() yet nothing is showing up in the DB. Furthermore, I don't understand how the GET requests are being sent to the server. And I cannot seem to successfully run my POST request in my view even though I can send a POST through my form Submit button (does not send info to DB). I've tried multiple methods. I'm either not understanding the fundamentals of POST/GET requests or I'm missing something in my Django code. The HTML and FORM renders as expected. VIEW def MenuCreateView(request,*args,**kwargs): form = MenuCreateForm(request.POST) form = MenuCreateForm(request.POST) if request.method == "POST": form = MenuCreateForm(request.POST) if form.is_valid(): # menu = form.save(commit=False) # menu.employee = request.user # menu.date = 'Jan 1' form.save() context = {"form": form} return render(request,"menu_create.html",context) print('Posted') else: form = MenuCreateForm() context = {"form": form} print('Get requested') return render(request, "menu_create.html",context) print('Anything') HTML <body> {% block content %} <form action='.' method='POST'>{% csrf_token %} {{ form.as_p }} <input type='submit' value='Save' /> </form> {% endblock %} </body> FORM BODY class MenuCreateForm(forms.ModelForm): date = forms.DateField() item_1 = forms.CharField( required=False, widget=item_CharField_widget) ... class Meta: model= Menu fields= ['date','item_1','item_2','item_3', 'item_4','item_5',] I expect the POST to print POSTED in my … -
Django authenticate always return None even if username and password are correct
I'm trying to do a web page using django. Where a user can register and login to the page. But When I try to login the authenticate function returns None even if the entered password and username are correct. I'm using django version 2.1.2 and Python 3.5 I have tried adding AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) in settings.py this is the function that I'm using for registration. def SignUp(request): countryobj = Country.objects.all() if request.method == 'POST': form = CustomUserCreationForm(request.POST or None) gr=request.POST.get('grade') if gr == 'Grade': messages.add_message(request, messages.WARNING, 'Select Any Grade') return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj}) if form.is_valid(): print("hihihih") user = form.save() user.refresh_from_db() username= request.POST.get('username') user.password=form.cleaned_data.get('password1') user.student.birthdate = form.cleaned_data.get('birthdate') user.student.school_name = form.cleaned_data.get('school_name') user.student.individual = form.cleaned_data.get('individual') user.student.school_address = form.cleaned_data.get('school_address') user.student.country = form.cleaned_data.get('country') user.student.state = form.cleaned_data.get('state') user.student.communication_address = form.cleaned_data.get('communication_address') user.student.c_country = form.cleaned_data.get('c_country') user.student.c_state = form.cleaned_data.get('c_state') user.student.grade = form.cleaned_data.get('grade') user.student.cost = form.cleaned_data.get('cost') user.student.total = form.cleaned_data.get('total') user.student.type_user = form.cleaned_data.get('type_user') user.student.currency=form.cleaned_data.get('currency_code') user.save() subject = 'Registration Successfull' message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password email_from = settings.EMAIL_HOST_USER recipient_list = [user.email] send_mail(subject, message, email_from, recipient_list) messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials') return redirect('login') else: form = CustomUserCreationForm() return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj}) else: form = CustomUserCreationForm() print("lalala") # return render(request, 'authentication/registration.html') … -
How to return a single list of separate models from a Django View
I'm creating a leaderboard system for a spelling website and I need to show a list of top 10 scoring users, as well as the user who is accessing the website currently. When I call the context_object_name template, the separate lists work. I can show the top 10 users and I can show the user who is signed in, but when I try to show both it fails. What do I do? views.py - The user is just being listed as that with 'id=10' for troubleshooting: from .models import Profile, User from django.http import HttpResponse,HttpResponseRedirect, Http404 from django.views.generic import ListView, TemplateView from django.shortcuts import get_object_or_404, render from django.urls import reverse class Homepage(ListView): template_name='homepage.html' context_object_name = 'profile_list' def get_queryset(self): return (Profile.objects.order_by('-score')[:10], User.objects.get(id=10).profile) models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) played = models.BooleanField(default=False) mistake = models.CharField(max_length=120, default="", blank=True) score = models.IntegerField(default=0) outOf = models.IntegerField(default=0) percentCorrect = models.CharField(max_length=120, default="n/a") def __str__(self): return self.user.username; The relevant part of homepage.html: {% if profile_list %} <h1 id=ldbtitle>Leaderboard:</h1> <ul id=ldb> <li id=ldbfields> <div id=ldb1> <p>Username</p> </div> <div id=ldb2> <p>Score</p> </div> </li> {% for Profile in profile_list %} <li id=ldbitems> <div id=ldb1> … -
pass image next and previous
I am using the code below that has two modal "modalgallery" shows the enlarged image in the modal "modalgconfirmedelete" when you go to delete the image. I wanted the "modalgallery" to include the next and previus buttons, but I could not do it. thanks for the help modalgallery.js $(function() { $('.pop').on('click', function() { $('.imagepreview').attr('src', $(this).attr('data-img-url')); $(this).next('.imagemodal').modal('show'); }); }); modalconfirmedelete.js $(function() { $('.pop2').on('click', function() { $(this).closest(".imagemodal").next(".delete").modal('show'); }); }); perfil.html {% for photo in photos %} <a class="pop" href="#" data-img-url="{{ photo.file.large.url}}"><img src="{{ photo.file.medium.url}}"class="img-thumbnail" width="200" height="200"> </a> <!-- Modal Gallery--> <div class="modal fade imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">X</span></button> <img src="" class="imagepreview" style="width: 100%;" > <a class="pop2" href="#" ><img src="{% static 'svg/delete.svg' %}" width="20" height="20" alt="">Deletar </a> </div> </div> </div> </div> <div class="modal fade delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">X</span></button> <h2>Tem certeza que deseja deletar essa foto: </h2> <a href="{% url 'delete' photo.id %}" type="button" class="btn bg-danger text-white js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Deletar </a> </div> </div> </div> </div> {% endfor %} </div> </div> </div> {% endif %} {% endif %} -
How to use data of vue object in django Templates href
I want to construct an url using django templates href mode, but the problem is that the url must contain data from vue object. In my Vue object, I use ${} to avoid delimiter clash with django, so I try to construct url like this: {%url 'main:commodityInfoPage' %{task.category} %{task.searchKey} %} Whole code of this part like this: <tr v-for="task in taskList"> <td>${task.searchKey}</td> <td>${task.category}</td> <td>${task.taskId}</td> <td>${task.status}</td> <td><a href="{%url 'main:commodityInfoPage' %{task.category} %{task.searchKey} %}">Info</a></td> </tr> And my django router like this: path('commodityInfo/<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage') Unfortunately, it doesn't work. Now I know it is about the params %{task.category},%{task.searchKey}. But I don't know how to set the format correctly, could you tell me how to fix it? -
Django (CBV) how to display form for comments beneath the post?
I have button 'add comment' beneath the post, that redirects to URL with form for comment. What I would like to have is form displayed beneath the post. I tried including URL with comment form in post template but got errors about form not being valid. Here are parts of my code : forms.py class CommentForm(forms.ModelForm): class Meta: model = models.Comment fields = ('text',) views.py class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ('user', 'group') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('username')) ... @login_required def add_comment_to_post(request, pk, **kwargs): post = get_object_or_404(models.Post, pk=pk) if request.method == 'POST': form = forms.CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect('posts:single', username=post.user, pk=post.pk) else: form = forms.CommentForm() return render(request, 'posts/comment_form.html',{'form': form}) post_detail.html {% extends "posts/post_base.html" %} {% block post_content %} <div class="col-md"> {% include "posts/_post.html" %} </div> {% endblock %} {% block post_post %} {% if user.is_authenticated %} <div class="container comments"> <!-- COMMENTS FORM IN HERE --> <a class="btn btn-primary add-comment" id="add-comment" href="{% url 'posts:add_comment' username=post.user.username pk=post.pk %}">Add Comment</a> {% for comment in post.comments.all %} <div class="jumbotron comment"> <p>{{ comment.author }} <span>{{ comment.created_at }}</span></p> <p>{{ comment.text_html|safe }}</p> </div> {% endfor %} </div> {% endif %} {% endblock %} … -
Is there any PasswordField in Django?
I'm new to Django, I'm building a Rest API (with Django Rest Framework). I've created a very basic User model : from django.db import models class User(models.Model): pseudo = models.CharField(max_length=50) username = models.CharField(max_length=20) email = models.EmailField(max_length=50) class Meta: verbose_name: "User" verbose_name_plural = "Users" def __unicode__(self): return '%s %s %s' % (self.pseudo, self.username, self.email) But it seems that Django don't have "PasswordField" for models... Is it a good practice to set a password field as CharField ? How can I hash the password before to send to the database ? -
Creating a relationship between two models after both models have been created
Explaining based on the django tutorial for creating a library: Say you allow a user to add a Book model to your library database. However you don't want them to add a Genre model to the Book. Instead, you have a Genre model in your database already with all listed Genre's in the world. When the user adds a Book to your database, you want your database to add the proper Genre to your Book based on text in the Book's summary. Say the Book has a TextField named summary and it has the words science and fiction in it when a bookinstance is created. The database will then add a Genre of science fiction to your bookinstance based on the words found in the bookinstance's summary TextField. Whether this happens at the moment of bookinstance creation or immediately after doesn't matter to me. I am trying to do this same thing with a website that would handle logging/creating workouts. When a user adds a workout (i.e. book to the library) to the database, I would like the database to add a movement (i.e. genre for books) to the workout depending upon what text is in the workout TextField. Example … -
Django tree models where two have manytomany relashionshio
I have those models and i want to select specific data from all models exemple: Consultatie.objects.filter(pacient=1) get data from Diagnotic specific to that pacient get data from Medicamentatie specific to that pacient Sorry for my english class Pacient(models.Model): name= models.CharField(max_length=100) class Medicamentatie(models.Model): lista_medicament = models.ForeignKey(ListaMedicamente, on_delete=models.PROTECT, choices='') class Diagnostic(models.Model): lista_boala = models.ForeignKey(ListaBoli, on_delete=models.PROTECT, choices='') medicamentatie_diagnostic = models.ManyToManyField(Medicamentatie) class Consultatie(models.Model): pacient = models.ForeignKey(Pacient, on_delete=models.CASCADE, choices='') medic = models.ForeignKey(Medic, on_delete=models.PROTECT, choices='') diagnostic = models.ManyToManyField(Diagnostic) -
In Django, how to redirect to an UpdateView upon submitting the CreateView?
I've created a single FormView and template HTML that I'm going to use for both creating and updating records from a Model. However, I cannot figure out how to set the CreateView to redirect to the new primary key that's being created. I've currently set it to go back to the base page, and but I can't seem to find any information on where to start with getting the new or existing primary key to redirect to the UpdateView. models.py class NewEmployee(models.Model): name = models.CharField(max_length=50) position = models.CharField(max_length=50) start_date = models.DateField() date_entered = models.DateTimeField('date entered', auto_now_add=True) forms.py class NewEmpForm(ModelForm): class Meta: model = NewEmployee fields = ['name', 'position', 'start_date'] views.py class EditView(UpdateView): model = NewEmployee form_class = NewEmpForm class Add_Emp(CreateView): model = NewEmployee form_class = NewEmpForm urls.py urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('add/', views.Add_Emp.as_view(success_url='../'), name='newemp-add'), path('<int:pk>/', views.EditView.as_view(success_url="../"), name='newemp-rev'), ] newemployee_form.html <DOCTYPE html> <html> <head> <title>Employee</title> </head> <body> <form method="post" > {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-default">Submit</button> </form> </body> </html> -
Django - Adding a second database entry causes failure. Django no longer uses 'default'
My database and project work great using this database setting: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'myprojectdb', 'USER': 'myprojectuser', 'PASSWORD': 'my_secret_password', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': True }, } But I want to add a 'readonly' database entry for my readonly db user, like this, so that I can run django-sql-explorer: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'myprojectdb', 'USER': 'myprojectuser', 'PASSWORD': 'my_secret_password', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': True }, 'readonly': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'myprojectdb', 'USER': 'myprojectreadonly', 'PASSWORD': 'your_eyes_only_secret', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': True } } And now django throws a couple different errors. If I try to do anything with migrations, I get: django.db.utils.ProgrammingError: permission denied for relation django_migrations If I try to runserver, I get: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed It seems like when I add the second database setting, django is attempting to use that for migrations, running the server, etc, even though it's not 'default' If I comment out the second entry, everything works great again. Any recommendations on how to correct this? -
How to pass arguments to graphql nested relation fields? [PYTHON-DJANGO]
I have a django database with Item and Store models being in many-to-many relation. Currently querying it like: { items(numItems:2){ productId productName stores{ storeId } } } By default it returns all related stores for the first 2 items. I'd like to restrict the number of returned stores to say 5: { items(numItems:2){ productId productName stores(numStores:5){ storeId } } } Is that implementable from Django schema level? I was trying something like: class Query(graphene.ObjectType): items = graphene.List(ItemType, num_items=graphene.Int(), num_stores=graphene.Int()) stores = graphene.List(StoreType, num_stores=graphene.Int()) def resolve_items(self, info, num_items, num_stores): for item in items: item.stores = item.stores[:num_stores] return Item.objects.all()[:num_items] def resolve_stores(self, info, num_stores): return Store.objects.all()[:num_stores] But it doesnt allow me to modify many-to-many field. -
502 Bad Gateway. After implementing the application on 'digitalocean'
I added my applications on DigitalOcean. But when I turn on my website I see the error. "502 Bad Gateway nginx/1.14.0 (Ubuntu)". I would like to solve it, but I do not know where I can find logs with errors. I always used CMD and when I tried to turn on the server, if something did not work, the CMD clearly said what was wrong. Where can I find something like this on DigitalOcean. I used PythonAnywhere once, and there was a separate tab with information about errors (practically the same as in CMS). Please forgive me for simple questions, I have little experience in servers and GIT. Any help will be appreciated. -
“The name ' Recipient_list ' is undefined in my Django project ” Error
In my Django project I get the "name 'recipient_list' undefined" error. What should I do to correct? def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] try: send_mail(name, from_email, subject, message, recipient_list) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, "giris/contact.html", {'form': form}) def thanks(request): return HttpResponse('Thank you for your message.') I would like to send an e-mail to my e-mail address at the end of the transaction. -
How do you use an uploaded file(saved in MySQL and local media folder) in a python script in Django
I have a simple python script that receives excel input, perform changes, and output as a csv file using openpyxl and pandas. As of right now, I have a page(built with Django) where it lets users upload a file, which then stores into server DB(MySQL) and local media folder, and show some information in a table format about the excel(Name, date, and download button to re-download the file). Even after whole lot of search, I am still hard stuck on how to load up the uploaded file from DB. My original code for the python script did: xlInput = input('Name of the Excel file to convert: ') csvOutput = input('Name of the resulting CSV file: ') wb = load_workbook(xlInput) sheets = wb.sheetnames ws = wb[sheets[0]] to accept input from terminal and change values in the sheet. How can I change the input code to accept the file from the MySQL DB or to run it when file is uploaded, automatically? -
How use composite primary key with django
I want to use a composite primary key in my django application. Equivalent of following sql schema: create table A ( a SERIAL NOT NULL, b INTEGER NOT NULL, c VARCHAR(50), PRIMARY KEY(a, b) ) insert into A (b, c) values (1, 'auto a, set b; 1.1'); insert into A (a, b, c) values (1, 2, 'set a, set b; 1.2'); insert into A (b, c) values (2, 'auto a, set b; 2.1'); insert into A (a, b, c) values (1, 3, 'set a, set b; 1.3'); insert into A (a, b, c) values (2, 4, 'set a, set b; 2.2'); select * from A; a | b | c ------------------------- 1 | 1 | auto a, set b; 1.1 1 | 2 | set a, set b; 1.2 2 | 2 | auto a, set b; 2.1 1 | 3 | set a, set b; 1.3 2 | 4 | set a, set b; 2.2 Column a must be serial and columns a and b must be primary key together. I found example with unique_constraint = (('a', 'b'),) but it causes integer type for a column and following indexes in my database schema: "pkey" PRIMARY KEY, btree (a) "some_constraint" … -
SVG rendering chart with D3 only when going back or forward to the page
On my local, D3 only renders the svg chart when going back to or forward to the page. It doesn't render on initial page load. Following the D3 tutorial here I can get the chart to render perfectly in a codepen or when going back to the page. I'm running the page using Django's flatpages app. I've tried multiple browsers and dev tools. The page returns no errors and the data is loaded before the function to create the chart is called. Is there a way to debug D3 or the Javascript function that I am missing? I suspect it's something to do with async and I need to add a window.onload like below but so far this hasn't worked. document.addEventListener("DOMContentLoaded", function(event) { fetch(api) .then(function(response) { return response.json(); }) .then(function(data) { var parsedData = parseData(data); window.onload = function() { drawChart(parsedData); } }) .catch(function(err) { console.log(err); }) }); Thanks in advance for any help. -
Django - Can't get code from DB to display in template
I'm trying to get my objects in the DB to display in the template. I've done this several times with other projects and I have looked over my code multiple times. It is displaying the text outside of the template language (like the header), just not what's in the template language. I just cant seem to pick up what the issue is. If someone can help me with this that'd be greatly appreciated. views.py from django.shortcuts import render from .models import Post # Create your views here. def posts_home(request): posts = Post.objects.order_by('pub_date') return render(request, 'posts/postshome.html', {'posts': posts}) models.py from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=250) pub_date = models.DateTimeField() image = models.ImageField(upload_to='media/') body = models.TextField() def __str__(self): return self.title HTML Template <h1>Welcome to Nick's Blog!</h1> {% for post in posts %} {{ post.title }} {{ post.body }} {{ post.pub_date }} {% endfor %} -
Django template rendering changed username on invalid edit profile form
I have a view where it is possible to change user's name and username. Field name has custom validators. If validators fail, form is not saved. It even works. The only problem is that I render username in my base.html template with this code Login as {{ user.username }} and username is rendered changed even when form is failing and user's username in the database is not changed. When I go to another URL, username is correct (it is unchanged value). Can you help me with that? It feels like bug and not a mistake in my code. -
Why is it bad to use non-dict objects in JsonResponse?
By default Django's JsonResponse class doesn't allow non-dict objects like arrays. I've looked at the documentation but it never explains why that'd be unsafe or otherwise undesired. Are there any good reasons only to use dict objects? I found something about old security vulnerabilities but as far as I can tell that's all patched up now. -
Django model-forms widget choice based on URL variables
lets say I have a form based on the model: Form1: class Meta: model = Comment widgets = {"field1": forms.HiddenInput } # option 1 #or widgets = {"field2": forms.HiddenInput } # option 2 And I have 2 widgets options . First -displays 2nd field but hides 1st and second -other way around. Choice of option 1 or option 2 is based on what ‘key’ variable it would receive from URL kwargs. For example if key == 1 then option 1 is chosen, if key == 2 – then second option is chosen. #example <a href="{% url "app:route" key="1 or 2 " pk=object.pk %}"> COMMENT</a> Question is how to reach self.kwargs dictionary in .forms? Or there is an alternative less dumb way to do it? Final goal is to use one of the options , base oneself on the “key” variable , that is different urls would send different “key = x “ variables. Where I could implement this sort of logic in Django? Views?