简体   繁体   English

如何将外键初始化为Django中的一个表单?

[英]How to initialize foreign key into a form in Django?

I have these two models, one Voucher model is a foreign key to the RegistrationForm model. Anytime someone does a search and the item exists in the Voucher model, I want it to be initialized to the Registration form and saved.我有这两个模型,一个 Voucher model 是 RegistrationForm model 的外键。任何时候有人进行搜索并且该项目存在于 Voucher model 中,我希望将其初始化为注册表并保存。

Error Message错误信息

 raise ValueError(
ValueError: Cannot assign "'phr201'": "RegistrationForm.voucher" must be a "Voucher" instance.

Models楷模

class Voucher(models.Model):
    name = models.CharField(max_length=120, null=True, blank=True)

 
class RegistrationForm(models.Model):
    voucher = models.OneToOneField(Voucher, on_delete=models.CASCADE)
    full_Name = models.CharField(max_length=200,)
    Date_of_birth = models.CharField(max_length=100)

View.py查看.py

class RegistrationProcessing(generic.CreateView):
    form_class = Registerform
    template_name = 'RegistrationProcessing.html'

    def form_valid(self, form):
        form.instance.voucher = self.request.GET.get('q')
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(RegistrationProcessing, self).get_context_data(**kwargs)
        query = self.request.GET.get('q', default='')
        print(query.id)
        context.update({
            'job_listing': Voucher.objects.filter(
                Q(name__iexact=query)
            )
        })
        return context


As error says Cannot assign "'phr201'": "RegistrationForm.voucher" must be a "Voucher" instance You're trying to assign a string to a OneToOne relation you've to pass a instance of Voucher instead of passing string you've to do like this正如错误所说Cannot assign "'phr201'": "RegistrationForm.voucher" must be a "Voucher" instance你试图将一个字符串分配给OneToOne关系你必须传递一个Voucher实例而不是传递字符串你'必须这样做

def form_valid(self, form):
    voucher_instance = Voucher.objects.get(name=self.request.GET.get('q'))
    form.instance.voucher = voucher_instance
    return super().form_valid(form)

here I'm using get so it will raise an exception if given query does not exists you've to handle it in try except block or you can use other way like this在这里我使用 get 所以如果给定的查询不存在它会引发异常你必须在 try except 块中处理它或者你可以使用其他方式这样

Voucher.objects.filter(name=self.request.GET.get('q')).first()

or use get_object_or_404()或使用get_object_or_404()

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

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