Django AbstractUser ManyToManyField did not get anything - django

I have created an abstract user model in Django. The user belongs to multiple services. When I register the user to database then the user has been register instead user_services. user_services are not stored in database while we register the new user.
models.py
class UserAbstract(AbstractUser):
user_services = models.ManyToManyField(UserServices, related_name='services', blank=True)
is_expert = models.BooleanField(default=False)
forms.py
class UserRegistrationForm(UserCreationForm):
class Meta:
model = UserAbstract
fields = [
'username',
'email',
'password1',
'password2',
'user_services',
'is_expert',
]
views.py
def Register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
user = form.save()
if user is not None:
login(request, user)
messages.success(request, f'{username} account has been registered!')
return redirect('profile')
else:
messages.error(request, "Invalid username or password.")
else:
form = UserRegistrationForm()
return render(request, 'user/register.html', {'form': form})

I just need to add this line after save the user!
user = form.save()
user.user_services.set(services) # services

Related

how to identify and set User model foreign keys in User details database on submitting my User Registration form

As I mentioned above I want to automatically identify the User's id from the User model and set it in my User details model as foreign key on Submitting Registration form curenty I am making changes manully to testing purpose which is not a practice for standalone website
models.py
class Student_Details(models.Model):
u_id=models.ForeignKey(User,null=True,on_delete=models.SET_NULL)
field=models.CharField(max_length=400,null=True)
class Institute_Details(models.Model):
I_id=models.ForeignKey(User,null=True,on_delete=models.SET_NULL)
name=models.CharField(max_length=400,null=True)
zipcode=models.CharField(max_length=6,null=True)
def __str__(self):return str(self.name)
class Staff_Details(models.Model):
s_id=models.ForeignKey(User,null=True,on_delete=models.SET_NULL)
Institute_from=models.ForeignKey(Institute_Details,null=True,on_delete=models.SET_NULL)
def __str__(self):return str(self.s_id)
form.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['id','username','first_name','last_name','email', 'password1', 'password2']
class Institute_form(ModelForm):
class Meta:
model = Institute_Details
fields=['name','zipcode']
viewspy
#unauthenticated_user
def registerPage(request):
form = CreateUserForm()
form2 = Institute_form(request.POST)
if request.method == 'POST':
form = CreateUserForm(request.POST)
form2 = Institute_form(request.POST)
if form.is_valid():
if request.POST.get('user_type') == 'User':
user1 = form.save()
group1 = Group.objects.get(name='Student')
user1.groups.add(group1)
elif request.POST.get('user_type') == 'Institute':
user2 = form.save()
form2.save()
group2 = Group.objects.get(name='Institute')
user2.groups.add(group2)
return redirect('default')
context = {'form': form,'Iform':form2}
return render(request, "htmls/signup.html", context)
def logoutUser(request):
logout(request)
return redirect('default')

What is the easiest way to require the user to fill in default fields of the User model like first name and last name in Django in UserCreationForm?

I am using Django built-in authentication views and form to create a registration/login system, and I'm using the UserCreationForm to register a user but only the username is required. I only want to make other User fields required as well. What is the simplest way to do that without creating a new user model?
Here are my forms:
# Create user registration form class.
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)
And here are my views:
def register(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('index'))
elif request.method == 'GET':
form = CustomUserCreationForm()
elif request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
context = {
'user': request.user,
}
return HttpResponseRedirect(reverse('index'), context)
else:
return HttpResponseRedirect(reverse('register'))
else:
return HttpResponse("Project 3: TODO")
context = {
'form': form,
}
return render(request, 'registration/signup.html', context)
You can override the fields for first and last name on the form to make them required. Note, this won't change the fact that the database table still allows null values for those fields
class CustomUserCreationForm(UserCreationForm):
first_name = forms.CharField(required=True, max_length=150)
last_name = forms.CharField(required=True, max_length=150)
class Meta:
model = User
fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)

Form after registration is not submitting Django

