Reputation: 27
I'm writing an application and I want to be able to click on the username and go to the profile of the user. I have searched a lot around and didn't find anything that I wanted.
I want that when I press on Admin, I will be redirected to the profile with all the information that is saved through the Model that I created.
class Farmer(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE)
address = models.CharField(max_length=50)
age = models.IntegerField()
province = models.CharField(max_length=100)
company_name = models.CharField(max_length=30)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
products = models.CharField(max_length=200)
def __str__(self):
return self.name.username
How can I achieve something like this?
I thought that I need to write a function inside my views.py but I'm stuck and don't know how to go further.
def profile(request):
# something here..
return render(request, 'home_page/profile.html')
In my project the urlpattern is:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('home_page.urls')),
path('people/', include('people_page.urls')),
]
In my app people:
urlpatterns = [
path('',views.people, name='people-index'),
path('profile/', views.profile, name='profile-index')
]
The template:
<div class="sales">
{%for x in info%}
<div class="farmer-info">
<img src="{%static 'people_page/name.png' %}" alt="name icon" />
<span
><a href="{% url 'profile-index'%}">{{ x.name }}</a> <span>{{ x.company_name }}</span>
<hr
/></span>
</div>
{%endfor%}
Upvotes: 0
Views: 678
Reputation: 351
views.py
from django.shortcuts import render, get_object_or_404
from .models import Farmer
def profile(request, id):
farmer = get_object_or_404(Farmer, id=id)
context = {
'farmer': farmer,
}
return render(request, 'home_page/profile.html', context)
urls.py:
path('profile/<id>/', views.profile, name='profile-index')
template.html
<a href="{% url 'profile-index' x.id %}">{{ x.name }}</a>
Upvotes: 2