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
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)
# ...
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)
I have a Django 1.6 app running on gunicorn with nginx. I'm getting an error intermittantly, it seems to occur on any page that writes to the database.
The error is:
Exception Value: 'module' object has no attribute '\__newobj__'
Traceback:
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/apps/cantifix-direct/products/views.py" in dispatch_product_form
359. return cls.as_view()(request)
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/contrib/formtools/wizard/views.py" in dispatch
236. response = super(WizardView, self).dispatch(request, *args, **kwargs)
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/contrib/formtools/wizard/views.py" in post
272. management_form = ManagementForm(self.request.POST, prefix=self.prefix)
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/forms/forms.py" in __init__
100. self.fields = copy.deepcopy(self.base_fields)
File "/usr/lib/python2.7/copy.py" in deepcopy
174. y = copier(memo)
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/utils/datastructures.py" in __deepcopy__
144. for key, value in self.items()])
File "/usr/lib/python2.7/copy.py" in deepcopy
174. y = copier(memo)
File "/home/django/venvs/cantifix-direct/local/lib/python2.7/site-packages/django/forms/fields.py" in __deepcopy__
188. result = copy.copy(self)
File "/usr/lib/python2.7/copy.py" in copy
88. rv = reductor(2)
Exception Type: AttributeError at /products/configure/
Exception Value: 'module' object has no attribute '__newobj__'
I'm getting this maybe 1 in 3 times of all pages that write to the database, it's very strange.
here is models from one of my apps:
https://gist.github.com/anonymous/6648fd6233717c11a462
here is my views.py
import json
from itertools import groupby
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404, render, redirect
from django.views.generic import DetailView, ListView, FormView, UpdateView
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import resolve_url
from django.conf import settings
from django.contrib.auth.views import redirect_to_login
from prices import Price
from core.utils import DistanceAwareJSONEncoder, is_expert, apply_vat
from .models import (Product, ProductCustomisation, ProductConfiguration,
PROJECT_TYPE_CHOICES, PROPERTY_TYPE_CHOICES,
OptionsRecommendation, ProductGroup)
from .mixins import ProductOptions
from sales.models import Estimate, Pallet
from . import forms
from customer.models import Address
from delivery.models import DeliveryMethod
class ProductDetailView(DetailView):
model = Product
class ProductGroupListView(ListView):
model = ProductGroup
template_name = 'products/product_groups.html'
def get_queryset(self):
return ProductGroup.objects.filter(hidden=False).order_by('name')
class ProductListView(ListView):
model = Product
template_name = 'products/product_list.html'
def get_queryset(self):
return Product.objects.filter(hidden=False,
group=self.kwargs['pk']).order_by('name')
#------------------------------------------------------------------------------
class GetRangesMixin(object):
def get_dimension_ranges(self):
return {'max_width': self.product.max_frame_width_mm,
'min_height': self.product.min_frame_height_mm,
'max_height': self.product.max_frame_height_mm,
'min_width': self.product.min_frame_width_mm}
class ProductWizardMixin(GetRangesMixin):
def get_recommended_options(self, proj_type, prop_type):
if proj_type is not None:
proj_type = str(proj_type)
if prop_type is not None:
prop_type = str(prop_type)
product = self.get_form_instance(self.steps.current).product
proj_name = dict(PROJECT_TYPE_CHOICES).get(proj_type)
prop_name = dict(PROPERTY_TYPE_CHOICES).get(prop_type)
try:
proj = product.options_recommendation.get(type=proj_type)
except OptionsRecommendation.DoesNotExist:
proj = None
try:
prop = product.options_recommendation.get(type=prop_type)
except OptionsRecommendation.DoesNotExist:
prop = None
recommendations = {}
for name in ProductOptions.get_fields():
proj_val, prop_val = (getattr(proj, name, None),
getattr(prop, name, None))
text = []
if proj_val:
text.append("project type (%s)" %proj_name.lower())
if prop_val:
text.append("property type (%s)" %prop_name.lower())
if not len(text):
continue
text = 'Recommended due to ' + ' and '.join(text)
recommendations[name] = (proj_val or prop_val, text)
return recommendations
def done(self, form_list, **kwargs):
form_data = self.get_all_cleaned_data()
session = self.request.session
self.instance.apply_option_switches()
self.instance.save()
if self.request.user.is_anonymous():
session['project_type'] = form_data.get('project_type')
session['property_type'] = form_data.get('property_type')
else:
user_profile = self.request.user.profile
user_profile.default_project_type = form_data.get('project_type')
user_profile.default_property_type = form_data.get('property_type')
user_profile.save()
approx = form_data.get('approx_dimensions', False)
session['approx_dimensions'] = approx
session['product_customisation_id'] = self.instance.id
session.save()
return redirect('products_product_summary')
def get_template_names(self):
template_name = 'products/%s_%s.html' %(self.template_prefix,
self.steps.current)
return [template_name, 'products/wizard_base.html']
#property
def product(self):
try:
return self.get_cleaned_data_for_step('product').get('product')
except:
return None
def get_form_instance(self, step):
if self.instance is None:
self.instance = ProductCustomisation(product=self.product)
return self.instance
def get_context_data(self, *args, **kwargs):
context = super(ProductWizardMixin, self).get_context_data(*args, **kwargs)
context['product'] = self.product
context['steps'] = [(s.replace('_', ' ').capitalize(), s==self.steps.current)
for s in self.steps.all]
return context
def get_form_initial(self, step):
data = super(ProductWizardMixin, self).get_form_initial(step)
data['user'] = self.request.user
if step == self.project_type_step:
if self.request.user.is_anonymous():
data['project_type'] = self.request.session.get('project_type',None)
data['property_type'] = self.request.session.get('property_type',None)
else:
data['project_type'] = self.request.user.profile.default_project_type
data['property_type'] = self.request.user.profile.default_property_type
if step == 'product':
data['product_id'] = self.request.GET.get('product')
return data
#------------------------------------------------------------------------------
class GuidedView(ProductWizardMixin, SessionWizardView):
template_prefix = 'guided'
approx_dimensions_step = 2
project_type_step = 'project_type'
instance = None
_product = None
_recommendations = None
form_list = [
('project_type', forms.ProjectTypeForm),
('product', forms.ProductForm),
('dimensions', forms.DimensionsForm),
('configuration', forms.ConfigurationForm),
('options', forms.OptionsForm),
]
def get_form_initial(self, step):
data = super(GuidedView, self).get_form_initial(step)
if step == "configuration":
form_data = self.get_cleaned_data_for_step('dimensions')
data['width'] = form_data['width']
elif step == 'product':
form_data = self.get_cleaned_data_for_step(self.project_type_step)
if form_data:
data['project_type'] = form_data['project_type']
data['property_type'] = form_data['property_type']
elif step == "options":
for name, (val, _) in self.recommendations.items():
data[name] = val
return data
#property
def recommendations(self):
if self._recommendations is None:
product = self.get_form_instance('options').product
form_data = self.get_cleaned_data_for_step('project_type')
proj_type = form_data['project_type']
prop_type = form_data['property_type']
self._recommendations = self.get_recommended_options(
proj_type,
prop_type
)
return self._recommendations
def get_context_data(self, form, **kwargs):
context = super(GuidedView, self).get_context_data(form,**kwargs)
if self.steps.current == 'dimensions':
context['ranges'] = self.get_dimension_ranges()
if self.steps.current == 'options':
form_data = [(form[field], self.recommendations.get(field, None))
for field in form.fields]
context['form_data'] = form_data
return context
#------------------------------------------------------------------------------
class ExpertView(ProductWizardMixin, SessionWizardView):
template_prefix = 'expert'
approx_dimensions_step = 1
project_type_step = 'customisation'
_product = None
instance = None
form_list = [
('product', forms.ProductForm),
('customisation', forms.ExpertForm),
]
def get_context_data(self, form, **kwargs):
context = super(ExpertView, self).get_context_data(form, **kwargs)
if self.steps.current == 'customisation':
context['ranges'] = self.get_dimension_ranges()
return context
def post(self, request, *args, **kwargs):
if not request.is_ajax():
return super(ExpertView, self).post(request, *args, **kwargs)
proj_type = request.POST.get('customisation-project_type')
prop_type = request.POST.get('customisation-property_type')
recommendations = self.get_recommended_options(proj_type, prop_type)
return HttpResponse(json.dumps(recommendations),
content_type='application/json')
#------------------------------------------------------------------------------
class ProductSummaryView(FormView):
form_class = forms.SummaryForm
template_name = 'products/summary.html'
#property
def approx_dimensions(self):
return self.request.session.get('approx_dimensions', False)
def get_initial(self):
self.custom = get_custom(self.request)
return {'user': self.request.user,
'address': self.request.GET.get('address'),
'method': self.request.GET.get('method', 1)}
def form_valid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
context = super(ProductSummaryView, self).get_context_data(**kwargs)
form = kwargs['form']
approx_dimensions = self.approx_dimensions
context['user'] = self.request.user
context['custom'] = self.custom
context['total_cost'] = self.custom.total_price
context['approx_dimensions'] = approx_dimensions
form_data = getattr(form, 'cleaned_data', None)
if form_data and not form.errors:
method = form_data.get('delivery_method')
delivery = self.estimate_delivery(
method,
address=form_data.get('delivery_address'),
postcode=form_data.get('delivery_postcode')
)
else:
method = DeliveryMethod.objects.get(id=1).name.lower()
delivery = Price(0, currency='GBP')
context['delivery_method'] = method
context['delivery_price'] = delivery
return context
def estimate_delivery(self, method, address=None, postcode=None):
if address is None:
address = '%s, UK' %postcode
backend = method.get_backend()(
destination=address,
num_items=1, # TODO only one item per product?
weight=self.custom.total_weight,
longest_length=self.custom.longest_length_mm
)
val = backend.get_charge_excl_tax()
return Price(net=val, gross=apply_vat(val), currency='GBP')
#------------------------------------------------------------------------------
class EditProductViewBase(UpdateView, GetRangesMixin):
model = ProductCustomisation
form_class = forms.ExpertForm
template_name = 'products/expert_customisation.html'
def get_initial(self, **kwargs):
return {'user': self.request.user,
'approx_dimensions': self.approx_dimensions}
#property
def reverse_args(self):
return None
def get_success_url(self):
return reverse(self.reverse_url, kwargs=self.reverse_args)
def form_valid(self, form):
form.instance.apply_option_switches()
return super(EditProductViewBase, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(EditProductViewBase, self).get_context_data(**kwargs)
self.product = self.object
context['ranges'] = self.get_dimension_ranges()
context['cancel_url'] = self.get_success_url()
return context
class EditProductView(EditProductViewBase):
reverse_url = 'products_product_summary'
#property
def approx_dimensions(self):
approx = self.request.session.get('approx_dimensions', 'approx')
return 'approx' if approx else 'exact'
def get_object(self, queryset=None):
return get_custom(self.request)
#------------------------------------------------------------------------------
def dispatch_product_form(request):
if request.GET.has_key('mode'):
cls = None
if request.GET['mode'] == 'guided':
cls = GuidedView
elif request.GET['mode'] == 'expert':
cls = ExpertView
if cls is not None:
return cls.as_view()(request)
product = request.GET.get('product')
query = 'mode=guided%s' %('&product=%s'%product if product is not None
else '')
return redirect('%s?%s' %(reverse('products_product_configure'), query))
#------------------------------------------------------------------------------
def get_custom(request):
custom_id = request.session.get('product_customisation_id', None)
return get_object_or_404(ProductCustomisation, id=custom_id)
def remove_custom(request):
request.session.pop('product_customisation_id', None)
#login_required
def create_estimate(request):
return add_for_model(Estimate, request)
#login_required
def create_pallet(request):
return add_for_model(Pallet, request)
#login_required
def add_to_estimate(request, estimate=None):
return add_for_model(Estimate, request, estimate)
#login_required
def add_to_pallet(request, pallet=None):
return add_for_model(Pallet, request, pallet)
def add_for_model(model, request, id=None):
custom = get_custom(request)
kwargs = {}
if model == Estimate:
kwargs['approx_dimensions'] = request.session.get(
'approx_dimensions',
False
)
if id is not None:
obj = get_object_or_404(model, id=id)
if obj.user!=request.user:
raise PermissionDenied
else:
obj = model.objects.create(user=request.user)
obj.add_item(custom, **kwargs)
remove_custom(request)
return redirect(reverse('sales_user_%s_detail' %model.__name__.lower(),
args=(obj.id,)))
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.