как перенаправить на страницу профиля и посмотреть данные вошедшего в систему пользователя в Django? - PullRequest
0 голосов
/ 01 мая 2020

Я работал над небольшим проектом, и он развивался плавно, пока я не получил дорожный блок. Однако я не могу перейти на страницу профиля. Мой веб-сайт работает следующим образом:

1) user sign up and redirect to login screen once registration successful.
2) user login and now he/she sees a form, where he/she needs to fill in mandatory fields
3) save and then either click on "profile" link(in the navbar) to see the profile data, or "save" button will redirect to the profile page automatically. 

пункт 3) не работает. Пока у меня есть гиперссылка в NavBar для «профиля». Но он ничего не делает, хотя я написал метод GET. Может быть, я не получаю данные должным образом.

Я просмотрел несколько веб-ссылок здесь и здесь в Stackoverflow, но их решения не работают для меня

Ниже приведены мои django данные о файлах:

views.py

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from django.contrib.auth.models import User
from .models import UserProfile
# from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .forms import SignUpForm, UserProfileForm
from django.views.decorators.csrf import csrf_exempt

def login_user(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            messages.success(request, f'login success')
            return redirect('bolo')
        else:
            messages.error(request, f'error while login, please try again')
            return redirect('login')
    else:
        return render(request, 'authenticate\\login.html', {})

Я также обнаружил, что мы можем использовать декоратор @login_required. Итак, я реализовал его, как показано ниже, для метода, который записывается в GET-данные из базы данных

@login_required
def profile_page(request):
    if request.method == "GET" and request.GET:
        form = UserProfileForm()
        sec_data = UserProfile.objects.all()
        context = {'form': form, 'sec_data': sec_data}
    else:
        return redirect('bolo')
    return render(request, 'authenticate\\profile.html', context)

urls.py

from django.urls import path
from .views import home, login_user, logout_user, register_user, userProfileView, profile_page

urlpatterns = [
    path("home/", home, name='home'),
    path("login/", login_user, name='login'),
    path("logout/", logout_user, name='logout'),
    path("register/", register_user, name='register'),
    path("bolo/", userProfileView, name='bolo'),
    path('profile/', profile_page, name='profile'),
]

models.py

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    Photo = models.FileField(upload_to='documents/%Y/%m/%d/', null=True)
    uploaded_at = models.DateTimeField(auto_now_add=True, null=True)
    dob = models.DateField(max_length=20, null=True)
    country = models.CharField(max_length=100, null=True)
    State = models.CharField(max_length=100, null=True)
    District = models.CharField(max_length=100, null=True)
    phone = models.CharField(max_length=10, null=True)

    def get_absolute_url(self):
        return reverse('profile', kwargs={'id': self.id})
* Профиль 1025 *. html
    {% extends 'base.html' %}
    {% load static %}
    {% block content %}

    <!--<form method="GET" enctype="multipart/form-data">-->
    <title>User Detailed Profile</title>
        {% if user.is_authenticated %}
            {% for data in sec_data %}
                Photo:
                <p><img src = {{ data.image.url }} width="200" height="200" /></p>
                <p>DOB:{{ data.dob }}</p>
                <p>Country: {{ data.country }}</p>
                <p>State: {{ data.State }}</p>
                <p>District: {{ data.District }}</p>
            {% endfor %}
        {% else %}

        {% endif %}

    <!--</form>-->
    {{data.errors}}
    {% endblock %}

base.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <title>Django People</title>
  </head>
  <body class="p-3 mb-2 bg-warning text-dark">
    <div class="container"python >
      <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
  <ul class="navbar-nav">
    {% if user.is_authenticated %}
    <li class="nav-item active">

      <a class="nav-link" href="{% url 'logout' %}">Logout</a>
    </li>
     {% else %}
    <li class="nav-item active">

      <a class="nav-link" href="{% url 'login' %}">Login</a>
    </li>
    {% endif %}

    <li class="nav-item active">
      <a class="nav-link" href="#">Contact</a>
    </li>

    <li class="nav-item active">
      <a class="nav-link" href="{% url 'profile' %}">Profile</a>
    </li>

  </ul>
</nav>

      <div class="row justify-content-center">
        <div class="col-8">
          <h1 class="mt-2">Django People</h1>
          <hr class="mt-0 mb-4">

        </div>
      </div>
    </div>

  </body>
</html>
          {% block content %}
          {% endblock %}

Пожалуйста, помогите, спасибо.

добавлена ​​последняя ошибка, как показано ниже:

RelatedObjectDoesNotExist at /profile/
User has no userprofile.
Request Method: GET
Request URL:    http://127.0.0.1:8000/profile/
Django Version: 3.0.5
Exception Type: RelatedObjectDoesNotExist
Exception Value:    
User has no userprofile.

signal.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import UserProfile


@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.userprofile.save()

Новая ошибка:

RelatedObjectDoesNotExist at /profile/
User has no userprofile.
Request Method:
GET
Request URL:
http://127.0.0.1:8000/profile/
Django Version:
3.0.5
Exception Type:
RelatedObjectDoesNotExist
Exception Value:
User has no userprofile.
Exception Location:
C:\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py in __get__, line 420
Python Executable:
C:\Python38\python.exe
Python Version:
3.8.2
Python Path:
['C:\\Users\\anshu\\djago-project\\SkoolSkill',
 'C:\\Python38\\python38.zip',
 'C:\\Python38\\DLLs',
 'C:\\Python38\\lib',
 'C:\\Python38',
 'C:\\Python38\\lib\\site-packages']
Server time:
Sat, 2 May 2020 09:08:02 +0000

1 Ответ

0 голосов
/ 01 мая 2020

Я думаю, что проблема в том, что вы проверяете request.GET в своем представлении profile_page, и это возвращает false. Это означает, что контекст не создается и не передается в функцию рендеринга (я ожидаю, что при попытке доступа к странице будет выдана ошибка).

@login_required
def profile_page(request):
    if request.method == "GET" and request.GET: # remove this line and the if/else
        form = UserProfileForm()
        sec_data = UserProfile.objects.all()
        context = {'form': form, 'sec_data': sec_data}
    else:
        return redirect('bolo')
    return render(request, 'authenticate\\profile.html', context)

Редактировать: вторая ошибка возникает из-за того, что UserProfile еще не существует, вы можете либо запретить доступ к странице, когда UserProfile не существует, либо автоматически создать профиль при сохранении пользователя, пример ниже.

from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
...