Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add multiple hidden fields in Django Form
I'm using Django. I need a form that shows the 3 fields of a class I have created, the idea is that for every time you want to add a new day and time show a new section (I do not know if I explain). I still do not logo to make it work, if someone has any idea they would be grateful. Models.py class Profesor(Person): legajo = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=30) matter = models.CharField(max_length=100, blank=True, null=True) calendar = models.ForeignKey('calendar', on_delete=models.DO_NOTHING) user = models.CharField(max_length=20, blank=True, null=True) class calendar(models.Model): day = models.DateTimeField(default=date.today().isoweekday()) hs_init = models.DateTimeField(default=datetime.now().hour) hs_end = models.DateTimeField(default=datetime.now().hour) Forms.py class addProfesorForm(ModelForm): calendar = forms.ModelChoiceField(queryset=calendar.objects.all(), widget=forms.HiddenInput()) class Meta: model = Profesor TYPES = ( ('Motiv', 'Motiv'), ('Academic', 'Académic'), ('Otro', 'Otro') ) help_texts = { 'matter': 'message' } fields = ['id', 'type', 'matter'] widgets = { 'type': Select2Widget(choices=typeS) } class calendarForm(ModelForm): class Meta: model = calendar fields = ['day','hs_init','hs_end'] Views.py def agregarTutor(request): if request.method == 'POST': form = addProfesorForm(request.POST['calendar']) calendar=calendar.objects.all()[0] if form.is_valid(): id = form.cleaned_data['id'] try: person_Sysatem = SysatemPerson.objects.get(pk=id) alumn_Sysatem = SysatemAlumn.objects.get(pk=id) except SysatemPerson.DoesNotExist: return render(request, 'menu/new-Profesor.html', {'new_manual': True, 'not_found': True, 'nbar': 'profesors', 'id': id}) new_Profesor = Profesor( nombre=person_Sysatem.nombre.rstrip(), id=person_Sysatem.numerodocu, legajo=alumn_Sysatem.legajo, telefono=person_Sysatem.telefono.rstrip(), mail=person_Sysatem.mail.rstrip(), type=form.cleaned_data['type'], calendar=form.cleaned_data['calendar'], matter=form.cleaned_data['matter'], user=id, ) Profesor.save(new_Profesor) contrasena = 'id'+str(id)[0:5] … -
AWS Aurora database read replica autoscaling - best practices for django project to connect your application to newly created databases?
Using AWS Aurora database service - you can configure master-slave replication and slave autoscaling (e.g. if slave CPU is higher than 75 percent - create a second slave). Newly created database has a new endpoint (host) which is not registered by django yet. What would be the best approach to firstly discover the newly created database and add it to a running django application? I am thinking about pinging every X seconds using, lets say, aws cli and checking how many slaves are there. But the problem with this is if a slave is destroyed by an autoscaling group - my django application would start erroring, so an appropriate handling is also required... -
Django rest how to do not send specific data of the serializer
For example, I would like to send user information with serializer.data response, where the serializer has: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'passwordHash', 'email') How can I send the serialized user without the passwordHash field of the serializer? -
get the actual value of the human-readable name from choices in django models
I made this model: name = models.CharField(max_length=3, choices=( ('sat', "Saturday"), ('sun', "Sunday"), ('mon', "Monday"), ('tue', "Tuesday"), ('wed', "Wednesday"), ('thu', "Thursday"), ('fri', "Friday"), ), null=False, blank=False, primary_key=True) and when I want to get objects I can only access the human-readable name of choices. how can I get an object by human-readable name? I tried this but got an error: Days.objects.get(name='saturday') -
DJANO sql-server sqllite3
I have a project in django , and i was using the default datebase (sqlite3) I have the following models : class Freguesia(models.Model): id = models.IntegerField("Freguesia ID", primary_key=True) nome = models.CharField("Freguesia",max_length=255) def __str__(self): return self.nome class Rua(models.Model): id = models.IntegerField("Rua id", primary_key=True) freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE) nome = models.CharField("Rua",max_length=255) def __str__(self): return self.nome In my Rua.models i have id's with 0000000000000000000000000digits and everything it is working fine. But when i starting using the sqlserver , and i try to import from excel to sqlserver this error start to happen: http://prntscr.com/mqxirq I try to change my field type to id = models.CharField("Rua id", primary_key=True,max_length=255) on Rua.models and try again to import excel-sqlserver and now i have this error: http://prntscr.com/mqxl99 So right now i have no idea what i can do to import my data from excel to my sqlserver -
Django How to get path variable from all request in middleware?
I am new to python(3)/Django(2.1.4) framework. I want to get path variable which is present in all urls in my middleware. I tried something below but its not working for me. URLS: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/mywebsite/<uuid:path_variable_name>/', include('website.urls')), ] Middleware : class my_middle_ware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print(request.GET.get['path_variable_name']) print(request.POST.get['path_variable_name']) response = self.get_response(request) return response I want to fetch path_variable_name in my middleware. Instead of using request.GET, request.POST and so on , Is there any generic way to intercept all request request.getPathVariable('path_variabl_name') ? Thanks In Advance. -
When using the length method in Django-template, ".length" and "|" Difference between
I am trying to compare the length of a variable in an if statement in a Django-template. I wrote it simply as A code, but it did not work. So I found out the B code through Googleing. I wonder why blog.body> 50 not blog.body | 50 A Code {% if post.contents.length > 50 %} {{ post.over }} ... <a href="{% url 'detail' post.id %}">detail view</a> //post.over is a predefined method in the model that limits the number of characters. {% else %} {{ post.contents}} <a href="{% url 'detail' post.id %}">detail view</a {% endif %} B Code {% if post.contents.length | 50 %} {{ post.over }} ... <a href="{% url 'detail' post.id %}">detail view</a> //post.over is a predefined method in the model that limits the number of characters. {% else %} {{ post.contents}} <a href="{% url 'detail' post.id %}">detail view</a {% endif %} What is the meaning of "|"? It does not seem to be the or operator ("||"). -
TypeError at /posts/category/ssc 'Category' object is not iterable
I am trying to view post category page using category slug. But I don't know why it gives error something like this after adding url. TypeError at /posts/category/ssc 'Category' object is not iterable templates/navbar.html <nav class="nav d-flex justify-content-between"> {% for lst in category %} <a class="p-2 text-muted" href="{% url 'posts:categoryview' slug=lst.slug %}">{{lst.name}}</a> {% endfor %} </nav> view.py def view_category(request, slug): category = get_object_or_404(Category, slug=slug) return render_to_response('category_view.html', { 'category': category, 'post': Post.objects.filter(category=category).values() }) models.py class Category(models.Model): name = models.CharField(max_length= 60) slug = AutoSlugField(populate_from='name') parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) urls.py urlpatterns = [ path("", posts_list, name="list"), path("category/", category_list, name="categorylist"), path("category/<slug>", view_category, name="categoryview"), ] -
Login a user (Backend) that has an unusable password set (Django)
I Check my Users Credentials outside of the statndard Django Auth methodology in and (Active Directory) and if they exist in the active directory but not in the Django users I make them an account (Also unsure if this is the correct way to do this) user = User.objects.create_user(username=username_param) user.set_unusable_password() I set an unusable password as I do not want to store Passwords on the Django site How would I log a user in based on if they pass my custom AD authentication by username and if they have no password set (in Django) as you cannot perform a check_password() method on the password field as it will always return False The password in the password field for the Django Admin page says Password:No password set. Thanks in Advance -
Creating custom rest driven nodes Django-Viewflow
i'm interested in creating a rest driven process in django-viewflow. I've been reading the official page and by doing so i've arrived to the conclusion that after aquiring the pro version of viewflow to have rest integration, I would still need to make my own rest implementation for the nodes to drive the process. My question is basically if what I understand is true, and if so how could I implement restful nodes to drive the process. -
How to rename objects in Django
I've created object called company (code below) from django.db import models from django.core.validators import MinValueValidator from multiselectfield import MultiSelectField class company(models.Model): company_name = models.CharField(max_length=100) COMPANY_TYPES = ( ('star', 'Startup'), ('sh', 'Software House'), ('ecom', 'E-commerce'), ('corp', 'corporation'), ) company_types = models.CharField(max_length=4, choices=COMPANY_TYPES) company_workers = models.PositiveIntegerField(validators=[MinValueValidator(1)]) company_headquarters = models.CharField(max_length=100) COMPANY_TECHNOLOGIES = ( ('php', 'PHP'), ('js', 'JavaScript'), ('ang', 'Angular'), ('java', 'Java'), ('ruby', 'Ruby'), ('ror', 'Ruby on Rails'), ('jee', 'Java EE'), ('python', 'Python'), ('django' , 'Django'), ) company_technologies = MultiSelectField(max_length=25, choices=COMPANY_TECHNOLOGIES) company_about = models.TextField() but I don't know exactly how to rename objects in admin site. I would like to every created object has title from company_title but I can't find a function like this. You can see below how it's looks on image (company object (2) , company object (1) ) enter image description here Does anyone know how to replace those names with company_name? -
NoReverseMatch for '' with keyword arguments '' not found
I'm using django 2.1.4 and python 3.6.7. When i try to run my app i have an error NoReverseMatch at /depotAnnonce/ Reverse for 'mesChambres' with keyword arguments '{'args': [26, 3]}' not found. 1 pattern(s) tried: ['depotAnnonce\/mesChambres\/(?P[^/]+)\/(?P[^/]+)$'] views.py : class DepotAnnView(TemplateView): template_name = "base/depotann.html" def get(self, request): form = Annonceform() return render(request, self.template_name, {'form': form}) def post(self, request): util = Annonceur.objects.filter(user_id=request.user.id)[0] form = Annonceform(request.POST) if form.is_valid(): titre = form.cleaned_data['titre'] nbChambre = form.cleaned_data['nbChambre'] superficie = form.cleaned_data['superficie'] loyer = form.cleaned_data['loyer'] bail = form.cleaned_data['bail'] animaux = form.cleaned_data['animaux'] fumeur = form.cleaned_data['fumeur'] description = form.cleaned_data['description'] id = Annonce.objects.count()+1 ann = Annonce(id, titre, nbChambre, superficie, loyer, bail, nbChambre, animaux, fumeur, description, request.user.id) ann.save() return redirect('mesChambres', args=[id,nbChambre]) return render(request, self.template_name, {'form' : form}) class MesChambreView(TemplateView): template_name = "base/mesChambres.html" def get(self, request, idAnn, nbCh): reponse = request.args form = Chambreform() return render(request, self.template_name, {'form': form}, reponse) def post(self, request): reponse = request.args form = Chambreform(request.POST) if form.is_valid(): loyerCh = form.cleaned_data['loyerCh'] superficieCh = form.cleaned_data['superficieCh'] ch = Chambre(Chambre.objects.count()+1, reponse[0], loyerCh, superficieCh) ch.save() return redirect('index') return render(request, self.template_name, {'form': form}, reponse) urls.py : path('depotAnnonce/mesChambres/<idAnn>/<nbCh>', views.MesChambreView.as_view(), name ='mesChambres'), -
Value Error when assign to foreign key field while creating the object
I have the following Models from django.db import models class League(models.Model): league_id = models.IntegerField() country = models.ForeignKey('Country', on_delete = models.CASCADE) name = models.CharField(max_length = 50) logo = models.CharField(max_length = 250) season = models.IntegerField() season_start = models.DateField() season_end = models.DateField() standings = models.BooleanField(default= False) class Country(models.Model): country = models.CharField(max_length = 20, primary_key=True) country_id = models.IntegerField() I created custom management command to get data from API then extract disered data from API responce and create object of model based on this data. My custom management command code from django.core.management.base import BaseCommand, CommandError from data.models import League, Country import requests import json def extracting_league(): response = requests.get("https://api-football-v1.p.rapidapi.com/leagues", headers={"X-RapidAPI-Key": "rRVyARf9ESmshWSiNIkYcTr0jp1nQh2JjsnNGNlcEYXM1XI"}) league = json.loads(response.text) return league parsed_league = extracting_league() print(parsed_league) def pars(): leagues = parsed_league['api']['leagues'] for id in parsed_league['api']['leagues']: lg_id = leagues[id]["league_id"] lg_name = leagues[id]["name"] lg_country = Country.objects.get_or_create(country = leagues[id]["country"]) lg_logo = leagues[id]["logo"] lg_season = leagues[id]["season"] One_league = League.objects.create(league_id = lg_id, country = lg_country, name = lg_name, logo = lg_logo, season = leagues[id]["season"], season_start = leagues[id]["season_start"], season_end = leagues[id]["season_end"], standings = leagues[id]["standings"]) One_league.save() print(One_league) class Command(BaseCommand): def handle(self, **options): extracting_league() pars() When i run script with python manage.py 'custom management commmand' i see in console the following error notifications Traceback (most recent call last): File … -
Redirect Multiple Domains to a Single Domain django
I don't understand where I mast put this code and what else mast to do. Please explain me this => https://djangosnippets.org/snippets/434/ from django.http import HttpResponseRedirect class ValidateHostMiddleware(object): """ In Apache's httpd.conf, you may have ServerName set to mysite.com.au along with a number of aliases: mysite.com, mysite.net, my-site.com etc. This middleware redirects any request that isn't for mysite.com.au to that domain, helping with SEO and brand recognition. """ def process_request(self, request): if not request.META['HTTP_HOST'].endswith('mysite.com.au'): return HttpResponseRedirect('http://www.mysite.com.au/') -
Inegrity Error While Saving Queries From View
I am getting Integrity Error. The data is entering database. Then after it is giving error. Why this is happening Can any tell me how to do it IntegrityError at /trustyrequest/update/4/ (1062, "Duplicate entry '' for key 'email'") class TrustyRequestUpdate(generic.UpdateView): template_name = "trustyrequest/update.html" model = TrustyRequest form_class = TrustyRequestForm success_url = reverse_lazy('trustyrequest_list') def form_valid(self, form): if form.cleaned_data['status'] == 'Accepted': print('PK: ', form.instance.id) random_password = User.objects.make_random_password() # generate password here user = User( first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], phone_number=form.cleaned_data['phone_number'], ) user.set_password(random_password) user.save() elif form.cleaned_data['status'] == 'Pending': print('Pending') print('PK: ', form.instance.id) elif form.cleaned_data['status'] == 'Rejected': print('Rejected') print('PK: ', form.instance.id) return super().form_valid(form) Is there a good way to do above code. -
UpdateView testing form validity before saving
Adjust visibility in UpdateView and its fields, I'm updating here the image field, and it's working perfectly, my question is: which if I give submit it saves the data without making sure that the form is valid, and does not appear in the form errors in red Views.py class PhotoUpdate(LoginRequiredMixin, UpdateView): model= Usuario fields = ['foto'] template_name='change-photo.html' def get_object(self, queryset=None): if queryset is None: queryset = self.get_queryset() # This should help to get current user # Next, try looking up by primary key of Usario model. queryset = queryset.filter(pk=self.request.user.usuario.pk) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404("No user matching this query") return obj def get_success_url(self): return reverse('sistema_perfil') urls.py url(r'^change-photo/$', views.PhotoUpdate.as_view(), name='sistema_change_photo'), change_photo.html {%extends 'bases/base.html' %} {% load static %} {% load bootstrap %} {% load widget_tweaks %} {% load crispy_forms_tags %} {% block main %} <div class="container"> <div class="card text-white bg-primary mb-3"> <div class="card-header"><small class="text"> <a href="{% url 'sistema_index' %}" class="text-white ">Home /</a> <a href="{% url 'sistema_perfil' %}" class="text-white ">Perfil /</a> <a class="text-white">Foto</a> </small></a></p> Trocar a foto do perfil </div> <div class="card bg-light text-center "> <div class="card-body text-secondary text-center"> <form method="post" action="{% url 'sistema_change_photo' %}" class="form-signin" enctype="multipart/form-data"> {% csrf_token %} <div … -
how to pass variables from views to template in django
i have 3 dependent dropdownlists country city road. where the user make its selection the system works as it should. now i need to display the selections of the user on the template. how can i pass it from the view to the template ? i am sending the data from the template using ajax in json format. and i am receiving the data in views.py through httpResponse is it possible to use httpResponse as render in order to send dictionaries? home.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script>$(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; $.ajax({ type:"GET", url:'/getCity', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ result[i].name +'</option>'); }; }, }); }); </script> </head> <body> <select name="selectcountries" id="selectcountries"> {% for item in countries %} <option val="{{ item.name }}"> {{ item.name }} </option> {% endfor %} </select> <select name ="selectcities" id="selectcities"> </select> <select name ="selectroads" id="selectroads"> </select> <p>the selected country {{ selected_country }}</p> <p> the selected city {{ selected_city }}</p> <p>the selected road {{ }}</p> </body> </html> views.py def index(request): countries = … -
Django Two Factor Authentication
I have recently been reading through the documentation about django-two-factor-authentication which I found here : https://django-two-factor-auth.readthedocs.io/en/stable/installation.html The documentation is great. However, I'm trying to understand the full requirements for this solution. If I implement this package, do I then need to rely on a third party to complete this solution or can two factor authentication be achieved without a third party? My primary concern is the cost associated with plugging in to third parties. If it can be avoided, obviously I'd prefer free. If it can't be avoided, does anyone have experience with any of the third party providers offering two factor authentication? I've researched Twillio a bit but I know there are others out there who perform this service as well. Thanks in advance for any input. -
django using custom permission table
In my Django project, I have a custom user model and a custom permission model I want to add my custom permission there and use it in my project. my view class is viewset.Viewsets I have two problems: 1. how can I define for Django using my table as a permission table 2. In Django model permission I don't know how can I use this permission -
Translating dynamic content in django
I have a text that has both static and dynamic part like this. Custom message with %(card_status)s text inside I am in fix as to what the best method there is to translate the text. This is what I currently have, {% blocktrans with obj.card_status as card_status %}Custom message with {{ card_status }} text inside{% endblocktrans %} If I do that, the message generated is msgid "Custom message with %(card_status)s text inside" msgstr "This will be translated" But the problem with this approach is that, no matter what the card_status variable is, the translated text will be same. I tried enumerating the django.po file manually with msgid for each of the card_status's possible values. But that is not being considered, example, msgid "Custom message with ACTIVE text inside" msgstr "This will be translated with ACTIVE text" Can somebody suggest a method or a hack that can be used here. There are many similar questions in stack that I referred, but somehow I am not able to get the solution I require. Hope someone can put an end to this question once and for all for everybody's joy. -
Form for unique Email doesnt work in django
My class RegistrationFormUniqueEmail is there to check if the email adress is unique or not doesnt work and i dont see where my mistake is. i know i could also declare email in models unique=true but i would like to know why my code isnt working in forms.py Also how do i remove the help text from django UserCreateForm? help_text doesnt work for me. from django import forms from django.contrib.auth.forms import UserCreationForm,UserChangeForm from .models import CustomUser from django.core.exceptions import ValidationError from django.contrib.auth.forms import UserCreationForm class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['placeholder'] = 'example@example.com' self.fields['first_name'].widget.attrs['placeholder'] = 'first name' self.fields['last_name'].widget.attrs['placeholder'] = 'last name' self.fields['password1'].widget.attrs['placeholder'] = '8 characters atleast' self.fields['password2'].widget.attrs['placeholder'] = 'repeat password' class Meta(UserCreationForm.Meta): model=CustomUser fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) class CustomUserChangeForm(UserChangeForm): model=CustomUser fields=('email','password1','password2') #subclass of customusercreation class RegistrationFormUniqueEmail(CustomUserCreationForm): def clean_email(self): if CustomUser.objects.filter(email__iexact=self.cleaned_data['email']): raise ValidationError(" Email address is already in use") return self.cleaned_data['email'] -
How to bind data of model over websocket that has a field of ForeignKey type?
Basically i am binding a model over websocket.That model has a field of type ForeignKey.At the front-end i want to extract values of ForeignKey field This is my main model class Visitors(models.Model): name = models.CharField(max_length=120) ip = models.CharField(max_length=120) username = models.CharField(max_length=120) #---------other_existing_field----------------------- In this model i am making a ForeignKey relationship. Class ChatVisitors(models.Model): country = models.CharField(max_length=120) city = models.CharField(max_length=120) region = models.CharField(max_length=120) chat_visitor = models.ForeignKey('Visitors',on_delete=models.CASCADE) This is the model where i am doing WebsocketBinding. Class ChatVisitorsBinding(WebsocketBinding): model = ChatVisitors stream = "chatStream" fields = ['country','city','region','chat_visitor'] @classmethod def group_names(cls, *args, **kwargs): return ["chatting.values"] def has_permission(self, user, action, pk): return True Following is defined in consumers.py: class Demultiplexer(WebsocketDemultiplexer): consumers = { "chatStream" : ChatVisitorsBinding.consumer, } groups = ["chatting.values"] Now at the front end i am listening the data sent over websocket.Following is the script i have: var webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect("ws://my-domain/stream/"); webSocketBridge.listen(); webSocketBridge.demultiplex("chatStream", function(payload, streamName) { console.log(payload.data.country); #1 console.log(payload.data.city); #2 console.log(payload.data.region); #3 console.log(payload.data.chat_visitor.username); #4 console.log(payload.data.chat_visitor.name); #5 console.log(payload.data.chat_visitor.ip); #6 }); In console i can see correct values for #1,#2 and #3 but for #5, #6 and #7 'undefined' is being shown. Could you guide me how to fetch values in this case? Thanks in advance! -
Permanently redirect to another url in django
I have an application in django 1.5. I would like to do redirect from one address to another - permanently. That is, I want to get an effect in which I will redirect: from: domain.com/team/event-2019/01-03-2019/827 to: domain.com/team/event/01-03-2019/827 - (without 2019) I would like the event to be at the address: always under this url: domain.com/team/event/01-03-2019/827 and redirect on this url from: domain.com/team/event-2019/01-03-2019/827 Now I got an error: 'HttpResponseRedirect' object has no attribute 'find' from this place: if event_slug != activity.event.slug or str(date_url) != str(format_date(activity.date, "d-m-Y")): return HttpResponsePermanentRedirect(activity.get_absolute_url()) -
Using Django test framework to access databases from outside django shell
I'm currently working on a project that has two use cases: the first, with my client application remotely accessing my database service with some various api calls (this case works fine); the second, to allow for a locally-run client program to access a copy of my database on the local machine, without having to start up a server process, using the same api calls. I've found the following code to work from within the manage.py shell: from django.test import Client client = Client() resp = client.get("/api/call/path").json() However, I cannot get it to work from outside the manage.py parameters. I first run the following code: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DataSite.settings") django.setup() But then, when I run the snippets to get the client running, I get the following error: [exception.py:135:handle_uncaught_exception() ] Internal Server Error: /api/call/path Traceback (most recent call last): <Traceback here> OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I've attempted to follow the steps that the manage.py utility uses to start up its shell, but can't quite replicate whatever about this server is running in the background. Is there something I'm missing? Alternatively, is there a better way to … -
Django Formset: object has no attribute 'get'
I think I'm almost there, but the last part just doesn't want to work :(. I hope you can help as I'm not seeing it anymore after 2 days. Within my FormWizard I'm trying to (1) show a Formset based on a Slider Input in a previous set (setting the Extra value) and (2) in each Form within the Formset I want to show a ChoiceField (forms.Select) based on a Text-input in a previous step. With a lot of searching on stackoverflow I am able to do step 1. Step 2 is almost working, except for the fact that the ChoiceField doesn't update with the new values from the Text-input. This is my code in views.py: class FormWizardView(LoginRequiredMixin, SessionWizardView): template_name = 'test/test.html' def get_form_initial(self, step): if step == 'formset_step': form_class = self.form_list[step] data = self.get_cleaned_data_for_step('slider_step') if data is not None: # To set the extra value in formset based on slider input extra = data['number_slider'] form_class.extra = extra # To set the ChoiceField value in formset based on text-input form1_cleaned_data = self.get_cleaned_data_for_step('text_input_step') formset = form_class().forms for form in formset: if form1_cleaned_data: form.fields['text_input'].choices = [item for item in form1_cleaned_data.items()] # Print form to test if the form updates print(form) return formset …