I am converting an old project with Class Views and I want to know if the pattern I am using is "safe".
In brief I have a class View like this (code simplified ):
class FileAddHashedView(FormView):
"""This view hashes the file contents using md5"""
form_class = FileUploadForm
success_url = reverse_lazy('vault-show')
template_name = "vault/add.html"
filebox_random= 0
def get_success_url(self):
return reverse('vault-show', kwargs={'random': self.filebox_random})
def form_valid(self, form):
instance = form.save(commit=False)
#generate a random number
rng = random.SystemRandom()
#TODO: must catch exception here
instance.random=rng.randint(0, sys.maxint)
instance.save()
#TODO: check what is the proper way to generate the parametric URL
self.filebox_random=instance.random
messages.success(
self.request, 'File hashed and uploaded!', fail_silently=True)
return super(FileAddHashedView, self).form_valid(form)
def form_invalid(self, form, **kwargs):
messages.error(self.request, 'Upload failed ...', fail_silently=True)
return super(FileAddView, self).form_invalid(form)
And the corresponding views that gets activated:
class VaultStatus(TemplateView):
template_name = 'vault/vault.html'
def get(self, request,random):
# retrieve object info
data = {
'filebox': FileBox.objects.get(random=random)
}
return render(request,self.template_name,data)
#return render_to_response('vault/vault.html', {'random': random});
Now my question is: is there a better way in get_success_url to get the self.filebox_random without relying on a class attribute?
Is this thread-safe?
You're not using a class attribute here. Even though you've defined filebox_random at class level, by setting a value to that name within an instance method in Python you're actually creating an instance attribute with the same name, which hides the class-level one. (Although I'm not actually sure why you're defining the class attribute in the first place).
Django does quite a lot of work behind the scenes to ensure that class-based views are thread-safe, so there is no danger in setting instance attributes.
Related
i'm new in Django and i'm learning about the views and the methods and how they work, especially with this problem. The thing is that I would like to know how to automatically save a value of a field in my model after updating an object in a UpdateView, for example when I update an object, in this case a report where I can assign a person to do it, I would like to save a model value that shows the "status" and save the value of "assigned" or something like that, to know if the report was already assigned or not. I know there are methods and that maybe one of them could be done by overwriting the class, but I do not know how to apply it or which one to use.
For help this is a simple class of a UpdateViews that i'm using:
class reporteupdate(UpdateView):
model = reporte_fallo
form_class = ReporteAsignar
template_name = 'formulario/jefe_asignar.html'
success_url = reverse_lazy('formulario:reporte_listar_jefe')
and the field of the model that I would like to assign a value to is called status.
i'm waiting for your help, since I'm stuck with that doubt. Thanks!!!
the query dict will be changable after you create a copy of it in post method so you can do this:-
class SomeUpdateView(UpdateView):
model=your model
form_class=you form
def post(self, request, **kwargs):
request.POST = request.POST.copy()
request.POST['status'] = 'Assigned'
return super(SomeUpdateView, self).post(request, **kwargs)
You could perhaps set the status flag after the form has been successfully validated, by overriding the form_valid() method in your reporteupdate view:
class reporteupdate(UpdateView):
...
def form_valid(self, form):
# Call super() to save the model and return the success url
resp = super().form_valid(form)
# Set your status flag
self.object.status = 'assigned'
self.object.save()
return resp
I am trying to create a user profile page where users can see and update their preferences for certain things, like whether they are vegetarian, or have a particular allergy, etc. I want the data to be displayed as a form, with their current preferences already populating the form fields.
So I've created the following Model:
class FoodPreferences(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE) # One user has one set of food prefs
vegetarian = models.BooleanField()
vegan = models.BooleanField()
...
that's referenced in my forms.py:
class FoodPreferencesForm(forms.ModelForm):
class Meta:
model = FoodPreferences
exclude = ('user', )
I've tried creating a view that inherits FormView and then referencing the form, like this:
class UserProfileView(generic.FormView):
template_name = "registration/profile.html"
form_class = FoodPreferencesForm
success_url = reverse_lazy('user_profile')
This saves the form to a instance of the model correctly, but obviously it just displays the blank form again, after updating, so the user has no idea what their current preferences are.
To implement this I thought I might need to override get() and post() to get the instance of FoodPreferences for the user, and then pass those values into the form like you would a request.POST object. However, firstly, I don't know how to do that, and secondly I'd be taking responsibility for correctly updating the database, which the FormView was already doing.
This is what I've got for that solution:
def get(self, request, *args, **kwargs):
prefs = FoodPreferences.objects.get(user=request.user)
form = self.form_class(prefs)
return render(request, self.template_name, {'form': form, })
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if not form.is_valid():
return render(request, self.template_name, {'form': form, 'error': 'Something went wrong.'})
curr_prefs = FoodPreferences.objects.update_or_create(form.fields)
prefs.save()
return render(request, self.template_name, {'form': form, })
but I get a TypeError: argument of type 'FoodPreferences' is not iterable on the line in get():
form = self.form_class(prefs)
because it's not expecting a model instance.
Am I thinking about this in the right way? This seems like a common enough problem that Django would have something inbuilt to do it, but I can't find anything.
You should only rarely need to define get or post in a class-based view, and you definitely don't here.
To start with, you need to use a more appropriate base class for your view. Here you want to update an existing item, so you should use UpdateView.
Secondly, you need to tell the class how to get the existing object to update, which you can do by definining get_object. So:
class UserProfileView(generic.UpdateView):
template_name = "registration/profile.html"
form_class = FoodPreferencesForm
success_url = reverse_lazy('user_profile')
def get_object(self, queryset=None):
return self.request.user.foodpreferences
# or, if you aren't certain that the object already exists:
obj, _ = FoodPreferences.objects.get_or_create(user=self.request.user)
return obj
I've been working with Django for about 3 months now and feel I'm getting a bit better, working my way up to class based views. On the surface they seem cleaner and easier to understand and in some cases they are. In others, not so much. I am trying to use a simple drop down view via ModelChoiceField and a form. I can get it to work with a function based view as shown below in my views.py file:
def book_by_name(request):
form = BookByName(request.POST or None)
if request.method == 'POST':
if form.is_valid():
book_byname = form.cleaned_data['dropdown']
return HttpResponseRedirect(book_byname.get_absolute_url1())
return render(request,'library/book_list.html',{'form':form})
Here is my form in forms.py:
class BookByName(forms.Form):
dropdown = forms.ModelChoiceField(queryset=Book.objects.none())
def __init__(self, *args, **kwargs):
super(BookByName, self).__init__(*args, **kwargs)
self.fields['dropdown'].widget.attrs['class'] = 'choices1'
self.fields['dropdown'].empty_label = ''
self.fields['dropdown'].queryset = Book.objects.order_by('publisher')
This code works. When I have tried to convert to a Class Based View, that's when the trouble begins. I tried to do something like this in views.py:
class BookByNameView(FormView, View):
form_class = BookByName
initial = { 'Book' : Book }
template_name = 'library/book_list.html'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def get_success_url(self, *args):
return reverse_lazy('library:book_detail', args = (self.object.id,))
When using this with the same form, I receive an attribute error,
'BookByNameView' object has no attribute 'object'.
I've tried ListView as well and received several other errors along the way. The get_success_url also needs to take in a primary key and I can't figure out how to get that passed in as well. Again, I'm a 3 month Django newbie so please be gentle and thanks in advance for your thoughts and suggestions! I feel like I'm in the ballpark...just can't find my seat! I'm very open to doing this differently, if there's a cleaner/better way to do this!
Based on the latest feedback, it would appear the Class Based View should look like:
class BookNameView(FormView):
form_class = BookName
template_name = 'library/book_list.html'
def get_success_url(self, *args):
return reverse_lazy('library:book_detail')
Is this correct? I ran a test version of this and in response to your question as to why I am using self.object.id at all, I am trying to get the pk from the modelchoicefield that I am using to return the view I am trying to get. This may be where I am getting a bit lost. I am trying to get the detail view from the modelchoicefield dropdown, and return the book that is selected. However, I can't seem to pass the pk to this view successfully.
I updated my code to...
class BookByNameView(FormView, ListView):
model = Book
form_class = BookByName
template_name = 'library/book_list.html'
def get_success_url(self, *args):
return reverse_lazy('library:book_detail')
But now it says error...Reverse for 'book_detail' with no arguments not found.
Why are you using self.object there at all? You used form.cleaned_data in the original view, that's what you should use in the class based version too. Note that the form is passed to form_valid.
Note that you've done lots of other weird things too. Your getmethod is pointless, as is your definition of the initial dict; you should delete them both. Also, FormView already inherits from View, there's no need to have View in your declaration explicitly.
You can override the form_valid() function in FormView to achieve what you want. If the form is valid then it is passed to the form_valid() function.
Try this:
class BookByNameView(FormView):
model = Book
form_class = BookByName
template_name = 'library/book_list.html'
def form_valid(self, form):
bookbyname = form.cleaned_data['dropdown']
return HttpResponseRedirect(bookbyname.get_absolute_url())
I am new to django class based views and may be the way I am approaching this is a little naive, so I would appreciate if you could suggest a better way.
So my problem is here:
There are three types of users in my project. 1. Student, 2. Teacher, 3. Parent. I need to be able to show different user settings pertaining to each type of user when the user requests the settings page in their respective forms. Also, I need to be able to save the data into the respective tables as the user submits the form.
I have a class based view (UserSettingsView):
class UserSettingsView(LoginRequiredMixin, FormView):
success_url = '.'
template_name = 'accts/usersettings.html'
def get_initial(self):
if self.request.user.is_authenticated():
user_obj = get_user_model().objects.get(email=self.request.user.email)
if user_obj.profile.is_student:
return {
'first_name': user_obj.profile.first_name,
'last_name': user_obj.profile.last_name,
""" and other student field variables """
}
if user_obj.profile.is_teacher:
return {
""" Teacher field variables """
}
else:
return render_to_response('allauth/account/login.html')
def form_valid(self, form):
messages.add_message(self.request, messages.SUCCESS, 'Settings Saved!')
return super(UserSettingsView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(UserSettingsView, self).get_context_data(**kwargs)
context['user'] = get_user_model().objects.get(email=self.request.user.email)
context['userprofile'] = UserProfile.objects.get(user_id=context['user'])
return context
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
form.full_clean()
if form.is_valid():
user = request.user
user.profile.first_name = form.cleaned_data['first_name']
user.profile.last_name = form.cleaned_data['last_name']
user.profile.save()
if user.profile.is_student:
""" update student database """
user.save()
user.student.save()
if user.profile.is_teacher:
""" update teacher database """
user.save()
user.teacher.save()
return self.form_valid(form)
else:
return self.form_invalid(form)
Different instances of Usersettings view are called using the pick_settings generic view.
url(regex=r'^profilesettings/',view=pick_settings,name='profilesettings'),
And here is the pick_settings view:
def pick_settings(request):
if request.user.is_authenticated():
if request.method == 'GET':
if request.user.profile.is_student:
return UserSettingsView.as_view(form_class=StudentSettingsForm)(request)
if request.user.profile.is_teacher:
return UserSettingsView.as_view(form_class=TeacherSettingsForm)(request)
if request.user.profile.is_parent:
return UserSettingsView.as_view(form_class=ParentSettingsForm)(request)
else:
if request.method == 'POST':
"""
return ***<--- I need to know what to pass here to be able to call the appropriate post function of the UserSettingsView?---->"""***
else:
return HttpResponseRedirect('/accounts/login/')
I need to be able to call the post function of the UserSettingsView. May be using the get_context_data? But I am not sure how.
Again it will be great, if someone could suggest a better way because I am pretty sure this might be violating the DRY principle. Although, I am not too concerned with that as long as the job gets done as I am running a deadline. :) Thanks!
FormView has a method get_form_class(). It is called from get() and post(), so self.request will already be set (as will be self.request.user). Consequently,
class UserSettingsView(LoginRequiredMixin, FormView):
[...]
def get_form_class(self):
# no need to check is_authenticated() as we have LoginRequiredMixin
if request.user.profile.is_student:
return StudentSettingsForm
elif user.profile.is_teacher:
return TeacherSettingsForm
elif user.profile.is_parent:
return ParentSettingsForm
This should already to the trick as you get the correct form for each user type.
If you also need to render different templates, override get_template_names():
def get_template_names(self):
if request.user.profile.is_student:
return ['myapp/settings/student.html']
elif user.profile.is_teacher:
return ['myapp/settings/teacher.html']
elif user.profile.is_parent:
return ['myapp/settings/parent.html']
DRY can be achieved using proper inheritance in the templates combining common template fragments.
And lest I forget (I already forgot): To get rid of the if in the post() method of your view, simple override the save() method of you forms which I assume are ModelForms, anyway.
I'm still getting to grips with Django and, in particular, Forms.
I created MyForm which subclasses forms.Form in which I define a field like this :
owner = forms.CharField(widget=forms.HiddenInput)
When I create a new, blank instance of the Form I want to prefill this with the creator's profile, which I'm doing like this :
form = MyForm( {'owner' : request.user.get_profile()} )
Which I imagine sets the owner field of the form to the request.user's id. (The type of the corresponding "owner" field in the models.Model class is ForeignKey of Profile.)
Before rendering the form, I need to check one piece of information about the owner. So I try to access form.owner, but there seems to be no "owner" attribute of the form object. I also tried form.instance.owner, but similarly, no luck.
What am I doing wrong? What have I misunderstood?
You can access this value via the form's data dictionary:
form.data.get('owner')
Initial data in a form should be passed in with the initial kwarg.
Once you've turned the form into a bound form (usually by passing request.POST in as the first argument to instantiate the form, the place you are currently incorrectly providing the initial dictionary), and performed validation with form.is_valid(), the data the user submitted will be in form.cleaned_data, a dictionary. If they changed the initial value, their changed value will be in that dictionary. If not, your initial value will be.
If you don't want to let the user modify the value, then don't have it be a field, instead pass it in as a kwarg, and store it as an instance attribute in form.__init__():
class MyForm(Form):
def __init__(self, *args, profile, **kwargs):
super().__init__(*args, **kwargs)
self.profile = profile
...
form = MyForm(
request.POST if request.POST else None,
profile=request.user.get_profile(),
)
if request.method == "POST" and form.is_valid():
do_stuff_with(form.profile)
Also as with most things, this all gets easier if you drink the Django kool-aid and use generic views.
class MyView(FormView):
form_class = MyForm
...
def get_form_kwargs(self):
return {
**super().get_form_kwargs(),
"profile": self.request.user.get_profile()
}
def form_valid(self, form):
do_stuff_with(form.profile)
return super().form_valid(form)
Or for the initial case whereby you want it to be editable:
class MyView(FormView):
form_class = MyForm
...
def get_initial(self):
return {
**super().get_initial(),
"profile": self.request.user.get_profile()
}
def form_valid(self, form):
do_stuff_with(form.cleaned_data.get("profile"))
return super().form_valid(form)
If MyForm happens to be a form about one single instance of a specific model then this gets even easier with UpdateView instead of FormView. The more you buy into the way Django wants to do things, the less you have to work.