[英]django rest framework dosent even show the option to upload image. I do have imageField in models
django rest framework dosent even show the option to upload image. django rest 框架甚至显示上传图像的选项。 I do have imageField in models.
我确实在模型中有 imageField。 I also get
GET http://127.0.0.1:8000/api/person-create/ 405 (Method Not Allowed)
in console when i go to the api url to create new item. I also get
GET http://127.0.0.1:8000/api/person-create/ 405 (Method Not Allowed)
in console when i go to the api url to create new item. TLDR I am trying to upload images using django rest framework i can do it from admin but not with DRF or frontend any help is appreciated Thanks. TLDR 我正在尝试使用 django rest 框架上传图像,我可以从管理员那里完成,但不能使用 DRF 或前端任何帮助,谢谢。
view.py视图.py
@api_view(['POST'])
def create_person(request):
serializer = PersonSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data)
serializer.py序列化程序.py
class PersonSerializer(serializers.ModelSerializer):
image = serializers.ImageField(max_length=None, allow_empty_file=False, allow_null=True, required=True)
class Meta():
model = Person
fields = 'name', 'about', 'created_at', 'email', 'image'
urls.py网址.py
urlpatterns = [
path('', views.apiOverview, name='apiOverview'),
path('persons/', views.all_persons, name='all_persons'),
path('person/<str:pk>', views.person, name='person'),
path('person-create/', views.create_person, name='create'),
path('person-update/<str:pk>', views.update_person, name='update_person'),
path('person-delete/<str:pk>', views.delete_person, name='delete_person'),
]
models.py模型.py
class Person(models.Model):
name = models.CharField(max_length=50)
about = models.CharField(max_length=10000)
created_at = models.DateTimeField(auto_now_add=True)
email = models.EmailField(unique=True)
image = models.ImageField(blank=True, null=True, upload_to='media/', default='default.png')
Heres the frontend part create.js这是前端部分 create.js
const Create = () => {
let history = useHistory();
let [person, setPerson] = useState({
name:"",
about:"",
email:"",
image:"",
})
let createPerson = async (e) => {
e.preventDefault()
fetch(`/api/person-create/`, {
method: "POST",
headers: {
"content-type": 'application/json'
},
body: JSON.stringify(person)
})
.then(setPerson({
name:"",
about:"",
email:"",
image:"",
}))
}
let handleChange = (e) => {
setPerson({...person, [e.target.id]: e.target.value});
console.log(person)
}
useEffect(() => {
console.log("correct", person);
}, [person]);
return (
<div class="container">
<div class="row justify-content-center">
<form onSubmit={(e) => createPerson(e)}>
<div>
<h2>
<button onClick={() => history.push('/')} className="btn btn-primary mt-4">
❮ Back
</button>
</h2>
<h2 className="mt-4 mb-4" style={{width: '600px'}}>
New Person
</h2>
<div className="form-group" style={{width: '600px'}}>
<label>Name</label>
<input onChange={handleChange} className="form-control" id="name" placeholder="Enter Name" value={person.name} />
</div>
<div className="form-group" style={{width: '600px'}}>
<label for="exampleInputEmail1">About</label>
<textarea style={{height: '250px'}} onChange={handleChange} className="form-control" id="about" placeholder="Tell us somthing about yourself" value={person.about} />
</div>
<div className="form-group" style={{width: '600px'}}>
<label>Email</label>
<input onChange={handleChange} className="form-control" id="email" placeholder="Enter Email" value={person.email} />
</div>
<div className="custom-file mt-3">
<input onChange={handleChange} type="file" className="custom-file-input" id="image" value={person.image} />
<label className="custom-file-label" for="customFile">Choose file</label>
</div>
<button type="submit" className="btn btn-primary mt-4">Submit</button>
</div>
</form>
</div>
</div>
)
}
export default Create
You have restricted the allowed methods to POST only in your view, then it's expected that you get 405 error when doing a GET.您已将允许的方法限制为仅在您的视图中发布,那么在执行 GET 时预计会出现 405 错误。 You can add the GET method
您可以添加 GET 方法
@api_view(['POST', 'GET'])
Keep in mind you will need to handle the case of a GET then and return something.请记住,您将需要处理 GET 的情况并返回一些东西。 You can see an example at drf docs here:https://www.django-rest-framework.org/api-guide/views/#api_view
您可以在此处查看 drf 文档的示例:https://www.django-rest-framework.org/api-guide/views/#api_view
Also, as a good practice in a REST API you should avoid naming your endpoints with actions like -create
, -update
, -delete
.此外,作为 REST API 中的一个良好做法,您应该避免使用
-create
、 -update
、 -delete
等操作命名端点。 The standard is to have a single url per resource like persons/
and then it's stated that POST will be used for create, GET will be used to retrieve (one person ro a list), PUT/PATCH will we used for updated.标准是每个资源(如 people/)有一个
persons/
,然后声明 POST 将用于创建,GET 将用于检索(一个人 ro 一个列表),PUT/PATCH 将用于更新。
And you can do all that easily using DRF routers
and viewsets
, or a ModelViewSet
more specifically for your case.您可以使用 DRF
routers
和视图ModelViewSet
轻松完成所有这些工作,或者更具体地为您的情况使用viewsets
。 See more on drf docs here:在此处查看有关 drf 文档的更多信息:
https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset
https://www.django-rest-framework.org/api-guide/routers/#routers https://www.django-rest-framework.org/api-guide/routers/#routers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.