简体   繁体   English

如何将序列化器字段从 RESTful API - DRF (Django) 传递到前端框架?

[英]How to pass Serizalizer Fields to front-end Framework from RESTful API - DRF (Django)?

I want to use Svelte in the front-end and DRF (Django) in the back-end.我想在前端使用 Svelte,在后端使用 DRF (Django)。

This is what I have right now:这就是我现在所拥有的:

#models.py
class Student(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
# serializers.py
class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"

But when I know want to create a form in the front-end (Svelte) I have to manually do that?但是当我知道要在前端(Svelte)创建一个表单时,我必须手动这样做吗? Is there a way of requesting a json with all the required fields and the to build a form around it.有没有一种方法可以请求包含所有必填字段的 json 并围绕它构建一个表单。

Like first I request api.com/students/form which returns a json:就像我首先请求api.com/students/form一样,它返回一个 json:

{
  "fields":[
    "first_name",
    "last_name"
  ]
}

And then I could just iterate over the fields in "fields" and create <input> tags for the form accordingly.然后我可以遍历"fields"中的字段并相应地为表单创建<input>标签。

For your endpoint api.com/students/form you can create a view like this:对于您的端点api.com/students/form ,您可以创建如下视图:

from django.http import JsonResponse

@api_view(['GET'])
def get_form(request):
    fields = ["first_name","last_name"]
    return JsonResponse({"fields": fields})

You have to include all the fields you want on your fields array, or if you want all the fields of the model you can get them like this model._meta.fields or model._meta.get_fields()您必须在fields数组中包含所需的所有字段,或者如果您想要 model 的所有字段,您可以像这样获得它们model._meta.fieldsmodel._meta.get_fields()

You can do this by accessing metadata of the url, simply send OPTIONS request to the endpoint as suggested in documentation您可以通过访问 url 的元数据来执行此操作,只需按照文档中的建议将OPTIONS请求发送到端点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM