How to know if there is a user in a model - python

I have been trying to create a view that lets a user create a "profile" but if the user already has a profile then the user is redirected to page where the user can see other people's profiles(in order to see this other people's profiles, the user has to create a profile as a requirement), for doing this proces I have 2 templates, one that has a form to create the profile and other one that displays other user's profile. The error is that every user is redirected to mates-form.html even the ones that already have a profile. So far I think that the error is on the views.py file.
models.py
class Mates(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usermates')
users_requests = models.ManyToManyField(User, related_name="users_requests")
req_bio = models.CharField(max_length=400)
req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False)
views.py
def matesmain(request):
contents = Mates.objects.all()
if contents == request.user:
context = {
'contents': contents,
'form_mates': MatesForm(),
}
print("nice3")
return render(request, 'mates.html', context)
else:
return render(request, 'mates-form.html')
def mates(request):
if request.method == 'POST':
form_mates = MatesForm(request.POST, request.FILES)
if form_mates.is_valid():
instance = form_mates.save(commit=False)
instance.user = request.user
instance.save()
return redirect('mates-main')
print('succesfully uploded')
else:
form_mates = MatesForm()
print('didnt upload')
context = {
'form_mates': form_mates,
'contents': Mates.objects.all()
}
return render(request, 'mates-form.html', context)
forms.py
class MatesForm(forms.ModelForm):
class Meta:
model = Mates
fields = ('req_bio', 'req_image',)
exclude = ['user']
mates.html
{% if contents %}
{% for content in contents %}
Here is where the user can see other user's profiles
{% endfor %}
{% endif %}
mates-form.html
<form method="post" enctype="multipart/form-data">
{{ form_mates.as_p }}
</form>
If you have any questions or if you need to see more code please let me know in the comments, also I thought of other way for doing these removing the if statements from matesmain view and just using them on the html but that didnt work.

I suppose the user will have only one profile so Instead of ManyToOneRelation i.e. ForeignKey using OneToOneRelation with the User Model would be better.
class Mates(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates')
Now while creating the profile you can check whether the user profile already exists or not like this:
def mates(request):
if Mates.objects.filter(user=request.user).exists():
return redirect('redirect_to_some_view_you_want')
if request.method == 'POST':
form_mates = MatesForm(request.POST, request.FILES)

Related

Django Validation is working on django admin but not working on html template

I'm creating a form where if we register it should save data to the database if the form is valid. otherwise, it should raise an error but it doesn't save data to the database, and also some fields are required but if I submit the form it doesn't even raise the error field is required. but if I register it manually on Django admin pannel it works perfectly fine.
here is my model:
class foodlancer(models.Model):
Your_Name = models.CharField(max_length=50)
Kitchen_Name = models.CharField(max_length=50)
Email_Address = models.EmailField(max_length=50)
Street_Address = models.CharField(max_length=50)
City = models.CharField(max_length=5)
phone = PhoneNumberField(null=False, blank=False, unique=True)
def __str__(self):
return f'{self.Your_Name}'
also, I disabled html5 validation
forms.py
class FoodlancerRegistration(forms.ModelForm):
phone = forms.CharField(widget=PhoneNumberPrefixWidget(initial="US"))
class Meta:
model = foodlancer
fields = "__all__"
views.py:
def apply_foodlancer(request):
form = FoodlancerRegistration()
return render(request, 'appy_foodlancer.html', {"form": form})
and finally Django template
<form method="POST" novalidate>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="cta-btn cta-btn-primary">Submit</button>
</form>
Thank you for your time/help
You don't have any form saving logic in your view.
Try something like this:
def apply_foodlancer(request):
if request.method == 'POST':
form = FoodlancerRegistration(data=request.POST)
if form.is_valid(): # if it's not valid, error messages are shown in the form
form.save()
# redirect to some successpage or so
return HttpResponse("<h1>Success!</h1>")
else:
# make sure to present a new form when called with GET
form = FoodlancerRegistration()
return render(request, 'appy_foodlancer.html', {"form": form})
Also check that the method of your form in your HTML file is post. I'm not sure if POST also works.
Avoid defining fields in a modelform with __all__. It's less secure, as written in the docs

How to determine if a user has created a profile on django

I have been working on a view in which all of the users profiles are displayed but so that a user can see other peoples profiles in that page, the user has to first create a profile. So every user who has already created a profile can go to that page but if the user havent created one yet, then the user goes to a form until it has a profile. To make this happen, I am using if statments to determine if the user has a profile or not but this is not working because every user is being redirected to the form part of the page even if the user has already a profile. How can this error be fixed, is there something wrong with the database? Is there other way to make these happen besides using if statements on the html?
models.py
class Mates(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usermates')
users_requests = models.ManyToManyField(User, related_name="users_requests")
req_bio = models.CharField(max_length=400)
req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False)
views.py
def matesmain(request):
contents = Mates.objects.all()
context = {
'contents': contents,
'form_mates': MatesForm(),
}
print("nice3")
return render(request, 'mates.html', context)
def mates(request):
if request.method == 'POST':
form_mates = MatesForm(request.POST, request.FILES)
if form_mates.is_valid():
instance = form_mates.save(commit=False)
instance.user = request.user
instance.save()
return redirect('mates-main')
print('succesfully uploded')
else:
form_mates = MatesForm()
print('didnt upload')
context = {
'form_mates': form_mates,
'contents': Mates.objects.all()
}
return render(request, 'mates.html', context)
urls.py
urlpatterns = [
path('mates', views.mates, name='mates'),
path('mates-main', views.matesmain, name='mates-main'),
]
mates.html
{% if not contents.user == user %}
FORM GOES HERE
{% elif contents.user == user %}
{% for content in contents %}
USER PROFILES HERE
{% endfor %}
{% endif %}
If there are any questions or need to see more code please let me know in the comments:)
Mates.objects.all() is returning you every User in your database, but objects.all() doesn't have a method called .user(), you should use something like:
Mate.objects.get(name__exact='username')
You could look a the django docs to know more about how to make queries
https://docs.djangoproject.com/en/3.0/topics/db/queries/

