Использование пути urls со slug возвращает Страница не найдена (404) Не найдено ни одного профиля, соответствующего запросу

Я пытаюсь создать профиль пользователя для моего проекта django, я использую UpdateView, чтобы позволить пользователю редактировать модель профиля, когда он хочет создать профиль для своего аккаунта, но он возвращает ошибку каждый раз, когда я нажимаю на create profile url в шаблоне профиля.

Шаблон профиля:

<div class="container">
    <div class="row justify-content-center">
        {% for profile in profiles %}
        <div class="col">
            <a href="{{profile.website}}">{{profile.website}}</a>
            <a href="{{profile.twitter}}">{{profile.website}}</a>
        </div>
        {% endfor %}
    </div>
</div>
<br>
<div class="container">
    <div class="row">
        <a href="{% url 'editProfile' user.id %}" class="btn btn-primary">Create Profile</a>
    </div>
</div>

Моя модель:

class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    profile_image = models.ImageField(upload_to="avatars/")
    stories = models.TextField(max_length=500,blank=True, null=True)
    website = models.URLField(max_length=250, blank=True, null=True)
    twitter = models.URLField(max_length=250, blank=True, null=True)
    location = models.CharField(max_length=50, blank=True, null=True)
    slug = models.SlugField(blank=True, null=True)

мои урлы:

path('editprofile/<slug:slug>/edit', views.EditProfileView.as_view(), name='editProfile'),

мои взгляды:

@login_required(login_url='login')
def profile(request, pk):
    profiles = Profile.objects.filter(user=request.user)
    questions = Question.objects.filter(user=request.user)
    context = {'questions':questions, 'profiles':profiles}
    return render(request, 'profile.html', context)

class EditProfileView(UpdateView):
    model = Profile
    fields = ['profile_image', 'stories', 'website', 'twitter', 'location']
    template_name = 'edit_profile.html'
    success_url = reverse_lazy('index')

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(Creator, self).save(*args, **kwargs)

Первое исправление

  def save(self, *args, **kwargs):
        self.slug = slugify(self.user.field) #field is what you want to slugfiy 
        super(Creator, self).save(*args, **kwargs)

во-вторых

Вы отправляете ID, но url требует slug

  #old
  <a href="{% url 'editProfile' user.id %}" class="btn btn-primary">Create Profile</a>

  #should be
  <a href="{% url 'editProfile' user.slug_field %}" class="btn btn-primary">Create Profile</a>

Вы сделали user OneToOneField в вашей Profile модели, это означает, что вы не должны использовать filter() в profile представлении, вы должны использовать get_object_or_404 для получения профиля одного пользователя, так как он имеет OneToOneRelation.

Попробуйте это:

from django.shortcuts import get_object_or_404
@login_required(login_url='login')
def profile(request, pk):
    profile = get_object_or_404(Profile,user=request.user)
    questions = Question.objects.filter(user=request.user)
    context = {'questions':questions, 'profile':profile}
    return render(request, 'profile.html', context)

class EditProfileView(UpdateView):
    model = Profile
    fields = ['profile_image', 'stories', 'website', 'twitter', 'location']
    template_name = 'edit_profile.html'
    success_url = reverse_lazy('index')

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(Creator, self).save(*args, **kwargs)


def index(request):
    return render(request, 'index.html')

profile.html:

    <div class="container">
        <div class="row justify-content-center">
            {% comment %} {% for profile in profiles %} {% endcomment %}
            <div class="col">
                <a href="{{profile.website}}">{{profile.website}}</a>
                <a href="{{profile.twitter}}">{{profile.website}}</a>
            </div>
            {% comment %} {% endfor %} {% endcomment %}
        </div>
    </div>
    <br>
    <div class="container">
        <div class="row">
            <a href="{% url 'editProfile' profile.slug %}" class="btn btn-primary">Create Profile</a>
        </div>
    </div>

Note: Я прошел profile.slug, так как EditProfileView также требует, чтобы слизень пришел по маршруту.

Note: Не следует запускать цикл при отображении данных с одним объектом.

index.html (шаблон успеха):

<body>
<h3>Profile updated successfully.</h3>
</body>

edit_profile.html

<body>
    <h2>You can edit your profile </h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Save">
    </form>
</body>

urls.py

urlpatterns = [
    path('profile-updated/', views.index, name='index'),
    path('profile/<int:pk>/', views.profile, name='profile'),
    path('editprofile/<slug:slug>/edit/',
         views.EditProfileView.as_view(), name='editProfile')
]

Это успешно обновит ваш профиль.

Вернуться на верх