How do I save a form with CreateView - python

I have a CreateView and inside this CreateView there is a form_valid() function. It gets the user_id and assigns it to the user that's logged in user id. The user is basically creating their own question and user_id is a foreign key.
class QuestionCreate(LoginRequiredMixin, CreateView):
model = Questions
form_class = CreatePost
def form_valid(self, form):
form.instance.user_id = self.request.user.id
return redirect("oauth:profile", username=self.request.user)
When I go to the URL of this view, I can see the view and when I try to submit a question it redirects me to the profile. However, the question is not saved in the database. I've tried inserting form.save() below the first line in form_valid and it does get saved in the table correctly, however, I don't get redirected to the profile, instead I get an error that states connection error what am I doing wrong?

Related

How to redirect user from registration page to profile if user is already registered?

I am using Django class-based views for my project and trying to redirect user from registration view if he is already authenticated. I've done it already with LoginView and it was pretty simple and looked just like adding few lines of code:
class Login(LoginView):
authentication_form = CustomAuthenticationForm
redirect_authenticated_user = True
LOGIN_REDIRECT_URL = "core:profile"
So after going to url for login, user ends up at his profile url. Absolutely simple and works perfectly.
However, there is no CBV for registration and therefore CreateView should be used, which doesn`t have any attributes for checking if user is authenticated.
The one method of doing something similar is UserPassesTestMixin, but it only gives me 403 Forbidden if user is authenticated, not redirect.
Here is my current registration view:
class Registration(UserPassesTestMixin, CreateView):
form_class = RegistrationForm
template_name = "registration/user_form.html"
success_url = reverse_lazy("core:profile")
def test_func(self):
return self.request.user.is_anonymous
def form_valid(self, form):
print(self.kwargs)
self.object = form.save(commit=True)
self.object.is_active = True
self.object.save()
login(self.request, self.object, backend="core.auth_backend.AuthBackend")
return HttpResponseRedirect(self.success_url)
Maybe somebody have done it already?
Would be very grateful for every advice!
In your Registration class, add a get method and remove your test_func:
def get(self,request,*args,**kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect('redirect_url')
return super().get(request,*args,**kwargs)

Django - Listing first model field values in second model createView form field for logged in user

I am trying to add a transaction (2nd model) for a specific account (1st model) based on the logged in user, either by listing the available account in the transaction creatView, or by clicking on the account name on the rendered HTML page.
class Account(models.Model):
account_holder_name = models.ForeignKey(User,to_field="username",on_delete=models.CASCADE)
# other fields
class Transaction(models.Model):
account = models.ForeignKey(Account,to_field="account_name",on_delete=models.CASCADE)
# other fields
I can add account successfully using below form_valid function in CreateView:
def form_valid(self, form):
userName = User.objects.get(username=self.request.user.username)
form.instance.account_holder_name = userName
return super().form_valid(form)
And also created ListView for accounts related to login user:
def get_queryset(self):
return Account.objects.filter(account_holder_name=self.request.user.username)
Rendering it in HTML by looping object list showing available accounts for the logged in user.
class Transaction(genric.creatView):
user=Account.objects.filter(account_holder_name=self.request.user.username)
tran_create=Transaction.object.create(account_name=user,**Kwargs)
tran_create.save()

How to attach current logged in user to object when object is created from django admin

I'm working on website whose an app which has class called Members whose a field that is related to the builtin User class from django.contrib.auth.models and it looks like
class Members(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
member_image = models.ImageField(upload_to='unknown')
member_position = models.CharField(max_length=255)
...
So as you can see when I'm adding member_image as a user I have also to select the user which doesn't make sense to me because I want to detect which user is logged in and pass his/her id as default parameter
like
class Members(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, default=request.user.id)
and after remove the user field in the admin panel like
class MembersAdmin(admin.ModelAdmin):
fields = ('member_image', 'member_position', ...)
so that if the user field doesn't selected it will set the logged in user_id by default
but to access request out of the views.py is not possible.
so how will I achieve this I also tried the following answers
Access session / request information outside of views in Django
Accessing request.user outside views.py
Django: How can I get the logged user outside of view request?, etc
but still not get it
Modify MembersAdmin save_model method and attach request.user to the object prior to saving.
class MembersAdmin(admin.ModelAdmin):
fields = ('member_image', 'member_position', ...)
def save_model(self, request, obj, form, change):
obj.user = request.user
super().save_model(request, obj, form, change)
For exclude the current logged in User for particular page or view, You can try this :-
from django.contrib.auth import get_user_model
User = user_model()
def some_view(request):
exclude_current_user = User.objects.exclude(user=request.user)

Django - perform action on Profile while creating User

I was looking for solution for my problem here, but it didnt solve my problem.
I want to create user's profile while their signing up.
To signup I use CreateView
class UserRegisterView(generic.CreateView):
form_class = SignUpForm
template_name = 'registration/register.html'
success_url = reverse_lazy('login')
#this method doesn't work and I get
# `Profile.user" must be a "User" instance`
def form_valid(self,form):
Profile.objects.create(user=self.request.user)
My Profile model looks like:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#rest of fields like bio, social urls etc
My main point is to automatically create user's profile when their create their account.
What is the best way to solve this?
I will suggest to avoid using signals, since you have a form.
self.request.user will return an user object only when an user is logged in using any form of authentication (Session, token etc.)
def form_valid(self,form):
user = form.save()
Profile.objects.create(user=user)
return super(UserRegisterView, self).form_valid(form)

Django CreateView with two forms at same page

I'm using Django and trying to display the detail of the person who has posted the data. So basically showing the username of the person who has posted the 'thing' defined in models.py
In views.py I'm trying:
def thing_detail_view(request, pk):
thing_detail = Thing.objects.get(pk=pk)
user = User.objects.get(request.user)
return render(request, 'thing_detail.html', {'thing_detail': thing_detail, 'user': user})
Im getting error:
'User' object is not iterable
But I know I should not use request.user because thats basically means the user who is having current session or currently logged in. Any idea how can I get the username of the user who has posted the data of a particular 'pk' and show it in the html?
I think you have to use userId = thing_detail.userId instead of request.user
userId can be your primery key for User Model

Categories

Resources