I do not use admin apps in Django, and I want to edit the user with form, but when I edit the groups to the users, Django doesn't save my choice and user has no groups.
views.py:
def useredit(request, pk):
user = get_object_or_404(User, pk=pk)
if request.method == "POST":
form = EditUserForm(request.POST, instance=user)
if form.is_valid():
user.save()
messages.success(request, 'Utilisateur édité avec succés !')
return HttpResponseRedirect('/user')
else:
form = EditUserForm(instance=user)
return render(request, 'compta/users/edit.html', {'form': form})
forms.py:
class EditUserForm(UserChangeForm):
class Meta:
model = User
fields = '__all__'
def save(self, commit=True):
user = super().save(commit)
self._save_m2m()
return user
You need to save form instead of user instance
replace
if form.is_valid():
user.save()
#^^^^
with
if form.is_valid():
form.save()
#^^^^
Related
I was working on an e-commerce website using Django for which I created a customer model in models.py
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
def __str__(self):
return self.name
and when I register a new user on my site using this view:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('store')
else:
form = SignUpForm()
return render(request, 'store/signup.html', {'form': form})
The user gets created but I get the error RelatedObjectDoesNotExist: User has no Customer
I know it's because the User model is created but not Customer, I'm new to Django and want to know a way to map these two models at the time of registration.
In views.py when you register the user you can also a create a customer modal ıf its what you want. If so try this:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
Customer.objects.create(user=user,name=username,email=email) // get the email from the form
login(request, user)
return redirect('store')
else:
form = SignUpForm()
return render(request, 'store/signup.html', {'form': form})
Also can add your customer modal ın admin panel and manually add your customer info just for demonstration.
I currently have an index view with several input tags for a name, file and tags.
I'm trying to connect the model that handles that view (name: Uploaded) to the User model and associate the logged in users username to the Uploaded model.
Here's my view:
def index(request):
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
else:
form = FileUploadForm
allTags = Tag.objects.all()
context = {'form': form, 'allTags': allTags}
return render(request, 'index.html', context)
and here's the Uploaded model:
class Uploaded(models.Model):
objects: models.Manager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users")
name = models.CharField(max_length=50)
file = models.FileField(upload_to=MEDIA_ROOT)
tags = TaggableManager()
def __str__(self):
return f"{self.name} {self.file}"
You can "patch" the .instance wrapped in the form with the logged in user:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
else:
form = FileUploadForm()
allTags = Tag.objects.all()
context = {'form': form, 'allTags': allTags}
return render(request, 'index.html', context)
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
I write an app in django - sth like twitter, i have already log in/log out panel, and form when already logged in user can add a tweet.
A tweet has a 3 columns in database:
class Tweet(models.Model):
content = models.CharField(max_length=140)
creation_date = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
The form looks like:
class TweetForm(forms.Form):
content = forms.CharField(label='content')
And the view:
class TweetCreationView(LoginRequiredMixin, View):
permission_required = 'twitter.add_tweet'
raise_exception = True
permission_denied_message = 'You are not allowed being there!'
def get(self, request):
form = TweetForm()
return render(request, "twitter/add_tweet.html", {"form": form})
def post(self, request):
form = TweetForm(request.POST)
if form.is_valid():
if request.user.is_authenticated():
username = request.user.username
user_id = username.id
content = form.cleaned_data.get('content')
return render(request, "twitter/add_tweet.html", {"form": form})
How can i obtain an already logged in user in django and add his/her id to post view form?
do something similar to this. I did not check if this is working.
if request.user.is_authenticated():
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
content = form.cleaned_data.get('content')
form.save()
return render(request, "twitter/add_tweet.html", {"form": form})
Ok,
I've managed to do it in kinda primitive way:
def post(self, request):
form = TweetForm(request.POST)
if form.is_valid():
t = Tweet()
current_user = request.user
t.content = form.cleaned_data.get('content')
t.user_id = current_user.id
t.save()
if t:
return redirect(reverse("base"), locals())
return render(request, "twitter/add_tweet.html", locals())
I have a form that inherits from the UserCreationForm. The file looks like this:
from django import forms
from django.contrib.auth import password_validation
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, Group
from main.models.users import MyUser
class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
group = forms.CharField(max_length=50, required=True)
class Meta:
model = MyUser
fields = ("group", "email", "username", "email", "password1", "password2")
def save(self, commit=True):
user = super(MyUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
For some reason, when trying to fill up the form, I get a password mismatch error like so:
ERROR - {'password_mismatch': "The two password fields didn't match."}
I tried overriding the clean_password1 and clean_password2 with no help. Code:
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
# Method inherited from BaseForm
self.add_error('password1', error)
return password1
Any ideas why this is happening? Why is it thinking that both of my passwords are not identical? I'm sure they are, as I tried a million times and even copy and pasted.
view:
def register(request):
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
if form.is_valid():
print(f"Valid form. Choosen group: {form.cleaned_data.get('group')}")
user = form.save()
group = Group.objects.get(name=form.cleaned_data.get('group'))
user.groups.add(group)
login(request, user)
messages.success(request, f"Thanks, {form.cleaned_data.get('username')}, "
f"for signing up as a {form.cleaned_data.get('group')} ")
return redirect('main:homepage')
else:
logger.error(form.error_messages)
for msg in form.error_messages:
messages.error(request, f'{msg}: {form.error_messages[msg]}')
return render(request,
template_name='main/register.html',
context={'form': form})
else:
form = MyUserCreationForm()
return render(request,
template_name='main/register.html',
context={'form': form})
i am not sure about code but you can try this
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def signup(request):
if request.method == 'POST':
#inhereting Usercreation form
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
#validating the password match while creating the user.
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})
I am new to django, I an updating my userprofile models using forms and view,I need to get the current user who is logged in and I need to update the details for that user
forms.py
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('gender','email_id','mobile_number','date_of_birth')
View.py
def update_UserProfile_views(request):
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.save()
else:
form = ProfileForm()
return render(request, 'base.html', {'form': form})
You can create a instance and get user name
def update_UserProfile_views(request):
try:
current_user = request.user
user = UserProfile.objects.get(user_name=current_user)
except Exception:
return render(request, 'base.html', {})
else:
if request.method == "POST":
form = ProfileForm(request.POST,instance=user)
if form.is_valid():
profile = form.save(commit=False)
profile.save()
else:
form = ProfileForm()
return render(request, 'base.html', {'form': form})