Ryan Oh
Ryan Oh

Reputation: 657

How do I create user specific page with Django?

so I've just started studying Django, and ran into a problem.

I'm trying to create a user-specific page, in which if user logs in and inputs his/her info, the info is displayed on the screen, dynamically of course.

So let me show you the codes I wrote.
Here's models.py

class UserInfo(models.Model):
    authuser = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True, 
    default=None)
    name = models.CharField(max_length=50)
    introduction = models.CharField(max_length=100)

And here's views.py

@login_required(login_url="/register")
def main(response):
    thisUser = # I have no idea on which code to write here.
    return render(response, 'main.html', {'thisUser' : thisUser}) 

And here's the html file, main.html

{% extends 'base.html' %}

{% block content %}
{{thisUser.name}}
{{thisUser.introduction}}
{% endblock %}

So this is what I've done so far. I have completed all the registration/login/logouts, as well as the forms for letting users input their info(name, introduction). And the next step I'm trying to take is this user specific page, but I have no idea on how to create it.

I would very much appreciate your help. Thanks. :)

Upvotes: 0

Views: 1272

Answers (2)

Paritosh Yadav
Paritosh Yadav

Reputation: 347

better to change user field to onetoone field

thisUser = UserInfo.objects.get(authuser=request.user)

(also change def main(response) to def main(request)/same in render also)

request.user will give you current login user object

you can do same in template example:

<h1>Name: {{request.user.name}}</h1>

Upvotes: 0

l.b.vasoya
l.b.vasoya

Reputation: 1221

First You user OneToOneField in Your UserInfo model as i give

class UserInfo(models.Model):
    authuser = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True, 
    default=None)
    name = models.CharField(max_length=50)
    introduction = models.CharField(max_length=100)

Then makemigrations and then migrate

I think you done login/singup with user model

after login what ever page you render that write only the give line @in you html file

{% extends 'base.html' %}

{% block content %}

Name         : {{ request.user.userinfo.name }}
Introduction : {{ request.user.userinfo.introduction }}

{% endblock %}

If you face problem with extends user of onetoone field i give link refer it

if still you have problem let me know..!

Upvotes: 1

Related Questions