Django hidden field is not saving to database

I am trying to save users IP address in my extended profile model. The goal is to make this a hidden field. Currently, I can debug by printing the IP address to the console. The issue arises when I try and save the info.
views.py
def index(request):
#request.session.flush()
if request.user.is_authenticated:
return redirect('ve:dashboard')
elif request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.refresh_from_db() # Load the profile instance created by the Signal
user.profile.birth_date = form.cleaned_data.get('birth_date')
user.ipaddress = get_ip(request)
print(user.ipaddress)
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('ve:dashboard')
else:
form = RegistrationForm()
return render(request, 'index.html', {'form': form})
forms.py
class RegistrationForm(UserCreationForm):
# birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD')
birth_date = forms.DateField(widget=SelectDateWidget(years=range(1999, 1910, -1)))
#ipaddress = forms.IntegerField(widget=forms.HiddenInput(), required=False)
class Meta:
model = User
fields = ('username', 'email', 'birth_date', 'password1', 'password2',)
exclude = ['ipaddress',]
index.html
<form method="post">
{% csrf_token %}
{% for field in form %}
<p class="text-left">
{{ field.label_tag }}<br>
{{ field }}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
</form>
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
...
ipaddress = models.CharField(default="0.0.0.0", max_length=30)
This form was working fine before I tried adding the ipaddress field. I've been trying several versions and sometimes the form creates a new user but the ipaddress is not saved..
The current code above gives me there error on POST:
DoesNotExist at / User matching query does not exist. Due to this line "user.refresh_from_db() # Load the profile instance created by the Signal"
From the docs:
This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False, then it will return an object that hasn’t yet been saved to the database.
So since you're passing commit in as False you're getting an unsaved instance back. Attempting to call refresh_from_db on an object that doesn't actually exist in the database will fail, as it is clearly doing. If the instance to a model has no id then refresh_from_db will fail when called on it.
As for the continuing inability to save IP address, I noticed that your form meta has the model set to the User object. The default Django User object has no ip address. I see that in the model file you linked you have a Profile model that does have an IP Address so in that case I think you simply have your form set up wrong. Or you need to handle the request differently.
Form change
Currently your form is attempting to create/modify a Django User model. Unless you've made a custom User model that you didn't show, this user model will not have an ipaddress as a field in the database meaning even if you set user.ipaddress = <address> and then save the user, the ip address won't persist outside of the current scope since all you did was declare a new variable for the user instance.
If you change your form to point at your Profile model you'll be able to save the address using profile.ipaddress = <address> and save it successfully. But you will have to update your template since by default it will only show the fields for your profile and not the user object associated with it.
Change Template/View
You can also change the template and view to accommodate it. Apparently your view is able to produce an IP Address using the get_ip function so for the time being I'll assume your template is fine as is so the only changes that need to be made are to your view.
Currently your view is getting an unsaved User instance back when it calls form.save. This means you need to save the user and then create a Profile model that references it with your ip address attached.
def index(request):
#request.session.flush()
if request.user.is_authenticated:
return redirect('ve:dashboard')
elif request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
# do anything you need to the unsaved user here
user.save()
prof = Profile.objects.create(user=user,
ipaddress=get_ip(request),
date=form.cleaned_data.get('birth_date')
# no need to save prof since we called objects.create
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('ve:dashboard')
else:
form = RegistrationForm()
return render(request, 'index.html', {'form': form})

Form is not saving user data into database Django

Python noob here trying to learn something very simple.
I'm trying to create a basic form that takes some personal information from a user and saves it into a sqlite3 table with the username of the user as the primary key.
My models.py looks like this:
class userinfo(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key= True,
on_delete=models.CASCADE)
name = models.CharField(max_length = 200, blank = True)
email = models.EmailField(max_length= 300, default = 'Null')
phone = models.CharField(max_length= 10, default = 'Null')
def __unicode__(self):
return self.user
forms.py:
class NewList(forms.ModelForm):
class Meta:
model = userinfo
exclude = {'user'}
views.py
def newlist(request):
if request.method == 'POST':
form = NewList(request.POST)
if form.is_valid():
Event = form.save(commit = False)
Event.save()
return redirect('/home')
else:
form = NewList()
return render(request, 'home/newlist.html', {'form': form})
html:
{% load static %}
<form action="/home/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
urls.py too, but I don't know how that would help:
urlpatterns = [
url(r'^newlist/$', views.newlist, name='newlist')
]
So when I go to the url, I see the form. I can then fill the form, but when I submit the form, the data doesn't go into the database.
What am I doing wrong here?
Thanks in advance!
I think all you need to do is just save the form if it's valid, probably also add the userinfo as an instance of the form. You are also exluding the user from the form and need to assign it manually.
def newlist(request):
if request.user.is_authenticated():
user = request.user
if request.method == 'POST':
form = NewList(request.POST, instance=user.userinfo)
if form.is_valid():
form.save(commit=false)
form.user = user
form.save()
return redirect('/home')
else:
form = NewList(instance=user.userinfo) # add this if you want it to automatically fill the form with the old data if there is any.
return render(request, 'home/newlist.html', {'form': form})
The rest look like it should work.Except you need to send the post URL back to newlist:
{% load static %}
<form action="/newlist/" method="POST">
{% csrf_token %}
{{ form.as_p }}
</form>
If users are assigned at the creation of the model the first time, you don't need the user save, but since this is saving a users data you want to make sure they are logged in anyway:
def newlist(request):
if request.user.is_authenticated():
user = request.user
if request.method == 'POST':
form = NewList(request.POST, instance=user.userinfo)
if form.is_valid():
form.save()
return redirect('/home')
else:
form = NewList(instance=user.userinfo) # add this if you want it to automatically fill the form with the old data if there is any.
return render(request, 'home/newlist.html', {'form': form})
The instance is the model it is either going to save to, or copying data from. In the: form = NewList(request.POST, instance=user.userinfo) part, it is taking the POST data from the form, and linking that to the specific model entry of user.userinfo, however, it will only save to the database when you call form.save().
The user.userinfo is just so you can get the correct form to save to, as userinfo is a onetoone model to user. Thus making it possible to get it with user.userinfo.
The form = NewList(instance=user.userinfo) part is where it takes the currently logged in user's userinfo and copies into the form before it is rendered, so the old userinfo data will be prefilled into the form in the html. That being if it got the correct userinfo model.

Anonymous User - Displaying User Information

I am trying to display my users information but I am getting anonymous user as my output;
Anonymous User
My code in my views.py is as follows;
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
form = RegistrationForm()
args = {'form' : form}
return render(request, 'accounts/register.html', args)
def view_profile(request):
args = {'user': request.user}
return render (request, 'accounts/profile.html',args)
I am over-riding the UserCreationForm, my code in forms.py is;
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = {
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
}
def save(self,commit=True):
user = super(RegistrationForm,self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
My profile.html where I want my profile information to be displayed is;
{% block head %}
<title> User Profile </title>
{% endblock %}
{% block body %}
<div class="container">
<p>
<h1> {{user}}</h1>
<h3>First Name: {{user.first_name}}</h3>
<h3>Last Name: {{user.last_name}}</h3>
<h3>Email: {{user.email}}</h3>
</p>
</div>
{% endblock %}
Really not sure where I am going wrong any help is greatly appreciated.
you must decorate your def view_profile(request): with #login_required, otherwise Django will serve this request also to Anonymous users.
Also note that if you have (or add) django.core.context_processors.request to your settings.TEMPLATE_CONTEXT_PROCESSORS
(or settings.TEMPLATES['OPTIONS']['context_processors'] depending your django version) you can use {{request.user}} in your template without create specific entry in context.

Categories