Restarting FormWizard from done method - django

I'm trying use the FormWizard for to submit an order "charge" in wizard done method. Extending the example in the documentation, performing the credit card "charge" in the done means you can't go back and reprompt for credit card, because the wizard performs self.storage.reset() after calling the done method.
What is the right approach? The confirmation form clean() step is called multiple times for revalidation, etc, & seems too removed from done() where all validated forms are available.
Thanks for any pointers.
Kent

I could think of this:
In done() method you will be charging the user. If its declined/failed, save each forms data in session/cookies.
Restart the wizard from specific step where payment info is taken. NamedUrlWizard might be helpful.
Implement your get_form_intial() to return data from session/cookies for the step.
However, I think validation of this may fail as skipped steps do not have data. So you may have to do some more to get pass that.

I guess the answer is "you can't get there from here". I opened a ticket #19189, but it's unclear this feature will be added.

Here is my solution:
1. extend WizardView, modify render_done method to catch exception in it:
- detailed description
from django.contrib.formtools.wizard.views import SessionWizardView
class MySessionWizardView(SessionWizardView):
def __init__(self, **kwargs):
super(MySessionWizardView, self).__init__(**kwargs)
self.has_errors = False
class RevalidationError(Exception):
def __init__(self, step, form, **kwargs):
self.step = step
self.form = form
self.kwargs = kwargs
def __repr__(self):
return '%s(%s)' % (self.__class__, self.step)
__str__ = __repr__
def render_done(self, form, **kwargs):
final_form_list = []
for form_key in self.get_form_list():
form_obj = self.get_form(step=form_key,
data=self.storage.get_step_data(form_key),
files=self.storage.get_step_files(form_key))
if not form_obj.is_valid():
return self.render_revalidation_failure(form_key, form_obj, **kwargs)
final_form_list.append(form_obj)
try:
done_response = super(MySessionWizardView, self).render_done(form, **kwargs)
except self.RevalidationError as e:
return self.render_revalidation_failure(e.step, e.form, **e.kwargs)
self.storage.reset()
return done_response

Related

Django Detailview Error Handling

I have a scenario where I am trying to send different messages to the user in the event that they are not authorized to see a record or if the record does not exist. I have been able to get the interface to send a message to the user if a 404 occurs, but can't quite figure out the logic based on criteria of the record. I've been playing with get, get_object, or get_object_or_404 and nothing quite works.
Here is my DetailView..
class BookSearchDetailView(LoginRequiredMixin,DetailView):
model = Book
context_object_name = 'book_detail'
template_name = 'book/book_search_detail.html'
def get_object(self, queryset=None):
return get_object_or_404(Book, book_number=self.request.GET.get("q"))
def get(self, request, *args, **kwargs):
book_number=self.request.GET.get("q")
try:
self.object = self.get_object()
except Http404:
messages.add_message(self.request, messages.INFO, 'Book Number %s Not Found' % book_number )
return HttpResponseRedirect(reverse('Book:book_number_search'))
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
except Not a Preference:
Book_number exists but is not self.request.user.preferences.all()
I realize the except Not a Preference doesn't work, but I am illustrating what I am trying to do.
Here is my model.
class Book(models.Model):
book_name = models.CharField(max_length=80,null=True,unique=False)
book_number = models.IntegerField(editable=True,null=True)
Note I do not have a slug defined to my model. In the current code above, this doesn't cause any problems. When I have played with different code variations, one of the error messages I get is that DetailView must be called with a pk or a slug.
I am ultimately trying to filter the book so that if the user doesn't have attributes to allow them to see the book it would essentially return none.
I have also tried to override get_queryset, but when I use the code below,
def get_queryset(self):
queryset = super(BookSearchDetailView, self).get_queryset()
return queryset.filter(book_number__in=self.request.user.preferences.all())
However, when I define the code above, my DetailView does not seem to honor it or have any effect.
What I've read is that the get_object either gets the object or 404. I've got that piece work working fine. Just can't figure out how to incorporate a third variation of error message.
Thanks in advance for any thoughts.

Overridden save() method behavior not using super().save() method

