简体   繁体   English

django rest 框架甚至显示上传图像的选项。 我在模型中有 imageField

[英]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">
                            &#10094; 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.

相关问题 上传图片-Django Rest Framework - Upload image - Django rest framework javascript if else 语句不起作用。 即使我单击 twoStory 图像,它也会返回 singleStory。 我试过了!=和--- - javascript if else statement not working. It returns singleStory even if I click on the twoStory image. I have tried != and --- "<i>CkEditor Is not uploading images and files.<\/i> CkEditor 没有上传图片和文件。<\/b> <i>Even i have no Option to upload image or files<\/i>即使我没有上传图片或文件的选项<\/b>" - CkEditor Is not uploading images and files. Even i have no Option to upload image or files 如何在Django中上传到ima​​gefield - How to upload to imagefield in Django 我有一个脚本来调整图像大小。 无论如何让它输出5张图像? - I have a script to resize an image. Is there anyway to have it output 5 images? django休息框架上传文件 - django rest framework upload file 如何将来自html5画布的base64图像保存为Django中的ImageField? - How do I save base64 image from html5 canvas as ImageField in Django? Django rest 框架:如何发送和下载 xlsx 文件? - Django rest framework: How do I send and download xlsx file? Onclick显示/隐藏图像。 没有Java语言? - Onclick show/hide image. No Javascript? 如何为以下 models.py 和 serializers.py 创建 REST 视图集? 我是 django rest 框架的新手 - How to create REST viewset for following models.py and serializers.py? i am new with django rest framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM