从表单对模型执行POST请求时,它不会为对象分配ID

时间:2017-02-23 03:44:11

标签: python django

当我从管理员添加帖子时,它会分配ID,我可以链接到帖子。我去那个地址时没有错误。但是,如果我创建一个帖子表格,我似乎并没有得到一个ID。我收到一个错误,指出没有匹配的查询。我以为ID是自动分配的。

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/reports/5/this-is-even-more-formal/

Django Version: 1.10.5
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'TheFishNetwork',
 'accounts',
 'subnetwork',
 'posts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/swapnil/PycharmProjects/fishnetwork/posts/views.py" in report_detail
  38.     user = User.objects.get(id=pk)

File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/db/models/query.py" in get
  385.                 self.model._meta.object_name

Exception Type: DoesNotExist at /reports/5/this-is-even-more-formal/
Exception Value: User matching query does not exist.

views.py

@login_required
def create_report(request):
    if request.method == "POST":
        if request.POST['title'] and request.POST['body']:
            report = FishingReport()
            report.title = request.POST['title']
            report.slug = slugify(report.title)
            report.body = request.POST['body']
            report.sub_network = SubNetwork.objects.get(sub_name=request.POST['sub'])
            report.pub_date = timezone.datetime.now()
            report.author = request.user
            report.save()
            return render(request, 'posts/createreport.html')
    else:
        subnetwork = SubNetwork.objects.all()
        return render(request, 'posts/createreport.html',
                      {'subnetwork': subnetwork})


def report_detail(request, pk):
    report = FishingReport.objects.get(id=pk)
    comments = Comment.objects.filter(parent_report=pk)
    user = User.objects.get(id=pk)
    return render(request, 'posts/report_detail.html',
                  {'report': report,
                   'comments': comments,
                   'user': user})

urls.py

urlpatterns = [
    url(r'^create/', views.create_report, name='create_report'),
    url(r'^(?P<pk>[0-9]+)/([-\w]+)/$', views.report_detail, name='report_detail'),
]

models.py

class FishingReport(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    body = models.TextField()
    pub_date = models.DateTimeField()
    author = models.ForeignKey(User)
    votes_total = models.IntegerField(default=1)
    sub_network = models.ForeignKey(SubNetwork)

    def get_absolute_url(self):
        return reverse('posts:report_detail',
                       args=[self.id,
                             self.slug])

    def __str__(self):
        return self.title

1 个答案:

答案 0 :(得分:1)

您使用相同的主键访问ReportUser

report = FishingReport.objects.get(id=pk)
comments = Comment.objects.filter(parent_report=pk)
user = User.objects.get(id=pk)

在网址中,pk=5似乎是您创建的报告的ID,而不是您尝试访问的用户的ID。并且,查看堆栈跟踪,似乎数据库中没有标识为5的用户。