Remove user in Django - python

I would like to remove user.
I know that probably I can use some library like allauth but I want to do this on my view.
I didn't find any tutorial for that so I am trying to do this learn-by-mistakes way.
Ok. so in urls I have:
urlpatterns = [
('^remove$', views.remove_user, name="remove"),
]
forms:
class RemoveUser(forms.ModelForm):
class Meta:
model = User
fields = ('username',)
views:
#login_required(login_url='http://127.0.0.1:8000/')
def remove_user(request):
if request.method == 'POST':
form = RemoveUser(request.POST)
username = request.POST.get('username')
if form.is_valid():
rem = User.objects.get(username=username)
rem.delete()
return redirect('main')
else:
form = RemoveUser()
context = {'form': form}
return render(request, 'remove_user.html', context)
I can access website and type text in textfield. When I type random username I get error "user does not exist" so everything ok, but when I type correct username I get message: "A user with that username already exists" and this user is not removed.
Please, can you help me with that?

Change your form to a normal form-
class RemoveUser(forms.Form):
username = forms.CharField()
The view will be as follows -
#login_required(login_url='http://127.0.0.1:8000/')
def remove_user(request):
if request.method == 'POST':
form = RemoveUser(request.POST)
if form.is_valid():
rem = User.objects.get(username=form.cleaned_data['username'])
if rem is not None:
rem.delete()
return redirect('main')
else:
## Send some error messgae
else:
form = RemoveUser()
context = {'form': form}
return render(request, 'remove_user.html', context)
EDIT-- Another way to approach the same problem is to deactivate the user
if form.is_valid():
rem = User.objects.get(username=form.cleaned_data['username'])
if rem is not None:
rem.is_active = False
rem.save()

Related

Django - Unable to find object using pk (Matching query DoesNotExist)

