如何通过表单在 Django 模型中用当前用户填充用户字段?

how to populate user field with current user in django models via forms?

您好,我正在开发 Django 应用程序。我正在实现的功能是让我的用户从网站上购买互联网包。

到目前为止,我已经实现了模型、视图、模板和 url。但在表格中,我得到了在该应用程序上注册的所有用户的下拉列表。我自动希望 django link 具有当前登录用户的用户并让他 select 他想购买的包并自动填充模型(table)。

我的models.py


def get_deadline():
    return dt.today() + timedelta(days=30)

class CustomUser(AbstractUser):
    Address = models.CharField(max_length=500)

    def __str__(self):
        return self.username

class Plans(models.Model):
    plan_name = models.CharField(max_length=50)
    speed = models.IntegerField()
    price = models.FloatField()

    def __str__(self):
        return self.plan_name


class Orders(models.Model):
    user = models.ForeignKey(CustomUser, on_delete = models.CASCADE)
    pack = models.ForeignKey(Plans, on_delete = models.CASCADE)
    start_date = models.DateField(auto_now_add=True)
    end_date = models.DateField(default=get_deadline())
    is_active = models.BooleanField(default=True)

    def __str__(self):
        name = str(self.user.username)
        return name

我的views.py



class UserBuyPlan(LoginRequiredMixin, View):
    template = 'plans/plan.html'
    #success_url = reverse_lazy('autos:all')
    success_url = reverse_lazy('home-home')

    def get(self, request):
        form = BuyPlanForm()
        ctx = {'form': form}
        return render(request, self.template, ctx)

    def post(self, request):
        form = BuyPlanForm(request.CustomUser,request.POST)
        if not form.is_valid():
            ctx = {'form': form}
            return render(request, self.template, ctx)

        make = form.save()
        return redirect(self.success_url)

我的forms.py(我尝试在线搜索并找到了这个init实施但不起作用)


class BuyPlanForm(forms.ModelForm):

    class Meta():
        model = Orders
        fields = "__all__"

    def __init__(self, *args, **kwargs):

        self.user = CustomUser
        super(BuyPlanForm, self).__init__(*args, *kwargs)
        self.fields['user'].initial = self.user

结果表格的照片附在下面

好的,所以我找到了答案。 只需要稍微改变一下我的视图功能。 如果您需要详细教程,请访问 https://www.youtube.com/watch?v=-s7e_Fy6NRU&t=1840s 他以更好的方式解释。


class UserBuyPlan(LoginRequiredMixin, CreateView):
    model = Orders
    template_name = 'plans/plan.html'
    fields = ['pack']

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

并且还必须向我的订单模型添加绝对 url 方法


class Orders(models.Model):
    user = models.ForeignKey(CustomUser, on_delete = models.CASCADE)
    pack = models.ForeignKey(Plans, on_delete = models.CASCADE)
    start_date = models.DateField(auto_now_add=True)
    end_date = models.DateField(default=get_deadline())
    is_active = models.BooleanField(default=True)

    def __str__(self):
        name = str(self.user.username)
        return name

    def get_absolute_url(self):
        return reverse('home-home')

其余一切都一样。