简单的Django表单

时间:2017-10-03 13:39:36

标签: python django

我试图实现类似Twitter的关注系统(一个用户可以关注并被许多其他用户关注)。我尝试了很多方法,但我一直都会遇到错误。目前,每当我在整个表单中删除调试器或打印语句时,我发现我没有进入干净的方法,kwargs也没有填充值。

我希望能够传递follower& following作为Form的参数,只需在__init__中分配它们,但一切都会出错。当我在Javascript(React& Redux)中得到回复时,我得到的所有内容都是follower和& following说"此字段是必填字段。"

这是我到目前为止所得到的:

模型

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=100, unique=True)
    email = models.EmailField(unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    date_joined = models.DateTimeField(auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

class UserFollow(models.Model):
    follower = models.ForeignKey('User', models.CASCADE, related_name='follows')
    following = models.ForeignKey('User', models.CASCADE, related_name='followed_by')

    class Meta:
        unique_together = ('follower', 'following')

    def to_user(self):
        return {
            'id': self.pk,
            'follower': self.follower.pk,
            'following': self.following.pk
        }

视图

def follow(request, id):
    following = User.objects.get(pk=id)
    form = UserFollowForm(follower=request.user, following=following)
    if form.is_valid():
        user_follow = form.save()
        return JsonResponse({'user_followed': following.to_user()})
    return JsonResponse({'error': form.errors}, status=400)

表单

class UserFollowForm(forms.ModelForm):
    follower = forms.CharField()
    following = forms.CharField()

    class Meta:
        model = UserFollow
        fields = ('follower', 'following')

    def __init__(self, *args, **kwargs):
        self.follower = kwargs.pop('follower', None)
        self.following = kwargs.pop('following', None)
        super(UserFollowForm, self).__init__(*args, **kwargs)

    def clean_follower(self):
        return self.follower

    def clean_following(self):
        return self.following

1 个答案:

答案 0 :(得分:3)

您尚未将任何数据传递到表单中,因此它不受约束,也永远不会被验证。

但是我不明白你为什么要在这里使用表格。您似乎不想从用户那里获取发布的数据,也无法进行验证。只需直接创建UserFollow实例。

def follow(request, id):
    following = User.objects.get(pk=id)
    user_follow = UserFollow.objects.create(follower=request.user, following=following)
    return JsonResponse({'user_followed': user_follow.to_user()})