I have a model with a customized save() method that creates intermediate models if the conditions match:
class Person(models.Model):
integervalue = models.PositiveIntegerField(...)
some_field = models.CharField(...)
related_objects = models.ManyToManyField('OtherModel', through='IntermediaryModel')
...
def save(self, *args, **kwargs):
if self.pk is None: # if a new object is being created - then
super(Person, self).save(*args, **kwargs) # save instance first to obtain PK for later
if self.some_field == 'Foo':
for otherModelInstance in OtherModel.objects.all(): # creates instances of intermediate model objects for all OtherModels
new_Intermediary_Model_instance = IntermediaryModel.objects.create(person = self, other = otherModelInstance)
super(Person, self).save(*args, **kwargs) #should be called upon exiting the cycle
However, if editing an existing Person both through shell and through admin interface - if I alter integervalue of some existing Person - the changes are not saved. As if for some reason last super(...).save() is not called.
However, if I were to add else block to the outer if, like:
if self.pk is None:
...
else:
super(Person, self).save(*args, **kwargs)
the save() would work as expected for existing objects - changed integervalue is saved in database.
Am I missing something, or this the correct behavior? Is "self.pk is None" indeed a valid indicator that object is just being created in Django?
P.S. I am currently rewriting this into signals, though this behavior still puzzles me.
If your pk is None, super's save() is called twice, which I think is not you expect. Try these changes:
class Person(models.Model):
def save(self, *args, **kwargs):
is_created = True if not self.pk else False
super(Person, self).save(*args, **kwargs)
if is_created and self.some_field == 'Foo':
for otherModelInstance in OtherModel.objects.all():
new_Intermediary_Model_instance = IntermediaryModel.objects.create(person = self, other = otherModelInstance)
It's not such a good idea to override save() method. Django is doing a lot of stuff behind the scene to make sure that model objects are saved as they expected. If you do it in incorrectly it would yield bizarre behavior and hard to debug.
Please check django signals, it's convenient way to access your model object information and status. They provide useful parameters like instance, created and updated_fields to fit specially your need to check the object.
Thanks everyone for your answers - after careful examination I may safely conclude that I tripped over my own two feet.
After careful examination and even a trip with pdb, I found that the original code had mixed indentation - \t instead of \s{4} before the last super().save().

Django FormWizards: How to painlessly pass user-entered data between forms?

I'm using the FormWizard functionality in Django 1.4.3.
I have successfully created a 4-step form. In the first 3 steps of the form it correctly takes information from the user, validates it, etc. In Step #4, it right now just shows a "Confirm" button. Nothing else. When you hit "Confirm" on step #4, does something useful with it in the done() function. So far it all works fine.
However, I would like to make it so that in step 4 (The confirmation step), it shows the user the data they have entered in the previous steps for their review. I'm trying to figure out the most painless way to make this happen. So far I am creating an entry in the context called formList which contains a list of forms that have already been completed.
class my4StepWizard(SessionWizardView):
def get_template_names(self):
return [myWizardTemplates[self.steps.current]]
def get_context_data(self, form, **kwargs):
context = super(my4StepWizard, self).get_context_data(form=form, **kwargs)
formList = [self.get_form_list()[i[0]] for i in myWizardForms[:self.steps.step0]]
context.update(
{
'formList': formList,
}
)
return context
def done(self, form_list, **kwargs):
# Do something here.
return HttpResponseRedirect('/doneWizard')
Form #1 has an input field called myField.
So in my template for step #4, I would like to do {{ formList.1.clean_myField }}. However, when I do that, I get the following error:
Exception Value:
'my4StepWizard' object has no attribute 'cleaned_data'
It seems that the forms I am putting into formList are unbounded. So they don't contain the user's data. Is there a fix I can use to get the data itself? I would really like to use the context to pass the data as I'm doing above.
Try this:
def get_context_data(self, form, **kwargs):
previous_data = {}
current_step = self.steps.current # 0 for first form, 1 for the second form..
if current_step == '3': # assuming no step is skipped, this will be the last form
for count in range(3):
previous_data[unicode(count)] = self.get_cleaned_data_for_step(unicode(count))
context = super(my4StepWizard, self).get_context_data(form=form, **kwargs)
context.update({'previous_cleaned_data':previous_data})
return context
previous_data is a dictionary and its keys are the steps for the wizard (0 indexed). The item for each key is the cleaned_data for the form in the step which is the same as the key.

