__init__() got multiple values for argument 'crescator' - python

I have a ModelForm and in a ModelChoiceField I need to filter objects by request.user. When data is submitted, I got the error "init() got multiple values for argument 'crescator' ". How can I repair that?
#My Form
class AdaugaPereche(forms.ModelForm):
boxa = forms.IntegerField(label="Boxa", min_value=1)
sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year)
mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul")
femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela")
serie_pui_1 = forms.TextInput()
serie_pui_2 = forms.TextInput()
culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea",
required=False)
culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea",
required=False)
data_imperechere = forms.DateInput()
primul_ou = forms.DateInput()
data_ecloziune = forms.DateInput()
data_inelare = forms.DateInput()
comentarii = forms.TextInput()
# Functie pentru filtrarea rezultatelor dupa crescator
def __init__(self, crescator, *args, **kwargs):
super(AdaugaPereche, self).__init__(*args, **kwargs)
self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul",
perechi_masculi__isnull=True)
self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă",
perechi_femele__isnull=True)
self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
class Meta:
model = Perechi
fields = "__all__"
#My view
def perechenoua(request):
if request.method == "POST":
form = AdaugaPereche(request.POST, crescator=request.user)
if form.is_valid():
obj = form.save(commit=False)
obj.crescator = request.user
obj.save()
return HttpResponseRedirect("/perechi/")
else:
form = AdaugaPereche(crescator=request.user)
context = {
'form': form
}
template = loader.get_template("adauga-pereche.html")
return HttpResponse(template.render(context, request))
May the problem be obj = form.save(commit=False) obj.crescator = request.user obj.save() ?

The __init__ function of the form signature takes as first parameter here crescator, but you pass request.POST as that parameter, and furthermore you also pass this as a named parameter. By reordening the parameter, this should work:
class AdaugaPereche(forms.ModelForm):
# ...
def __init__(self, *args, crescator=None, **kwargs):
super(AdaugaPereche, self).__init__(*args, **kwargs)
self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul",
perechi_masculi__isnull=True)
self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă",
perechi_femele__isnull=True)
self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
# ...

Related

Unable to Update InlineFormset in Django with CBV

class PreChildrenView(CreateView):
model = PreDealDetails2
template_name = 'cam_app/children_form.html'
fields = '__all__'
success_url = reverse_lazy('forms_app:deal-entering')
session_initial = 'children_'
def get_initial(self,**kwargs):
initial = super(PreChildrenView, self).get_initial(**kwargs)
initial['deal_id'] = self.request.session['deal_id']
return initial
def get_context_data(self, **kwargs):
data = super(PreChildrenView, self).get_context_data(**kwargs)
if self.request.POST:
data['childrens'] = ChildrenFormSet(self.request.POST)
print('post')
else:
print('get')
data['childrens'] = ChildrenFormSet()
data['childrens'].extra = 5
data['info'] = 'Children Details'
return data
def form_valid(self, form):
print('wwwww')
context = self.get_context_data()
childrens = context['childrens']
if form.is_valid():
pass
if childrens.is_valid():
count = 0
self.object = form.save()
childrens.instance = self.object
childrens.save()
self.request.session[self.session_initial + 'children_count'] = count
self.request.session['valid_children'] = True
messages.success(self.request, 'Successfully filled Children Details')
return self.render_to_response(self.get_context_data(form=form))
else:
return super(PreChildrenView, self).form_invalid(form)
class UpdatePreChildrenView(UpdateView):
model = PreDealDetails2
template_name = 'cam_app/children_form.html'
fields = '__all__'
success_url = reverse_lazy('forms_app:deal-entering')
session_initial = 'children_'
def get_object(self, queryset=None):
return PreDealDetails2(deal_id = self.request.session['deal_id'])
def get_context_data(self, **kwargs):
data = super(UpdatePreChildrenView, self).get_context_data(**kwargs)
if self.request.POST:
a = PreDealDetails2.objects.get(deal_id = self.request.session['deal_id'])
data['childrens'] = ChildrenFormSet(self.request.POST)
print('post')
else:
print('get')
data['childrens'] = ChildrenFormSet(instance=self.object)
data['childrens'].extra = 5
data['info'] = 'Children Details'
return data
def form_valid(self, form):
print('update valid')
context = self.get_context_data()
childrens = context['childrens']
if form.is_valid():
print('wejri')
self.object =form.save()
if childrens.is_valid():
childrens.instance = self.object
childrens.save()
count = 0
self.request.session[self.session_initial + 'children_count'] = count
self.request.session['valid_children'] = True
messages.success(self.request, 'Successfully filled Children Details')
return self.render_to_response(self.get_context_data(form=form))
else:
return super(UpdatePreChildrenView, self).form_invalid(form)
else:
print('sfeief')
class PreChildrenRedirectView(RedirectView):
def get_redirect_url(self):
flag = 0
try:
PreDealDetails2.objects.get(deal_id=self.request.session['deal_id'])
flag = 1
except:
pass
if flag == 1:
return reverse("cam_app:update-prechildren-view")
else:
return reverse("cam_app:create-prechildren-view")
I am using above code to enter details to form and later update form.
CreateView is working fine and saving data.
UpdateView is displaying data. When i try to save updateview it is showing following error :-
Code Flow :-
First PreChildrenRedirectView is called. It checks if data already exist or not. If it does then Updateview is called and if it doesnot exist then Createview is called.
I am not using slug. Instead i am using get_object in Updateview. Let me know what is causing problem or how to solve the error.
Update
I have changed the forms.py to remove the error in child. But Deal Id is still showing error. I am also attaching the forms.py below
class ChildrenForm(forms.ModelForm):
class Meta:
model = PreChildrenDetails
fields = '__all__'
def __init__(self, *args, **kwargs):
super(ChildrenForm, self).__init__(*args, **kwargs)
self.fields['deal_id'].widget.attrs['readonly'] = True
self.helper = FormHelper(self)
self.helper.form_show_labels = False
def clean(self):
print('wow')
pass
ChildrenFormSet = inlineformset_factory(PreDealDetails2,PreChildrenDetails, form=ChildrenForm, fields = '__all__', extra=1)
Below is screenshot of error after updating

