【问题标题】:"Page not found (404)" when clicking on follow or unfollow button单击关注或取消关注按钮时出现“找不到页面 (404)”
【发布时间】:2017-09-19 06:36:26
【问题描述】:

urls.py

"""stratinum URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from imagec import views as imagec_views
from contact import views as contact_views
from django.conf.urls.static import static
from django.conf import settings
from django.core.urlresolvers import reverse


admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', imagec_views.home, name='home'),
    url(r'^about/$', imagec_views.about, name='about'),
    url(r'^detail/$', imagec_views.detail, name='detail'),
    url(r'^profile/$', imagec_views.userProfile, name='profile'),
    url(r'^create_form/$', imagec_views.create_form, name='create_form'),
    url(r'^contact/$', contact_views.contact, name='contact'),
    url(r'^userProfile/$', contact_views.contact, name='userProfile'),
    url(r'^accounts/', include('allauth.urls')),
    url('', include('social.apps.django_app.urls', namespace='social')),
    url('', include('django.contrib.auth.urls', namespace='auth')),
    url(r'^$', imagec_views.ListaFollow, name="lista_follow"),
    url(r'^add_follow/(?P<id>\d{1,})/$', imagec_views.AddFollow, name='add_follow'),
    url(r'^remove_follow/(?P<id>\d{1,})/$', imagec_views.RemoveFollow, name='remove_follow')

]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from .forms import AlbumForm
from .models import Album


from django.http import HttpResponse,HttpResponseForbidden

IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg']

# Create your views here.
def home(request):
    context = {}
    template = 'home.html'
    return render(request, template, context)

def about(request):
    context = {}
    template = 'about.html'
    return render(request, template, context)

@login_required()
def userProfile(request):
    user = request.user
    context = {'user': user}
    template = 'profile.html'
    return render(request, template, context)



def create_form(request):
        form = AlbumForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            album = form.save(commit=False)
            album.user = request.user
            album.image= request.FILES['image']
            file_type = album.image.url.split('.')[-1]
            file_type = file_type.lower()
            if file_type not in IMAGE_FILE_TYPES:
                context = {
                    'album': album,
                    'form': form,
                    'error_message': 'Image file must be PNG, JPG, or JPEG',
                }
                return render(request, 'detail.html', context)
            album.save()
            return render(request, 'create_form.html', {'album': album})
        context = {
            "form": form,
        }
        return render(request, 'create_form.html', context)

def detail(request):
        user = request.user
        #album = get_object_or_404(Album, pk=id)
        return render(request, 'detail.html', {'user': user})


from django.shortcuts import render, redirect
from .models import MyUser

from django.views.generic import TemplateView,View
from django.db.models import Q
from django.core.urlresolvers import reverse
from . import models
#from imagec.models import User
from django.contrib.auth.models import Permission, User


class ListaFollow(TemplateView):
    template_name = 'lista_follow.html'
    def get_context_data(self,**kwargs):
        context = super(ListaFollow,self).get_context_data(**kwargs)
        context['all'] = MyUser.objects.all()
        context['me'] = User.objects.get(username=self.request.user)
        context['notme'] = MyUser.objects.filter(follow__username=self.request.user)
        context['notfollow'] = MyUser.objects.filter(~Q(follow__username=self.request.user))
        return context

class AddFollow(View):
    def get(self,request, id):
        me=models.MyUser.objects.get(username=request.user)
        followed = models.MyUser.objects.get(id=id) #el wey
        me.follow.add(followed)
        return redirect(reverse('imagec/about.html'))

class RemoveFollow(View):
    def get(self,request, id):
        me=models.MyUser.objects.get(username=request.user) #instancia del usuario con el id que quiero crear
        followed = models.MyUser.objects.get(id=id)
        me.follow.remove(followed) #creo el usuario con mi nombre y la relacion
        return redirect(reverse('imagec/about.html'))

models.py

from __future__ import unicode_literals
from django.contrib.auth.models import Permission, User

from django.db import models


# Create your models here.
class profile(models.Model):
    name = models.CharField(max_length=120)
    description = models.TextField(default='description default text')

    def __unicode__(self):
        return self.name


class Album(models.Model):
    user = models.ForeignKey(User, default=1)
    image = models.FileField()


class MyUser(models.Model):
    user = models.ForeignKey(User)
    username = models.CharField(max_length=200)
    follow = models.ManyToManyField('self', blank=True)

    def __unicode__(self):
        return self.username

关于.html

{% extends 'base.html' %}

{%  block   content %}
<body>
<div class="container">
    <h1>Profile</h1>
    <p>Username: {{ user }}</p>
    <p>Email: {{ user.email }}</p>

            <p><input type="submit" value="Upload"/></p>

</div>
<table>
<tr>
<th colspan="3"> @ {{ user }}</th>
</tr>

<tr>
<td colspan="3">
<span> Follows </span>
</td>
</tr>


<td>{{follow}} <a href="add_follow/{{user.id}}">
    <button>Follow</button></a></td>
<td>{{follow}} <a href="remove_follow/{{user.id}}">
    <button>Unfollow</button></a></td>
</a>
<tr>
<td colspan="3">
<span> Unfollows </span>
</td>
</tr>


</table>
</body>

{%  endblock    %}

当我运行这段代码时,我会得到如下错误:

“未找到:/about/add_follow/1 [22/Apr/2017 07:26:25]“GET /about/add_follow/1 HTTP/1.1”404 6063”

在终端中。

【问题讨论】:

    标签: html django python-3.x


    【解决方案1】:

    发生这种情况是因为您使用相对 url 来创建指向关注/取消关注页面的链接。要解决此问题,您可以将其设为绝对 url 或使用 django 的 url reverser。

    使链接成为绝对链接:

    <td>{{follow}} <a href="/add_follow/{{user.id}}">
        <button>Follow</button></a></td>
    <td>{{follow}} <a href="/remove_follow/{{user.id}}">
        <button>Unfollow</button></a></td>
    

    使用url tempalte tag

    <td>{{follow}} <a href="{% url 'add_follow' id=user.id %}">
        <button>Follow</button></a></td>
    <td>{{follow}} <a href="{% url 'remove_follow' id=user.id %}">
        <button>Unfollow</button></a></td>
    

    了解Absolute and Relative urls

    【讨论】:

    • 通过添加上面的代码,我得到了新的错误,因为“TypeError at /add_follow/1/ __init__() 需要 1 个位置参数,但给出了 2 个”
    • 发生这种情况是因为您的 url conf 不正确。使用基于类的视图时,您必须在视图上调用.as_view()。将网址更改为imagec_views.AddFollow.as_view()
    • 为此我收到错误,因为“MultipleObjectsReturned at /add_follow/1/get() 返回了多个专辑——它返回了 5 个!”
    • 这意味着你不是在查询一个唯一的字段,让你的查询要么返回一个最大的对象,不超过这个。
    • umm.... id 字段是唯一字段,因为它在 django 中设置为主键,您应该查询该字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多