django __init__() got an unexpected keyword argument 'param' - python

My View.py
class AccountCreate(RequestPassingFormViewMixin, MyCreateView):
template_name = 'dashboard/account_form.html'
form_class = AccountForm
model = Account
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(AccountCreate, self).get_form_kwargs(*args, **kwargs)
common = get_object_or_404(Common, pk=self.kwargs['common_pk'])
combination_price = Account(common=common)
kwargs['instance'] = combination_price
return kwargs
def get_success_url(self):
return reverse('dashboard_account_list', kwargs={'chain_pk': self.object.chain.id})
def form_valid(self, form):
self.object = form.save(commit=False)
discount = form.cleaned_data['discount']
account_list = form.cleaned_data['account_list']
self.object.common = get_object_or_404(Common, pk=self.kwargs['common_pk'])
code = Account.get_code(self.object.common, account_list, discount)
self.object.code = code
self.object.save()
form.save_m2m()
return redirect(self.get_success_url())
and this is my form.py file
class AccountForm(autocomplete_light.ModelForm):
class Meta:
model = Account
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(AccountForm, self).__init__(*args, **kwargs)
common = Common.objects.get(pk=self.request.session.get('common_pk'))
products = Account.objects.filter(chain=chain)
form.fields['discount'].queryset = Discount.objects.filter(product__in=products)
form.fields['account_list'].queryset = AccountList.objects.filter(common=common)
def clean(self):
cleaned_data = super(AccountForm, self).clean()
discount = cleaned_data['discount']
if len(discount) <= 1:
self._errors["discount"] = self.error_class(['Choose at least two discount'])
return cleaned_data
account_list = cleaned_data['account_list']
common = Common.objects.get(pk=self.request.session.get('common_pk'))
code =Account.get_code(common, account_list, discount)
if not self.instance or (self.instance.code != code or self.instance.account_list != account_list):
if Account.objects.filter(code=code, account_list=account_list).exists():
msg1 = 'Already exists'
self._errors["discount"] = self.error_class([msg1])
return cleaned_data
I am tryng to add auto suggest option in my m2m field.I have added autocomplete in my form.py file.
But the problem is that,after adding autocomplete in the form,i am facing the error.

i have found the solution,in my forms,the __init__ method don't have the 'param' keyword argument,so i have rewrite my form.py something like this,adding self.param = kwargs.pop("param") and its worked.
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
self.param = kwargs.pop("param")
super(CombinationPriceForm, self).__init__(*args, **kwargs)
chain = Chain.objects.get(pk=self.request.session.get('chain_pk'))
products = Product.objects.filter(chain=chain)
self.fields['variants'].queryset = Variant.objects.filter(product__in=products)
self.fields['price_list'].queryset = PriceList.objects.filter(chain=chain)

Related

Pass kwarg into an inlineformset_factory?

I am trying to pass the request object into my inlineformset_factory and am struggling to accomplish this.
In forms.py I have the following:
class SummativeScoreForm(forms.ModelForm):
"""
Form definition for SummativeScore Form
"""
subdomain_proficiency_level = forms.ModelChoiceField(
empty_label="Undecided",
queryset=SubdomainProficiencyLevel.objects.none(),
widget=forms.RadioSelect,
required=False,
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super(SummativeScoreForm, self).__init__(*args, **kwargs)
if self.instance:
if self.request.user == self.instance.summative.employee:
self.fields["subdomain_proficiency_level"].disabled = True
self.fields[
"subdomain_proficiency_level"
].queryset = SubdomainProficiencyLevel.objects.filter(
subdomain=self.instance.subdomain
)
self.fields[
"subdomain_proficiency_level"
].label = f"""
{self.instance.subdomain.character_code}:
{self.instance.subdomain.short_description}
"""
class Meta:
model = SummativeScore
fields = "__all__"
widgets = {
"subdomain_proficiency_level": forms.RadioSelect(
attrs={"class": "list-unstyled"}
),
}
SummativeScoreInlineFormset = inlineformset_factory(
Summative,
SummativeScore,
fields=("subdomain_proficiency_level",),
can_delete=False,
extra=0,
form=SummativeScoreForm,
)
I'm using a FormView CBV to show this inline_formset
class SummativeScoreFormView(
LoginRequiredMixin,
UserIsObserverOrObserveeMixin,
SingleObjectMixin,
FormView,
):
model = Summative
template_name = "commonground/summative_score_form.html"
pk_url_kwarg = "summative_id"
def get(self, request, *args, **kwargs):
summative_id = kwargs.pop("summative_id")
self.object = self.get_object(
queryset=Summative.objects.filter(id=summative_id)
)
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
summative_id = kwargs.pop("summative_id")
self.object = self.get_object(
queryset=Summative.objects.filter(id=summative_id)
)
return super().get(request, *args, **kwargs)
def get_form(self, form_class=None):
return SummativeScoreInlineFormset(
**self.get_form_kwargs(), instance=self.object
)
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["request"] = self.request
return kwargs
def form_valid(self, form):
form.save()
messages.add_message(messages.SUCCESS, "Changes were saved!")
HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form):
print("invalid form")
return super().form_invalid(form)
def get_success_url(self):
user_id = self.kwargs["user_id"]
summative_id = self.kwargs["summative_id"]
return reverse(
"commonground:summative_detail",
kwargs={
"user_id": user_id,
"summative_id": summative_id,
},
)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
summative = get_object_or_404(
Summative, pk=self.kwargs["summative_id"]
)
context["summative"] = summative
return context
I keep getting this error:
__init__() got an unexpected keyword argument 'request'
I'm not sure how best to resolve this - any ideas? Is there a clear way to pass the request to the inlineformset_factory?
You are passing the request to the formset and not to the forms in the formset, hence you get the error. For passing custom parameters to the formsets forms [Django docs] you need to pass a form_kwargs parameter to the formset:
class SummativeScoreFormView(
LoginRequiredMixin,
UserIsObserverOrObserveeMixin,
SingleObjectMixin,
FormView,
):
...
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['form_kwargs'] = {'request': self.request}
return kwargs

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

