Reputation: 211
I am relatively new to Django, and web development in general. Basically, I want to pull a logged in users data from a database table so he can view/edit it on a 'My profile' page.
I'm guessing the best way to do this would be to call the logged in users 'id', then somehow use it to call the row in the database table I want?
This is how far I have got, but I don't want the user's 'id' in the url, I want the users 'row id' in the database table:
urls.py
url(r'^my-profile/(?P<id>[0-9]+)', my_profile, name="my_profile"),
views.py
user = request.user
template
<a href="{% url 'my_profile' id=user.id %}">My profile</a>
Any help would be much appreciated!
My current code:
models.py
class BarSignUp(models.Model):
LOCATION_CHOICES=(
("Central London", "Central London"),
("North London", "North London"),
("East London", "East London"),
("South London", "South London"),
("West London", "West London"),
)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=50)
bio = models.CharField(max_length=50)
area = models.CharField(max_length=50, choices=LOCATION_CHOICES, null=True)
booking_link = models.CharField(max_length=100, null=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.email
def get_absolute_url(self):
return reverse("barber_profile", kwargs={"id": self.id})
Upvotes: 0
Views: 1634
Reputation: 2360
Foreignkey is a Many-to-One relationship.So if you want to access all the logged-in users BarSignUp data, then you should do the following.
views.py
signups = request.user.barsignup_set.all()
template
{% for barsignup in signups %}
{{ barsignup }}
{{ barsignup.field }}
{% endfor %}
Also there is an error in you BarSignUp str method, please correct the same.
def __str__(self):
return self.user.email #if you want to display user email
Upvotes: 0
Reputation: 77892
Your BarSignUp
model has a ForeignKey on User
, which mean you can have zero, one, or many (for the largest possible definition of "many" - could be literally millions) of BarSignUp
records related to one given user. If that's really what you want, then request.user.barsignup_set.all()
will return them all (cf the FineManual).
If what you want is one single BarSignUp
per user, then you want a OneToOne
field instead of a ForeignKey
, and once you've updated your models you can get the current logged-in user BarSignUp
with request.user.barsignup
(this is document too)
Upvotes: 0
Reputation: 308829
As you already know, you can get the logged-in user with request.user
. Therefore you can remove the id from the regex and use r'^my-profile/$'
.
Then change your url tag to {% url 'my_profile' %}
.
Upvotes: 1