I am trying to assign currently logged in user as an attribute to a field of a modelform instance using generic views. I have referred to this SO post and did override post method but it was giving me an error that CreatedBy field was required. Also I have gone through mro on ccbv many times. View as below.
class PostCreate(LoginRequiredMixin, CreateView):
model = Post
form_class = PostForm
success_message = "Post Updated"
success_url = '/home/'
def get_form(self, form_class=None):
"""
Returns an instance of the form to be used in this view.
"""
form = super(PostCreate, self).get_form(form_class)
form.instance.CreatedBy=User.objects.get(id=self.request.user.id)
return form
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
self.initial = {'CreatedBy': User.objects.get(id=self.request.user.id)}
return self.initial.copy()
def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs
The reason I did override all these methods is to check the availability of initial dict in every method. It is available in every method but still form validation fails. But I think its better not to set values in get_initial(self) since I do not prepopulate form fields with existing data of any saved object, rather I want to update a field of an initialized form with User object of logged in user. I have gone through flow of control in ipdb but enden up with same error.
ipdb> form.initial={'CreatedBy':User.objects.get(id=request.user.id)}
ipdb> form.fields['CreatedBy']=User.objects.get(id=request.user.id)
ipdb> form.instance.CreatedBy=User.objects.get(id=request.user.id)
ipdb> form.is_valid()
False
ipdb> form.instance.CreatedBy
<User: userone>
ipdb> form.fields['CreatedBy']
<User: userone>
ipdb> form.initial
{'CreatedBy': <User: userone>}
Please notice that I am not looking for a manipulated form_valid(self) method.
I am caught up with this for hours. Any help is much appreciated.
The reason that created_by is still required is because you have not excluded it from the form itself; you need to do that in PostForm.
class PostForm(forms.ModelForm):
class Meta:
exclude = ['created_by']
As for assigning it automatically, the docs on the editing views have a specific section describing exactly how to do this; you override form_valid():
def form_valid(self, form):
form.instance.created_by = self.request.user
return super(PostCreate, self).form_valid(form)
Related
Hi in my program I keep receiving the above exception and am unsure why. The issue happens when my requestLessons_view method tries to save the form.
Views.py
def requestLessons_view(request):
if request.method == 'POST':
form = RequestLessonsForm(request.POST)
if form.is_valid() & request.user.is_authenticated:
user = request.user
form.save(user)
return redirect('login')
else:
form = RequestLessonsForm()
return render(request, 'RequestLessonsPage.html', {'form': form})
forms.py
class RequestLessonsForm(forms.ModelForm):
class Meta:
model = Request
fields = ['availability', 'num_of_lessons', 'interval_between_lessons', 'duration_of_lesson','further_information']
widgets = {'further_information' : forms.Textarea()}
def save(self, user):
super().save(commit=False)
request = Request.objects.create(
student = user,
availability=self.cleaned_data.get('availability'),
num_of_lessons=self.cleaned_data.get('num_of_lessons'),
interval_between_lessons=self.cleaned_data.get('interval_between_lessons'),
duration_of_lesson=self.cleaned_data.get('duration_of_lesson'),
further_information=self.cleaned_data.get('further_information'),
)
return request
The error I receive is:
IntegrityError at /request_lessons/
NOT NULL constraint failed: lessons_request.student_id
Your .save() method is defined on the Meta class, not the form, hence the error. I would advise to let the model form handle the logic: a ModelForm can be used both to create and update the items, so by doing the save logic yourself, you basically make the form less effective. You can rewrite this to:
class RequestLessonsForm(forms.ModelForm):
class Meta:
model = Request
fields = [
'availability',
'num_of_lessons',
'interval_between_lessons',
'duration_of_lesson',
'further_information',
]
widgets = {'further_information': forms.Textarea}
def save(self, user, *args, **kwargs):
self.instance.student = user
return super().save(*args, **kwargs)
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
views.py:
class ProfileView(DetailView):
model = User
template_name ="profile/profile_view.html"
class ProfileEdit(UserPassesTestMixin, UpdateView):
login_url = '/login/'
model = User
form_class = ProfileForm
template_name="profile/profile_new.html"
def test_func(request, user_id):
user = User.objects.get(pk=user_id)
if request.user == user.user:
return True
else:
return HttpResponse("<h1>You will not be able to edit other profiles</h1>")
urls.py
url(r'^(?P<pk>[0-9]+)/edit/$', ProfileEdit.as_view(), name='profile_edit')
I got this error: (test_func() missing 1 required positional argument: 'user_id')
This post addresses the same issue I want to solve. Is it different for class based views?
There are a couple of things wrong with this method.
The first is that, like any method, it needs self as the first argument.
Secondly, as the error states, the code that calls this view is not expecting to pass user_id as a parameter. You should get that value, as you would anywhere else in a class-based view, from self.kwargs.
Thirdly, you try to access the user attribute of the user, but that doesn't exist. You could just compare the user directly, but in fact there is no point in querying the user model at all; you can just compare the ID with the current user's ID.
def test_func(self, request):
if request.user.id == int(self.kwargs['pk']):
...
However, you should also ask yourself whether any of this is the right thing to be doing. Rather than passing the user id in the URL and then checking it's the same as the logged-in user's id, you could just omit the ID completely and just always access the current user. You would do that by defining get_object in the view to return request.user; you could then remove the UserPassesTestMixin, the test_func, and the URL parameter.
I got the answer i needed.
views.py
class ProfileEdit(UserPassesTestMixin, LoginRequiredMixin, UpdateView):
model = User
form_class = ProfileForm
template_name="profile/profile_new.html"
def test_func(self):
x = self.request.user.username
y = self.kwargs['slug']
if x == y:
return True
else:
if self.request.user.is_authenticated():
raise Http404("You are not authenticated to edit this profile")
I replaced 'id' with 'slug' i will be using that to edit
I want to connect each post with the logged in user who posted it.
models.py
from django.conf import settings
from django.db import models
# Create your models here.
class Campagin(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
media = models.FileField()
description = models.TextField(max_length=220)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return self.title`
As you can see the posts were made by two different users, but the relation shows that it is made by the first user
this image shows the registered users..
Views.py
class NewCampagin(LoginRequiredMixin, CreateView):
template_name = 'campagin/new_campagin.html'
model = Campagin
fields = ['title','media','description']
def get_absolute_url(self):
return reverse('campagin:active_campagin')
Okay so CreateView allows you to specify the model and fields attributes to implicitly create a form for you. It's quite neat for quick form submissions but in your case, you will need to make some customizations before saving the Campaign object into the database (linking up the current logged in user).
As a result, you will need to create your own form first (create a file called forms.py which can be next to your views.py) and enter this code:
class CampaignForm(ModelForm): # Import ModelForm too.
def __init__(self, *args, **kwargs):
# We need to get access the currently logged in user so set it as an instance variable of CampaignForm.
self.user = kwargs.pop('user', None)
super(CampaignForm, self).__init__(*args, **kwargs)
class Meta:
model = models.Campaign # you need to import this from your models.py class
fields = ['title','media','description']
def save(self, commit=True):
# This is where we need to insert the currently logged in user into the Campaign instance.
instance = super(CampaignForm, self).save(commit=False)
# Once the all the other attributes are inserted, we just need to insert the current logged in user
# into the instance.
instance.user = self.user
if commit:
instance.save()
return instance
Now that we have our forms.py all ready to go we just need to modify your views.py:
class NewCampagin(LoginRequiredMixin, CreateView):
template_name = 'campagin/new_campagin.html'
form_class = forms.CampaignForm # Again, you'll need to import this carefully from our newly created forms.py
model = models.Campaign # Import this.
queryset = models.Campaign.objects.all()
def get_absolute_url(self):
return reverse('campagin:active_campagin') # Sending user object to the form, to verify which fields to display/remove (depending on group)
def get_form_kwargs(self):
# In order for us to access the current user in CampaignForm, we need to actually pass it accross.
# As such, we do this as shown below.
kwargs = super(NewCampaign, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs
What's actually happening with my POST requests under the bonnet??
Note: This is just extra information for the sake of learning. You do
not need to read this part if you don't care about how your class
based view is actually handling your post request.
Essentially CreateView looks like this:
class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView):
"""
View for creating a new object instance,
with a response rendered by template.
"""
template_name_suffix = '_form'
Doesn't look that interesting but if we analyse BaseCreateView:
class BaseCreateView(ModelFormMixin, ProcessFormView):
"""
Base view for creating an new object instance.
Using this base class requires subclassing to provide a response mixin.
"""
def post(self, request, *args, **kwargs):
self.object = None
return super(BaseCreateView, self).post(request, *args, **kwargs)
we can see we are inheriting from two very important classes ModelFormMixin and ProcessFormView. Now the line, return super(BaseCreateView, self).post(request, *args, **kwargs), essentially calls the post function in ProcessFormView which looks like this:
def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form instance with the passed
POST variables and then checked for validity.
"""
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
As you can see, your CreateView really just boils down to this small post function which simply gets a specified form and validates + saves it. There's 2 questions to ask at this point.
1) What does form = self.get_form() do since I didn't even specify my form?
2) What is self.form_valid(form) actually doing?
To answer the first question, self.get_form() essentially calls another function form_class = self.get_form_class() and this function is actually found in ModelFormMixin (the one where inherited from!):
def get_form_class(self):
"""
Returns the form class to use in this view.
"""
if self.fields is not None and self.form_class:
raise ImproperlyConfigured(
"Specifying both 'fields' and 'form_class' is not permitted."
)
if self.form_class:
return self.form_class
else:
if self.model is not None:
# If a model has been explicitly provided, use it
model = self.model
elif hasattr(self, 'object') and self.object is not None:
# If this view is operating on a single object, use
# the class of that object
model = self.object.__class__
else:
# Try to get a queryset and extract the model class
# from that
model = self.get_queryset().model
if self.fields is None:
raise ImproperlyConfigured(
"Using ModelFormMixin (base class of %s) without "
"the 'fields' attribute is prohibited." % self.__class__.__name__
)
# THIS IS WHERE YOUR FORM WAS BEING IMPLICITLY CREATED.
return model_forms.modelform_factory(model, fields=self.fields)
As you can see, this function is where your form was being implicitly created (see very last line). We needed to add more functionality in your case so we created our own forms.py and specified form_class in the views.py as a result.
To answer the second question, we need to look at the function (self.form_valid(form)) call's source code:
def form_valid(self, form):
"""
If the form is valid, save the associated model.
"""
# THIS IS A CRUCIAL LINE.
# This is where your actual Campaign object is created. We OVERRIDE the save() function call in our forms.py so that you could link up your logged in user to the campaign object before saving.
self.object = form.save()
return super(ModelFormMixin, self).form_valid(form)
So here we are simply saving the object.
I hope this helps you!
More information at https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#createview
I would like to update my model with the currently logged in user. I am using django-vanilla-views. To store a new record I am trying to use CreateView. I don't want to display user on the form, just update it automatically.
Here is my model:
class Measurement(models.Model):
date = models.DateField()
user = models.ForeignKey(User)
And here is my view:
class CreateMeasurement(CreateView):
model = Measurement
fields = ['date']
success_url = reverse_lazy('list_measurements')
def get_form(self, data=None, files=None, **kwargs):
kwargs['user'] = self.request.user
return super(CreateMeasurement, self).get_form(data=data, files=files, **kwargs)
Unfortunately when accessing the view I get the following exception:
TypeError: __init__() got an unexpected keyword argument 'user'
I also tried to create a ModelForm for my model but got exactly the same error. Any ideas what I might be doing wrong?
You don't need to pass the user to the form, so don't override the get_form method. You have already excluded the user field from the model form by setting fields in your view, so you shouldn't need a custom model form either.
It should be enough to override the form_valid method, and set the user when the form is saved.
from django.http import HttpResponseRedirect
class CreateMeasurement(CreateView):
model = Measurement
fields = ['date']
success_url = reverse_lazy('list_measurements')
def form_valid(self, form):
obj = form.save(commit=False)
obj.user = self.request.user
obj.save()
return HttpResponseRedirect(self.get_success_url())
I'm getting an error:
AttributeError at /courses/create/
'CourseStudentForm' object has no attribute 'user'
When I try to create a new object by setting it's user field to the current user:
class CourseStudentCreate(CreateView):
model = CourseStudent
fields = ['semester', 'block', 'course', 'grade']
success_url = reverse_lazy('quests:quests')
#method_decorator(login_required)
def form_valid(self, form):
data = form.save(commit=False)
data.user = self.request.user
data.save()
return super(CourseStudentCreate, self).form_valid(form)
This is the model:
class CourseStudent(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
semester = models.ForeignKey(Semester)
block = models.ForeignKey(Block)
course = models.ForeignKey(Course)
grade = models.PositiveIntegerField()
active = models.BooleanField(default=True)
The form displays correctly, but when I submit I get the error.
ANSWER:
From here:
Pass current user to initial for CreateView in Django
If I want to keep user as a required field, it works if I change form_valid to:
def form_valid(self, form):
form.instance.user = self.request.user
return super(CourseStudentCreate, self).form_valid(form)
The cause of the error is described by Burhan Khalid below.
The reason it doesn't work is because you are missing a required field from your form class; recall that model form validation will also validate the model instance:
Validation on a ModelForm
There are two main steps involved in validating a ModelForm:
Validating the form
Validating the model instance
In your class, the inherited post method is calling is_valid():
def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form instance with the passed
POST variables and then checked for validity.
"""
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
You can see that it only calls form_valid() if is_valid() returns true; in your case it can't return true because you have a required attribute missing.
You can solve this problem easily by making the user foreign key optional in your model.