gpt4 book ai didi

python - ValueError at/posts/create/invalidliteral for int() with base 10 : 'create' in django Form

转载 作者:行者123 更新时间:2023-12-01 08:18:33 24 4
gpt4 key购买 nike

我正在尝试在 django 中制作 Django 表单,但这给了我类似这样的错误。

ValueError at /posts/create/ invalid literal for int() with base 10: 'create'

我不知道它从哪里来。

models.py

from django.db import models
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length= 120)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)


def __unicode__(self):
return self.title

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse("posts:detail", kwargs={"id": self.id})
#return "/posts/%s/" %(self.id)

views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Post
from .forms import PostForm

def posts_create(request):
form = PostForm()
context = {
"form": form,
}
return render(request, "post_form.html", context)

forms.py

from django import forms

from .models import Post

class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"title",
"content"
]

posts/urls.py

from django.urls import path
from .views import (
posts_create,
posts_delete,
posts_detail,
posts_list,
posts_update
)

app_name = "posts"

urlpatterns = [
path("", posts_list, name="list"),
path("<id>/", posts_detail, name="detail"),
path("create/", posts_create, name="create"),
path("edit/", posts_update, name="update"),
path("delete/", posts_delete, name="delete"),

]

urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', include('posts.urls', namespace='posts')),
]

这是我添加的网址

最佳答案

问题是你的模式带有 <id> ,匹配任何内容,因此这也包括-整数项,因此 create等都将在第二个path时得到解决。为了仅匹配整数,您可以添加 int: path converter [Django-doc]对于它,这会将模式限制为数字元素:

# posts/urls.py

# ...

urlpatterns = [
path("", posts_list, name="list"),
# added int:
path("<<b>int:</b>id>/", posts_detail, name="detail"),
path("create/", posts_create, name="create"),
path("edit/", posts_update, name="update"),
path("delete/", posts_delete, name="delete"),

]

所以现在只有带有整数的 URL 才会“触发”第二条路径。对于类似 create/ 的路径等等。Django 将在列表中进一步查找匹配项,从而触发 posts_create查看。

关于python - ValueError at/posts/create/invalidliteral for int() with base 10 : 'create' in django Form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54839967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com