To complete registration, I want users to complete secondary form. However secondary form is not submitting. I think user is not getting authenticated in the registration and then the secondary form is not submitting. The login() seems to not work.
# the form in this view that's not submitting
def agreements(request):
if request.method == "POST":
form = AgreementsForm(request.POST)
if form.is_valid():
user = request.user
agree = form.save(commit=False)
agree.save()
else:
raise ValidationError("Form is not valid. Try Again.")
else:
form = AgreementsForm()
return render(request, 'agree.html', {'form': form})
Here is the forms.py for the agreements:
class AgreementsForm(forms.ModelForm):
non_ent=forms.BooleanField(label='kdmkl kdldsk')
agreement1=forms.BooleanField(label='dmklsd. lkdfmld')
class Meta:
model = Agreements
fields = ('non_ent', 'agreement1')
def save(self, commit=True):
agree = super(AgreementsForm, self).save(commit=False)
agree.non_ent = self.cleaned_data['non_ent']
agree.agreement1 = self.cleaned_data['agreement1']
if commit:
agree.save()
return agree
Here is the initial registration view:
# register view which submits, but I think it's not authenticating the user
def registration(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = True
user.save()
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
return redirect('agreements_page')
else:
raise ValidationError("Form is not valid. Try Again.")
else:
form = CustomUserCreationForm()
return render(request, 'register.html', {'form': form})
Agreements Model:
class Agreements(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,blank=True, null=True)
non_ent = models.BooleanField(default=False, blank=True, null=True)
agreement1 = models.BooleanField(default=False, blank=True, null=True)
date = models.DateTimeField(default=datetime.now, blank=True, null=True)
def __str__(self):
return f'{self.user} ({self.date})'
You need to authenticate user first to login :
def registration(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = True
user.save()
# authenticate user first
user = authenticate(request,username=form.cleaned_data['username'],password=form.cleaned_data['password'])
if user:
login(request, user)
return redirect('agreements_page')
Then in your secondary form you can save request.user like this .
I hope you have a OneToOne relation with user in your Agreement model.
form = AgreementsForm(request.POST)
if form.is_valid():
agree = form.save(commit=False)
agree.user = request.user
agree.save()

Seller object has no attribute profile

I am developing a django website where seller can open their accounts and update their profiles,so while while creating seller account I want to create a profile objects,my code of user registration form is given below,
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
date_of_birth = forms.DateField(required=True,
input_formats=settings.DATE_INPUT_FORMATS)
class Meta:
model = User
fields = ['username', 'email', 'date_of_birth', 'password1',
'password2']
def save(self, commit=True):
date_of_birth = self.cleaned_data.pop('date_of_birth', None)
user = super(UserRegisterForm, self).save(commit)
seller = Seller.objects.create(name=user.username,
date_of_birth=date_of_birth, created_by=user)
profile = Profile.objects.create(seller=seller)
return user
my code for become_seller in views.py is,
def become_seller(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('seller_dashboard')
else:
form = UserRegisterForm()
return render(request, 'become_seller.html',{'form':form})
all of this is working fine,but when I go for edit profile,my code for edit in views.py is,
#login_required
def edit(request):
if request.method == 'POST':
profile_form =
ProfileEditForm(instance=request.user.seller.profile,
data=request.POST, files=request.FILES)
if profile_form.is_valid():
profile_form.save()
else:
profile_form =
ProfileEditForm(instance=request.user.seller.profile)
return render(request, 'profile_edit.html',
{'profile_form':profile_form})
so,while working for this I found the following error message
AttributeError at /seller/edit/ 'Seller' object has no attribute 'profile'
can anyone help me to sort out this issue please
try register also ListingAdmin like admin.site.register(Listing, ListingAdmin) instead of trying to register only model class
ListingAdmin is not registered in admin.site.register()
The issue is solved by using related_name = profile

How to update django auth User using a custom form

I am using Django's built in authentication to manage users on a social media website. I am using a one-to-one relationship to attach a profile to each user. I can update all the parts of the profile I have attached using an UpdateView. However I don't know how to do that with Django's built in User. So I created a form that uses the _meta class. I have gotten to the point where my form will add a new user instead of update the current one. I was hoping one of you could help me fix my code. Thanks in advance for any help you can offer
views.py
class PrivProfileUpdate(View):
form_class = UserUpdateForm
template_name = 'user/user_form.html'
#display a blank form
def get(self, request, pk):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
#proces form data
def post(self, request, pk):
form = self.form_class(request.POST)
user = User.objects.get(pk=pk)
if form.is_valid():
user = form.save(commit=True)
print("we are trying to save")
#cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
user.set_password(password) #this is the only way to change a password because of hashing
user.save()
return render(request, self.template_name,{'form': form})
forms.py
class UserUpdateForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password', 'first_name', 'last_name']
SOLUTION:
in views.py
class PrivProfileUpdate(UpdateView):
model = User
form_class = UserUpdateForm
template_name = 'user/user_form.html'
def form_valid(self, form):
user = form.save(commit=True)
password = form.cleaned_data['password']
user.set_password(password)
user.save()
return redirect('user:index')
There's nothing special about the User class here. Just as with any other model, to update an existing instance you pass it as the instance argument to the form.
However, you do not actually need to do this at all yourself. You should be using an UpdateView, which does this for you; then you do not need to define get and post. The only method you need to define here is form_valid, to set the password:
class PrivProfileUpdate(UpdateView):
form_class = UserUpdateForm
template_name = 'user/user_form.html'
def form_valid(self, form):
user = form.save(commit=True)
password = form.cleaned_data['password']
user.set_password(password)
user.save()
return HttpResponseRedirect(self.get_success_url())