E
E
Evgeny Abaev2021-01-14 09:57:37
Django
Evgeny Abaev, 2021-01-14 09:57:37

How to redirect a user from the comments to the page?

There is a controller that receives the user's id and redirects to his personal data page. I don't know what argument to pass in the request to redirect to the correct user

view.py

def post_detail(request, pk):
    post = Bb.objects.get(id=pk)
    comments = Response.objects.filter(post_id=pk)
    context = {'post': post, 'comments': comments}
    return render(request, 'bboard/bb_detail.html', context)


models.py
class Rreview(models.Model):
    """Отзывы"""
    email = models.EmailField()
    name = models.CharField(verbose_name="Имя", max_length=100, null=True)
    text = models.TextField(verbose_name="Сообщение", max_length=5000)
    parent = models.ForeignKey('self', verbose_name="Родитель", on_delete=models.SET_NULL, blank=True, null=True)
    post = models.ForeignKey(Bb, verbose_name="фильм", on_delete=models.CASCADE)


urls.pu
urlpatterns = [
    path('profile/<int:pk>/', profile_view, name='profile_view'),    
]


Here is where you need to submit your request.
<h3>Отзывы</h3>
    {% for comm in comments  %}
        <p><a href="{% url 'profile_view' comm.user.pk %}">{{ comm.name }}</a></p>
        <p>{{ comm.text }}</p>
        <br>
    {% endfor %}


Tell me how to pass the desired id?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Belokurov, 2021-01-14
@Norwich

As an id, you should pass not comm.user.pk, but comm.name.pk
But in general, I would recommend using the user name for the field, and not name, as you can see, such a name has already misled you.

V
Vladimir, 2021-01-14
@AstraVlad

I didn't understand something. After all, there is already a user id, the path with the user id is configured, what's the problem?
Although if the user is authorized, then nothing needs to be transmitted at all and no URLs need to be constructed, we take the user from the request and that's it.
Offhand from my code:

def users_add(request):
    if request.method == 'POST':
        ...
            login(request, user)
            # redirect to a new URL:
            return HttpResponseRedirect('/fighters/add/')

and get into:
def fighter_add(request):
    user = request.user

If you really want to go exactly by id, then:
urls.py
path('<int:pk>/', views.fighter_detail, name='fighter_detail')

views.py
def fighter_detail(request, pk):
    try:
        fighter = Fighters.objects.get(id=pk, active=True)
       ...
    except Fighters.DoesNotExist:
        context = {
            'result': 0,
        }

    return render(request, 'fighters/fighter_details.html', context)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question