How to get the ChoiceField value from a form in Django?

I want to get the chosen email-id from a drop down list made from ChoiceField. I have written a code but apparently it is not working.
How do I do it ?
Here is my views.py
#login_required
def assign(request):
if request.method == 'POST':
assign_now = AssignTask(data=request.POST, user=request.user)
if assign_now.is_valid():
task_title = assign_now.cleaned_data.get('title')
task_description = assign_now.cleaned_data.get('desc')
assign_email = assign_now.cleaned_data('assign_to')
assign_email = dict(AssignTask.fields['assign_to'].choices)[assign_email]
user_details = User.objects.get(email=assign_email)
t = Task(title=task_title, description=task_description, assigned_to=user_details)
t.save()
return HttpResponse('<h2>Successfully assigned task</h2>')
else:
return HttpResponse('<h2><Task assignment failed/h2>')
else:
return HttpResponse('<h2>Request method error</h2>')
Here is my forms.py
class AssignTask(forms.Form):
title = forms.CharField(max_length=200)
description = forms.CharField(widget=forms.Textarea)
assign_to = forms.ChoiceField(widget=forms.Select(choices=[]))
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
user_email = self.user.email.split('#')[1]
super(AssignTask, self).__init__(*args, **kwargs)
self.fields['assign_to'] = forms.ChoiceField(choices=[(i.email, i.email) for i in User.objects.filter(is_active=True, email__icontains=user_email)])
Error that I am getting is:
File "/home/gblp250/PycharmProjects/assignment/todoapp/views.py" in assign
118. assign_email = assign_now.cleaned_data('assign_to')
Exception Type: TypeError at /assign
Exception Value: 'dict' object is not callable
From the error traceback, We can understand, you are missing a .get() function
so, try this,
assign_email = assign_now.cleaned_data.get('assign_to')
instead of
assign_email = assign_now.cleaned_data('assign_to')
complete view function
#login_required
def assign(request):
if request.method == 'POST':
assign_now = AssignTask(data=request.POST, user=request.user)
if assign_now.is_valid():
task_title = assign_now.cleaned_data.get('title')
task_description = assign_now.cleaned_data.get('desc','Sample Description')
assign_email = assign_now.cleaned_data.get('assign_to')
user_details = User.objects.get(email=assign_email)
t = Task(title=task_title, description=task_description, assigned_to=user_details)
t.save()
return HttpResponse('<h2>Successfully assigned task</h2>')
else:
return HttpResponse('<h2><Task assignment failed/h2>')
else:
return HttpResponse('<h2>Request method error</h2>')

DeclarativeFieldsMetaclass object argument after ** must be a mapping, not int

I am trying to pass kwargs to my forms.py file, when the form is loaded I get an error saying my car_id is not defined on my forms.py file. I know this is because of the below line of code but I do not know how to fix it.
form = SelectCarModelForm()
forms.py
def __init__(self, *args, **kwargs):
self.car_id = kwargs.pop('car_id', None)
super(SelectCarModelForm, self).__init__(*args, **kwargs)
self.fields['car_model'] = forms.ModelChoiceField(
empty_label = "Select a Model",
queryset = CarModel.objects.filter(model=car_id),
widget = Select(attrs={'class': 'span12 small-margin-top small-margin-bottom'}),
required=True
)
view
if request.method == "POST":
form = SelectCarModelForm(request.POST)
if form.is_valid():
model = form.cleaned_data['car_model']
# Go to the next form in the process.
return redirect('view_car')
# Initial form
else:
form = SelectCarModelForm()
return render(
request,
template_name = 'cars/forms/view_car_models.html',
dictionary = {
'form':form,
}
)
You either do this:
# pass a `car_id` value when instantiating the form
form = SelectCarModelForm(car_id=<some_value>)
and if that's not feasible, maybe this:
def __init__(self, *args, **kwargs):
self.car_id = kwargs.pop('car_id', None)
super(SelectCarModelForm, self).__init__(*args, **kwargs)
if self.car_id is not None:
self.fields['car_model'] = forms.ModelChoiceField(
empty_label = "Select a Model",
queryset = CarModel.objects.filter(model=car_id),
widget = Select(attrs={'class': 'span12 small-margin-top small-margin-bottom'}),
required=True
)
else:
self.fields['car_model'] = forms.ModelChoiceField(
empty_label = "Select a Model",
queryset = CarModel.objects.filter(model=<SOME-OTHER-CRITERIA),
widget = Select(attrs={'class': 'span12 small-margin-top small-margin-bottom'}),
required=True
)