Django form: ask for confirmation before committing to db

Update: The solution can be found as a separate answer
I am making a Django form to allow users to add tvshows to my db. To do this I have a Tvshow model, a TvshowModelForm and I use the generic class-based views CreateTvshowView/UpdateTvshowView to generate the form.
Now comes my problem: lets say a user wants to add a show to the db, e.g. Game of Thrones. If a show by this title already exists, I want to prompt the user for confirmation that this is indeed a different show than the one in the db, and if no similar show exists I want to commit it to the db. How do I best handle this confirmation?
Some of my experiments are shown in the code below, but maybe I am going about this the wrong way. The base of my solution is to include a hidden field force, which should be set to 1 if the user gets prompted if he is sure he wants to commit this data, so that I can read out whether this thing is 1 to decide whether the user clicked submit again, thereby telling me that he wants to store it.
I would love to hear what you guy's think on how to solve this.
views.py
class TvshowModelForm(forms.ModelForm):
force = forms.CharField(required=False, initial=0)
def __init__(self, *args, **kwargs):
super(TvshowModelForm, self).__init__(*args, **kwargs)
class Meta:
model = Tvshow
exclude = ('user')
class UpdateTvshowView(UpdateView):
form_class = TvshowModelForm
model = Tvshow
template_name = "tvshow_form.html"
#Only the user who added it should be allowed to edit
def form_valid(self, form):
self.object = form.save(commit=False)
#Check for duplicates and similar results, raise an error/warning if one is found
dup_list = get_object_duplicates(Tvshow, title = self.object.title)
if dup_list:
messages.add_message(self.request, messages.WARNING,
'A tv show with this name already exists. Are you sure this is not the same one? Click submit again once you\'re sure this is new content'
)
# Experiment 1, I don't know why this doesn't work
# form.fields['force'] = forms.CharField(required=False, initial=1)
# Experiment 2, does not work: cleaned_data is not used to generate the new form
# if form.is_valid():
# form.cleaned_data['force'] = 1
# Experiment 3, does not work: querydict is immutable
# form.data['force'] = u'1'
if self.object.user != self.request.user:
messages.add_message(self.request, messages.ERROR, 'Only the user who added this content is allowed to edit it.')
if not messages.get_messages(self.request):
return super(UpdateTvshowView, self).form_valid(form)
else:
return super(UpdateTvshowView, self).form_invalid(form)
Solution
Having solved this with the help of the ideas posted here as answers, in particular those by Alexander Larikov and Chris Lawlor, I would like to post my final solution so others might benefit from it.
It turns out that it is possible to do this with CBV, and I rather like it. (Because I am a fan of keeping everything OOP) I have also made the forms as generic as possible.
First, I have made the following forms:
class BaseConfirmModelForm(BaseModelForm):
force = forms.BooleanField(required=False, initial=0)
def clean_force(self):
data = self.cleaned_data['force']
if data:
return data
else:
raise forms.ValidationError('Please confirm that this {} is unique.'.format(ContentType.objects.get_for_model(self.Meta.model)))
class TvshowModelForm(BaseModelForm):
class Meta(BaseModelForm.Meta):
model = Tvshow
exclude = ('user')
"""
To ask for user confirmation in case of duplicate title
"""
class ConfirmTvshowModelForm(TvshowModelForm, BaseConfirmModelForm):
pass
And now making suitable views. The key here was the discovery of get_form_class as opposed to using the form_class variable.
class EditTvshowView(FormView):
def dispatch(self, request, *args, **kwargs):
try:
dup_list = get_object_duplicates(self.model, title = request.POST['title'])
if dup_list:
self.duplicate = True
messages.add_message(request, messages.ERROR, 'Please confirm that this show is unique.')
else:
self.duplicate = False
except KeyError:
self.duplicate = False
return super(EditTvshowView, self).dispatch(request, *args, **kwargs)
def get_form_class(self):
return ConfirmTvshowModelForm if self.duplicate else TvshowModelForm
"""
Classes to create and update tvshow objects.
"""
class CreateTvshowView(CreateView, EditTvshowView):
pass
class UpdateTvshowView(EditTvshowView, UpdateObjectView):
model = Tvshow
I hope this will benefit others with similar problems.
I will post it as an answer. In your form's clean method you can validate user's data in the way you want. It might look like that:
def clean(self):
# check if 'force' checkbox is not set on the form
if not self.cleaned_data.get('force'):
dup_list = get_object_duplicates(Tvshow, title = self.object.title)
if dup_list:
raise forms.ValidationError("A tv show with this name already exists. "
"Are you sure this is not the same one? "
"Click submit again once you're sure this "
"is new content")
You could stick the POST data in the user's session, redirect to a confirmation page which contains a simple Confirm / Deny form, which POSTs to another view which processes the confirmation. If the update is confirmed, pull the POST data out of the session and process as normal. If update is cancelled, remove the data from the session and move on.
I have to do something similar and i could do it using Jquery Dialog (to show if form data would "duplicate" things) and Ajax (to post to a view that make the required verification and return if there was a problem or not). If data was possibly duplicated, a dialog was shown where the duplicated entries appeared and it has 2 buttons: Confirm or Cancel. If someone hits in "confirm" you can continue with the original submit (for example, using jquery to submit the form). If not, you just close the dialog and let everything as it was.
I hope it helps and that you understand my description.... If you need help doing this, tell me so i can copy you an example.
An alternative, and cleaner than using a vaidationerror, is to use Django's built in form Wizard functionality: https://django-formtools.readthedocs.io/en/latest/wizard.html
This lets you link multiple forms together and act on them once they are all validated.

