【问题标题】:Django Rest Framework create object additional dataDjango Rest Framework 创建对象附加数据
【发布时间】:2018-12-05 07:31:26
【问题描述】:

使用 Django 2.0,我有两个模型 postgroup,在 post 中有一个 ForeignKey 指向。我在“/group/name_of_group”有一个的详细视图,我可以在其中创建一个帖子的实例。 所以基本上,当我们创建 post 时,它的字段 group 应该被自动设置为页面的 group(假设是 group X,所以我们'在'/group/X'),我们将数据发送到: POST to /api/post/create 怎么做? 这是我的代码: 我的模型:

class Post(models.Model):
    user        = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)#the owner when we delete him, all his posts are deleted
    group       = models.ForeignKey(Group, default=1, on_delete=models.CASCADE)

class Group(models.Model):
    name        = models.CharField(max_length=50, default='', unique=True)

我的表格:

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

用于创建帖子的我的 API 视图:

class PostCreateAPIView(generics.CreateAPIView): #/api/group/create
    serializer_class    = PostModelSerializer           
    permission_classes  = [permissions.IsAuthenticated]

我提交表单时的 ajax 调用

event.preventDefault();
$.ajax({
       method   : "POST",
       url      : '/api/post/create',
       data     : formData,//data contains our new post
       success  : function(data){
         this_.find("input[type=text], textarea").val("");//a display function for html
         attachPost(data, prepend = true);//a display function for html

       },
       error    : function(data){
         console.log("ERROR:CH0x2 while fetching after creation form submit");
         console.log("data :",data.status, data.statusText);
       }
     });

NB 一个例子是设置帖子的所有者我们重写方法 perform_create (in PostCreateAPIView) 将用户设置为request.user 喜欢这个

def perform_create(self, serializer):               # create the post
    serializer.save(user = self.request.user)

但我无法在该方法中获得 名称或 pk

//////编辑/////////

我可以将我的创建网址更改为: /api/post/create/api/post/name_group/create

谢谢

【问题讨论】:

  • 我真的不明白您要做什么,您是否希望将您的新帖子组设置为“创建”(因为您在 /group/create 上做了您的请求)?否则,您的“数据包含我们的新帖子”到底是什么?如果您不以一种或另一种方式告诉他,django 应该如何猜测要在 Post 中添加哪个组?
  • 我想创建一个新帖子并从请求中自动设置组(它包含 kwargs 中的组)但是我在哪里可以访问此请求以获取组名称并将其设置在 formData 谢谢你!
  • PostModelForm fields 属性包括group,因此表单将具有选择组的小部件。如果我理解您应该从字段中省略该组,对吗?

标签: django django-rest-framework


【解决方案1】:

我使用 JQuery 来做到这一点, 准备好文档后,我选择了该项目并设置了我设法通过 serializer 传递的值,最后我像这样隐藏了该项目:(该项目是一个 HTML 项目)

HTMl:(后容器是我要附加帖子的地方

<p id="post-container" group-id     = "{{object.pk}}">

    </p>

序列化器类:

class GroupModelSerializer(serializers.ModelSerializer):
class Meta:
    model  = Group   # the model to get fields from
    fields = [      
    'id',//this is the id I get and set on the choice field (<select>)
    'moderators',
    'name',
    'description',
    'timestamp'

    ]

JS:

$(document).on("ready",function(){ 
var selectGroup   = $('#create-post').find('select');//create-post is the id of the form html item where I put the django generated form
var postContainer = $('#post-container');
var labelGroup   = $('#create-post').find('label');
var groupId       = postContainer.attr("group-id");
selectGroup.val(groupId); selectGroup.prop('disabled',true); selectGroup.hide();labelGroup.hide()
initAjaxVariables('post-container', fetchDataUrl, postDataUrl); // init variables
initPostListDisplay(); //Fetch posts and display them
});

谢谢大家!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2017-12-29
    • 1970-01-01
    • 2021-12-04
    • 2021-08-01
    相关资源
    最近更新 更多