'Django Assigning or saving value to Foreign Key field

can any one help me with assigning value to a foreign key field. Im trying to create user profile where user can add there countries. when creating the models, from django admin page there is no problem adding countries im only having an error in the front end side when adding country select option and I got an error value

ValueError: Cannot assign "{'countries': 1}": "RegsModel.nationality" must be a "Country" instance.

please see my omitted code.

models.py

class RegsModel(models.Model):
    name = models.CharField(blank=True, max_length=64)
    nationality = models.ForeignKey(Country,  on_delete=models.CASCADE)
    def __str__(self):
        return self.Employee_ID

class Country(models.Models):
    countries = models.CharField(blank=True, max_length=64)
    def __str__(self):
        return self.countries 

forms.py

class RegsForm(forms.ModelForm):
    class Meta:
        model = RegsModel
        fields = '__all__'

views.py

def register(request):
    if request.method == "POST":
        form = RegsForm(request.POST)
        if RegsFrom.is_valid()
            form.save(commit=False)
            form.nationality = request.POST['nationality']
    
    else:
        form = RegsForm(request.POST)

    return request('register', views.register, name='register',{'form':form})

register.html

<form method='POST'>
   {{form.as_p}}
   <button type='submit'>add</button>
</form>


Solution 1:[1]

Pass Country instance in nationality field instead of simple value.

views.py:


    def register(request):
        if request.method == "POST":
            form = RegsForm(request.POST)
            if form.is_valid()
                obj = form.save(commit=False)
                country_inst = Country.objects.get(countries = request.POST['nationality'])  # Pass country(e.g. 'India') value instead of dict..
                obj.nationality = country_inst
                obj.save()
        
        else:
            form = RegsForm(request.POST)
    
        return request('register', views.register, name='register',{'form':form})

Solution 2:[2]

why do you do form.nationality = request.POST['nationality'] you can just do form.save() and it will create the object for you because you already add the field to the form by the fields = '__all__' in your form

class RegsForm(forms.ModelForm):
    class Meta:
        model = RegsModel
        fields = '__all__'

Solution 3:[3]

To save value in forignkey just give the current object to the forignkey and rest forignkey will pickup its value.

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 Pradip
Solution 2 seif
Solution 3 Mukesh Nayal