How do I set user field in form to the currently logged in user?

Remove user field from rendered form (using exclude or fields, https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#selecting-the-fields-to-use ) class CandidateForm(forms.ModelForm): class Meta: model = Candidate exclude = [“user”] Find user profile and set user field in the create view. class CandidateCreateView(CreateView): … def form_valid(self, form): candidate = form.save(commit=False) candidate.user = UserProfile.objects.get(user=self.request.user) # use your own profile here candidate.save() return HttpResponseRedirect(self.get_success_url())

Test Django views that require login using RequestFactory

When using RequestFactory, you are testing view with exactly known inputs. That allows isolating tests from the impact of the additional processing performed by various installed middleware components and thus more precisely testing. You can setup request with any additional data that view function expect, ie: request.user = AnonymousUser() request.session = {} My personal recommendation … Read more

reverse for success_url on Django Class Based View complain about circular import

Using reverse in your method works because reverse is called when the view is run. def my_view(request): url = reverse(‘blog:list-post’) … If you overrride get_success_url, then you can still use reverse, because get_success_url calls reverse when the view is run. class BlogCreateView(generic.CreateView): … def get_success_url(self): return reverse(‘blog:list-post’) However, you can’t use reverse with success_url, because … Read more

A real example of URL Namespace

Typically, they are used to put each application’s URLs into their own namespace. This prevents the reverse() Django function and the {% url %} template function from returning the wrong URL because the URL-pattern name happened to match in another app. What I have in my project-level urls.py file is the following: from django.conf.urls.defaults import … Read more