'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.

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

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




Solution 1:[1]

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

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

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

or use get_object_or_404()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1