Django form not inserting form values

I have a from created which is generated by a model. I can save the form, but the form data is not inserted into the table. The insert occurs, but with blank data. Any help would be greatly appreciated.
models.py
class HelpDefinition(models.Model):
org = models.IntegerField(default=0)
help_type = models.CharField(max_length=255)
help_content = models.TextField(blank=True)
def __unicode__(self):
return self.name
views.py
def index(request, org_id=None):
help_def = HelpDefinition()
if org_id:
help_def = HelpDefinition.objects.get(org=org_id)
if request.method == 'POST':
form = FormHelp(request.POST)
if form.is_valid():
help_def.save()
messages.success(request, 'Saved!')
else:
messages.error(request, 'Ugh')
else:
form = FormHelp(request=request, initial=initial_data)
return {
'form': form,
}
forms.py
class FormHelp(forms.Form):
org = forms.CharField(widget=forms.HiddenInput, required=True)
help_type = forms.ChoiceField(abel='Text', required=True)
help_content = forms.CharField(label='Description', required=True, widget=forms.Textarea)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(FormHelp, self).__init__(*args, **kwargs)
Due that you dont use ModelForm, you need to set your attributes one by one.
if request.method == 'POST':
form = FormHelp(request.POST)
if form.is_valid():
help_def.org = form.cleaned_data.get("org")
help_def.help_type = form.cleaned_data.get("help_type")
help_def.help_type = form.cleaned_data.get("help_content")
help_def.save()

Django, change username form

I'm trying to create a modelform to allow users to change their username. I'm trying to do this using FormView instead of UpdateView because I want to include other forms (user management functionality) in this view eventually.
Relevant forms.py:
class FormHorizontalModelForm(forms.ModelForm)
def __init__(self, *args, **kwargs):
super(FormHorizontalModelForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
class PlayerRenameForm(FormHorizontalModelForm):
def __init__(self, user, *args, **kwargs):
super(PlayerRenameForm, self).__init__(*args, **kwargs)
self.helper.add_input(Submit('change_username', 'Change Username'))
class Meta:
model = User
fields = ('username',)
def save(self):
pass # I figured this might be saving the object since this is inherited off ModelForm
def form_valid(self, form):
self.change_username(new_username = self.cleaned_data['username'])
# self.send_email(new_username = self.cleaned_data['username'])
def change_username(self, new_username):
player = Player.objects.get(user = self.instance)
self.instance.username = new_username
self.instance.save()
player.changed_username = True
player.save()
views.py
class AccountView(UserAuthenticationMixin, FormView):
template_name = 'game/profile.html'
success_url = '/accounts/'
form_class = PlayerRenameForm
form_class_two = CrispyPasswordSetForm
form_class_three = CrispyPasswordChangeForm
def get_context_data(self, **kwargs):
context = super(AccountView, self).get_context_data(**kwargs)
if 'form' not in context:
context['form'] = self.form_class(user = self.request.user, data = (self.request.POST or None))
if 'password_set_form' not in context:
context['password_set_form'] = self.form_class_two(user = self.request.user, data = (self.request.POST or None))
if 'password_change_form' not in context:
context['password_change_form'] = self.form_class_three(user = self.request.user, data = (self.request.POST or None))
return context
def form_invalid(self, **kwargs):
return self.render_to_response(self.get_context_data(**kwargs))
def get_form(self, form_class):
return form_class(user = self.request.user, **self.get_form_kwargs())
def post(self, request, *args, **kwargs):
if 'change_username' in request.POST:
form = self.form_class(user = request.user, instance = request.user, data = self.request.POST)
form_name = 'form'
elif 'set_password' in request.POST:
form = self.form_class_two(user = request.user, data = self.request.POST)
form_name = 'password_set_form'
elif 'change_password' in request.POST:
form = self.form_class_three(user = request.user, data = self.request.POST)
form_name = 'password_change_form'
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(**{form_name: form})
The form returns valid, and returns to success_url. I know for a fact that it is passing into the correct part of the post function since I have stripped away the other parts to ensure that was working.

Categories