Whenever I try to create a "Tour" for a "User" I get this error:
"DoesNotExist at /add-tour/FAjK5CryF8/ - User matching query does not exist."
Specifically the problems seems to come from this line of code:
user = User.objects.get(pk=pk)
models.py
class Tour(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
tour_date = models.DateField(default=date.today)
tour_fans = models.ForeignKey(FanAccount, on_delete=models.PROTECT)
def __str__(self):
return f"{self.user} del {self.tour_date}"
views.py
def tour_new(request, pk):
user = User.objects.get(pk=pk)
if request.method == "POST":
form = TourForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.tour_fans = request.user
form.instance.user = user
instance.save()
form.save()
return render(request, "tour.html", {"form": TourForm(), "success": True})
else:
form = TourForm()
return render(request, "tour.html", {"form": form})
For "User" I'm using a custom Primary Key (ShortUUID).
I'm new to Python and Django so it may be something easily solvable, but after hours of attempts I seem unable to solve it.
You need to make sure your user instance does exist, so you should instead of user = User.objects.get(pk=pk)call user = get_object_or_404(User, pk=pk), then you need to pass user as an instance:
if request.method == "POST":
form = TourForm(request.POST, instance=user)

How to remove "this field is not required" in django?

I found posts with similar problem, but the solutions dont seem to work with me. Or maybe I am missing something.
I created a form in Django, but as a default it seems that every mandatory fields have this "this field is required" text above.
Ideally, I would like to have this only when someone tries to submit a form and a field is missing.
form.py
class ElderFlowerChampFormAdmin(ModelForm):
fieldsets=[
("Look",{'fields':[
('look_colour','look_clarity','look_effervescence')]}),
}
widgets = {
'user': forms.Select(attrs={'class':'form-control','required':'True'}),
'look_colour':forms.Select(attrs={'class':'form-control','required':'True'}),
}
view.py
def elderflowerchamp(request, product_id):
global ChampageRating
product = Product.objects.get(pk=product_id)
url = request.META.get('HTTP_REFERER')
submitted = False
try:
if request.method == "POST":
reviews = ChampageRating.objects.get(pk=product_id)
if request.user.is_superuser:
form = ElderFlowerChampFormAdmin(request.POST, instance=reviews)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ElderFlowerChampForm(request.POST, instance=reviews)
if form.is_valid():
ChampageRating = form.save(commit=False)
ChampageRating.user = request.user
ChampageRating.save()
return redirect('home')
else:
#This part goes to the page, but doesnt submit
reviews = ChampageRating.objects.get(pk=product_id)
if request.user.is_superuser:
form = ElderFlowerChampFormAdmin
else:
form = ElderFlowerChampForm
if 'submitted' in request.GET:
submitted = True
except:
reviews = None
if request.user.is_superuser:
form = ElderFlowerChampFormAdmin(request.POST)
if form.is_valid():
data = ChampageRating()
data.rating = form.cleaned_data['rating']
data.look_colour = form.cleaned_data['look_colour']
data.ip = request.META.get('REMOTE_ADDR')
data.product_id = product_id
data.user_id = request.user.id
data.save()
messages.success(request, 'Thank you! Your review has been submitted.')
return redirect('home')
else:
form = ElderFlowerChampForm(request.POST)
if form.is_valid():
data = ChampageRating()
data.rating = form.cleaned_data['rating']
data.look_colour = form.cleaned_data['look_colour']
data.ip = request.META.get('REMOTE_ADDR')
data.product_id = product_id
data.user_id = request.user.id
data.save()
messages.success(request, 'Thank you! Your review has been submitted.')
return redirect('home')
return render(request,"main/ElderFlowerReview.html", {'form':form, 'submitted':submitted,'reviews':reviews, 'product':product})
models.py
LOOKCOLOUR=(
(1,'Straw'),
(2,'Yellow'),
(3,'Gold'),
(4,'Amber'),
)
class ChampageRating(models.Model):
user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE)
product=models.ForeignKey(Product,related_name="champcomments", on_delete=models.CASCADE)
look_colour=models.IntegerField(choices=LOOKCOLOUR, default=0)
def __str__(self):
return '%s - %s - %s'%(self.user, self.product, self.date_added)
Any ideas
something wrong on case request.GET here:
if request.user.is_superuser:
form = ElderFlowerChampFormAdmin
else:
form = ElderFlowerChampForm
You send the FormClass into the template context, and not the form instance.
Also see eror on the except case: If i have a GET, i should not render BoundedForm, here should be form.bounded = false (form is not bounded with any data). But you are always made the BoundedForm, with the request.POST data after error here:
reviews = ChampageRating.objects.get(pk=product_id)
My opinion is - you should try to read about Django-GCBV, it is better way to avoid complex errors, like in your question.
https://docs.djangoproject.com/en/4.0/topics/class-based-views/

Django login() authenticate always returns None

I have this code written up and it correctly registers users, though when it comes to the login function, it only works for the superuser i have in the database. Every time I try to log in a user that i greated using the register form, authenticate returns None.
I'm having it print the form data and can confirm that the form being submitted has accurate info, yet it fails authentication every time unless i login the superuser.
Views:
def register(request):
print(request.method)
if request.method == 'POST':
form = reg_form(request.POST)
print(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
email = form.cleaned_data.get('email')
phone = form.cleaned_data.get('phone')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
user = Users.objects.create(
username=username, email=email,
password=password, phone=phone,first_name=first_name, last_name=last_name
)
try:
user = Users.objects.get(phone=form.cleaned_data.get('phone'))
print("User exists")
except Users.DoesNotExist:
print("DoesNotExist")
return render(request, 'register.html', {'form': reg_form})
login(request, user)
return render(request, 'profile.html')
else:
print(form.errors)
return render(request, 'register.html', {'form': reg_form})
else:
return render(request, 'register.html', {'form': reg_form})
def log_in(request):
if request.method == 'POST':
form = log_form(request.POST)
print(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
print(user)
if user is not None:
print("user exists")
login(request, user)
return render(request, 'profile.html')
else:
print("user does not exist")
print(form.errors)
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})
Register form:
class reg_form(ModelForm):
class Meta:
model = Users
fields = '__all__'
widgets = { 'password': forms.PasswordInput(),
}
Login form:
class log_form(forms.Form):
username = forms.CharField(label='username', max_length=64)
password = forms.CharField(widget=forms.PasswordInput)
The password should be hashed: in Django the passwords are not stored in a readable format, but it stores the hash of that password. This concept is discussed in the changing password section of the documentation.
This thus means that for your reg_form, you save the object with:
class reg_form(ModelForm):
class Meta:
model = Users
fields = '__all__'
widgets = { 'password': forms.PasswordInput()}
def save(*args, **kwargs):
user = super().save(*args, **kwargs)
user.set_password(user.password)
return user
This is a very simple version of a more advanced form: the UserCreationForm perhaps it makes more sense, like #iklinac says, to subclass from that form, and slightly alter it to your specific model and fields.
Please check if the user is actually getting created in the database or not if the user is not getting created then make following changes to your register method:
use 'Users.objects.create_user' method instead of 'Users.objects.create', please find below link for more details:
https://docs.djangoproject.com/en/3.2/topics/auth/default/
Also hash your password as Willem is suggesting.