How to write a basic try/except in a Django Generic Class View

I'd like to write an except clause that redirects the user if there isn't something in a queryset. Any suggestions welcome. I'm a Python noob, which I get is the issue here.
Here is my current code:
def get_queryset(self):
try:
var = Model.objects.filter(user=self.request.user, done=False)
except:
pass
return var
I want to do something like this:
def get_queryset(self):
try:
var = Model.objects.filter(user=self.request.user, done=False)
except:
redirect('add_view')
return var
A try except block in the get_queryset method isn't really appropriate. Firstly, Model.objects.filter() won't raise an exception if the queryset is empty - it just returns an empty queryset. Secondly, the get_queryset method is meant to return a queryset, not an HttpResponse, so if you try to redirect inside that method, you'll run into problems.
I think you might find it easier to write a function based view. A first attempt might look like this:
from django.shortcuts import render
def my_view(request):
"""
Display all the objects belonging to the user
that are not done, or redirect if there are not any,
"""
objects = Model.objects.filter(user=self.request.user, done=False)
if not objects:
return HttpResponseRedirect("/empty-queryset-url/")
return render(request, 'myapp/template.html', {"objects": objects})
The advantage is that the flow of your function is pretty straight forward. This doesn't have as many features as the ListView generic class based view (it's missing pagination for example), but it is pretty clear to anyone reading your code what the view is doing.
If you really want to use the class based view, you have to dig into the CBV documentation for multiple object mixins and the source code, and find a suitable method to override.
In this case, you'll find that the ListView behaviour is quite different to what you want, because it never redirects. It displays an empty page by default, or a 404 page if you set allow_empty = False. I think you would have to override the get method to look something like this (untested).
class MyView(ListView):
def get_queryset(self):
return Model.objects.filter(user=self.request.user, done=False)
def get(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
if len(self.object_list == 0):
return HttpResponseRedirect("/empty-queryset-url/")
context = self.get_context_data(object_list=self.object_list)
return self.render_to_response(context)
This is purely supplemental to #Alasdair's answer. It should really be a comment, but couldn't be formatted properly that way. Instead of actually redefining get on the ListView, you could override simply with:
class MyView(ListView):
allow_empty = False # Causes 404 to be raised if queryset is empty
def get(self, request, *args, **kwargs):
try:
return super(MyView, self).get(request, *args, **kwargs)
except Http404:
return HttpResponseRedirect("/empty-queryset-url/")
That way, you're not responsible for the entire implementation of get. If Django changes it in the future, you're still good to go.