ModelForm in Django

ModelForm:
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ChapterCreateForm, self).__init__(*args, **kwargs)
Not working
I wanna add self.field other. But it not working.
This is my code:
class ChapterCreateForm(ModelForm):
class Meta:
model = Chapter
exclude = ('user', 'book',)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ChapterCreateForm, self).__init__(*args, **kwargs)
def clean_title(self):
title = self.cleaned_data['title']
if Chapter.objects.filter(user=self.user, title=title).exists():
raise forms.ValidationError('THIS CHAPTER ALREADY WRITTEN')
return title
But this form it's working:
class BookCreateForm(ModelForm):
class Meta:
model = Book
exclude = ('user',)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(BookCreateForm, self).__init__(*args, **kwargs)
def clean_title(self):
title = self.cleaned_data['title']
if Book.objects.filter(title=title).exists():
if Book.objects.filter(user=self.user, title=title).exists():
raise forms.ValidationError('YOU WROTE THIS BOOK ')
raise forms.ValidationError('THIS BOOK ALREADY WRITTEN')
return title
Please help me. Thanks so much
You need to pass user in the form kwargs by overriding get_form_kwargs in the class UserCreateChapterView as below:
class UserCreateChapterView(UserPassesTestMixin, CreateView):
...
...
def get_form_kwargs(self):
kwargs = super(UserCreateChapterView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
Now you can use kwargs.pop('user') in the __init__ method of ChapterCreateForm and it should work.
Hope it helps!

Building tags plugin for django-wiki using django-taggit. Cannot save with .save_m2m() - type object has no attribute 'save_m2m'

I am building a custom tags plugin for django-wiki using django-taggit to save tags. I cannot save the form with .save_m2m as it says in the django-taggit docs. The tags can be saved in the admin but not through the fronted form because I cant save with .save_m2m(). I get the following error even after the form has been saved. Any help would be appreciated.
type object 'SidebarForm' has no attribute 'save_m2m'
wiki_plugins.py
class TagPlugin(BasePlugin):
slug = settings.SLUG
sidebar = {
'headline': _('Tags'),
'icon_class': 'fa-picture-o',
'template': 'sidebar.html',
'form_class': forms.SidebarForm,
'get_form_kwargs': (lambda a: {'instance': models.Tag(article=a)})
}
models.py
class TagRevision(RevisionPluginRevision):
def can_write(self, user):
if not settings.ANONYMOUS and (not user or user.is_anonymous()):
return False
return RevisionPlugin.can_write(self, user)
def can_delete(self, user):
return self.can_write(user)
class Meta:
verbose_name = _('tag')
verbose_name_plural = _('tags')
db_table = 'wiki__plugins_tags_tag' # Matches label of upcoming 0.1 release
if settings.APP_LABEL:
app_label = settings.APP_LABEL
def __str__(self):
if self.current_revision:
return ugettext('Tag: %s') % self.current_revision.tagrevision
else:
return ugettext('Current revision not set!!')
#python_2_unicode_compatible
class TagRevision(RevisionPluginRevision):
tags = TaggableManager()
def inherit_predecessor(self, tag):
"""
Inherit certain properties from predecessor because it's very
convenient. Remember to always call this method before
setting properties :)"""
predecessor = tag.current_revision.tagrevision
self.plugin = predecessor.plugin
self.deleted = predecessor.deleted
self.locked = predecessor.locked
self.tag = predecessor.tag
if not skip_image_file:
try:
self.tags = predecessor.tags
except IOError:
self.tags = None
class Meta:
verbose_name = _('tag revision')
verbose_name_plural = _('tag revisions')
# Matches label of upcoming 0.1 release
db_table = 'wiki_plugins_tags_tagrevision'
if settings.APP_LABEL:
app_label = settings.APP_LABEL
ordering = ('-created',)
def __str__(self):
return ugettext('Tag Revsion: %d') % self.revision_number
forms.py
from wiki_plugins_tags import models
class SidebarForm(PluginSidebarFormMixin):
def __init__(self, article, request, *args, **kwargs):
self.article = article
self.request = request
super(SidebarForm, self).__init__(*args, **kwargs)
self.fields['tags'].required = True
def save(self, *args, **kwargs):
if not self.instance.id:
tagged = models.Tag()
tagged.article = self.article
kwargs['commit'] = False
revision = super(SidebarForm, self).save(*args, **kwargs)
revision.set_from_request(self.request)
tagged.add_revision(self.instance, save=True)
return revision
return super(SidebarForm, self).save(*args, **kwargs)
class Meta:
model = models.TagRevision
fields = ('tags',)
class RevisionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.tags = kwargs.pop('tags')
self.request = kwargs.pop('request')
super(RevisionForm, self).__init__(*args, **kwargs)
self.fields['tags'].required = True
def save(self, *args, **kwargs):
if not self.instance.id:
kwargs['commit'] = False
revision = super(RevisionForm, self).save(*args, **kwargs)
revision.inherit_predecessor(self.tags, skip_image_file=True)
revision.deleted = False # Restore automatically if deleted
revision.set_from_request(self.request)
self.tags.add_revision(self.instance, save=True)
return revision
return super(RevisionForm, self).save(*args, **kwargs)
class Meta:
model = models.TagRevision
fields = ('tags',)

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