How to set default values in Forms

I am Building a BlogApp and i am stuck on a Problem.
What i am trying to do :-
I am trying to set the Default Value in forms.py for a Form.
views.py
def new_topic(request,user_id):
profiles = get_object_or_404(Profile,user_id=user_id)
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(data=request.POST)
new_topic = form.save(commit=False)
new_topic.owner = profile
new_topic.save()
return redirect('mains:topics',user_id=user_id)
#Display a blank or invalid form.
context = {'form':form}
return render(request, 'mains/new_topic.html', context)
forms.py
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['topic_no','topic_title']
What have i tried :-
I also did by using initial , BUT this didn't work for me.
form = DairyForm(request.POST,request.FILES,initial={'topic_title': 'Hello World'})
The Problem
Default value is not showing when i open form in browser.
I don't know what to do
Any help would be appreciated.
Thank You in Advance
You need to pass initial in the GET method, like this:
if request.method == 'GET':
form = TopicForm(initial={'topic_title': 'Hello World'})
else:
More information can be found in documentation.
You have to use instance=TopicInstance If you want any specific instance to be default. Or you want any other initial you should pass it like this
def new_topic(request,user_id):
profiles = get_object_or_404(Profile,user_id=user_id)
if request.method != 'POST':
form = TopicForm(initial={'topic_title': 'Hello World'})#When displaying it for first time
else:
form = TopicForm(data=request.POST)
new_topic = form.save(commit=False)
new_topic.owner = profile
new_topic.save()
return redirect('mains:topics',user_id=user_id)
#Display a blank or invalid form.
context = {'form':form}
return render(request, 'mains/new_topic.html', context)

Django UserProfile Forms

I have a Django form that allows a user to save their UserProfile details, but it only allows this to occur once. Given that additional saves ask to create a new entry, but i have a one-to-one relation between the user field and user UserProfile field.
When a user is created a UserProfile entry is not created. Rather they cannot access their account until these details are filled out.
I want to pre-populate the form with existing data when a student goes to access the form a second time.
def student_details(request):
#this is a form
if request.user.is_authenticated():
if request.method == 'POST':
form = DetailsForm(request.user, request.POST, request.FILES)
if form.is_valid():
note = form.save(commit=False)
note.user = request.user
note.completed_form = True
note.save()
return HttpResponseRedirect('/student-portal/')
else:
if request.user.get_profile():
pass
form = DetailsForm(request.user)
else:
form = DetailsForm(request.user)
return render_to_response("student-details.html", {'form': form}, context_instance=RequestContext(request))
return HttpResponseRedirect('/')
Sorry guys just found out how to do this:
def student_details(request):
#this is a form
if request.user.is_authenticated():
if request.method == 'POST':
form = DetailsForm(request.user, request.POST, request.FILES)
if form.is_valid():
note = form.save(commit=False)
user_profile = UserProfile.objects.get(user=request.user)
if user_profile:
note.id = user_profile.id
note.user = request.user
note.completed_form = True
note.save()
return HttpResponseRedirect('/student-portal/')
else:
try:
user_profile = UserProfile.objects.get(user=request.user)
form = DetailsForm(request.user, instance=user_profile)
except:
form = DetailsForm(request.user)
return render_to_response("student-details.html", {'form': form}, context_instance=RequestContext(request))
return HttpResponseRedirect('/')
The idea here is to query to see if a user_profile linked to that user already exists and then specify the ID for that entry.

Categories