el halcon
el halcon

Reputation: 59

foreign key error While submitting the forms

I had created a model and it contain foreign key fields also , but while I try to submit it shows error by saying like number cannot assign to the field where foreign key is assigned. I had submited models.py , forms.py , views.py below. Please go through it How can I upload as name . Error picture like below picture

models.py:


class UserReg(models.Model):
    username=models.ForeignKey(settings.AUTH_USER_MODEL,default=1,null=True,on_delete=models.CASCADE)
    Name=models.CharField(max_length=200)
    Date_of_Birth=models.DateField()
    Age=models.IntegerField()
    Gender=models.CharField(max_length=200, choices=GenderChoice)
    Phone_no=models.IntegerField()
    Mail=models.EmailField(unique=True)
    Address=models.TextField(max_length=700)
    District=models.ForeignKey(District,on_delete=models.CASCADE)
    Branch=models.ForeignKey(Branch,on_delete=models.CASCADE)
    Account_Type=models.CharField(max_length=200,choices=AccType)
    Materials=models.ManyToManyField(Materials)


class District(models.Model):
    name=models.CharField(max_length=200)

Views.py:



def reg(request):
    form = Userform(request.POST or None)
    if request.method == 'POST':

        username = request.POST.get('username')
        Name = request.POST.get('Name')
        Date_of_Birth = request.POST.get('Date_of_Birth')
        Age = request.POST.get('Age')
        Gender = request.POST.get('Gender')
        Phone_no = request.POST.get('Phone_no')
        Mail = request.POST.get('Mail')
        Address = request.POST.get('Address')
        District = request.POST.get('District')
        Branch = request.POST.get('Branch')
        Account_Type = request.POST.get('Account_Type')
        Materials = request.POST.get('Materials')
        obj = UserReg(username=username, Name=Name, Date_of_Birth=Date_of_Birth, Age=Age, Gender=Gender,
                      Phone_no=Phone_no, Mail=Mail, Address=Address, District=District, Branch=Branch, Account_Type=Account_Type, Materials=Materials)
        obj.save()
        return redirect('/')

    return render(request, 'registration.html', {'form': form})

template part:

<div class="form-row">
                        <div class="name">District</div>
                            <div class="value">
                                <div class="col-sm ">
                                <div class="rs-select2 js-select-simple select--no-search">
                                {{form.District}}
                                <div class="select-dropdown"></div>
                            </div>
                        </div>
                      </div>
                    </div>

forms.py

class Userform(forms.ModelForm):
Gender = forms.ChoiceField(choices=GenderChoice)
Account_Type = forms.ChoiceField(choices=AccType)
District = forms.ModelChoiceField(queryset=District.objects.all())
Branch = forms.ModelChoiceField(queryset=Branch.objects.all())
class Meta:
    model = UserReg
    fields = ['username','Name','Date_of_Birth','Age','Gender','Phone_no',
              'Mail','Address','District','Branch','Account_Type', 'Materials']
    widgets = {
        'username':forms.TextInput(attrs={'class':'form-control','readonly':'readonly'}),
        'Name':forms.TextInput(attrs={'class':'form-control form-control-lg input--style-5'}),
        'Date_of_Birth':DateInput(attrs={'class':'form-control-lg input--style-5'}),
        'Age':forms.NumberInput(attrs={'class':'form-control form-control-lg input--style-5'}),
        'Gender':forms.RadioSelect(attrs={'class':' form-check-input input--style-5 '}),
        'Phone_no':forms.NumberInput(attrs={'class':'form-control form-control-lg input--style-5'}),
        'Mail':forms.EmailInput(attrs={'class':'form-control form-control-lg input--style-5','type':'email'}),
        'Address':forms.Textarea(attrs={'class':'form-control input--style-5','rows':'4'}),
        'District':forms.Select(),
        'Branch':forms.Select(),
        'Account_Type':forms.RadioSelect(attrs={'class':'form-check form-check-input input--style-5'}),
        'Materials':forms.CheckboxSelectMultiple(attrs={'class':'form-check form-check-input input--style-5'}),
    }

Upvotes: 0

Views: 317

Answers (2)

Sunderam Dubey
Sunderam Dubey

Reputation: 8837

The error simply says assign actual instance of District model instead of "5".

So, first fetch district instance from District model through get_object_or_404 then assign it to UserReg model, so:

If found nothing, it will raise Http404 error.

def reg(request):
    if request.method == 'POST':
        form=UserForm(request.POST)
        if form.is_valid():
            user_reg=form.save(commit=False)
            user_reg.save()
            user_reg.save_m2m()
            return redirect("/")
    else:
        form=UserForm()          

    return render(request,'registration.html',{'form':form})

Upvotes: 0

nigel239
nigel239

Reputation: 1755

You seem to be trying to assign an integer to the foreign key field. The value returned from the form will be a foreign key (an integer, as it's the id field in this question), while the foreign key field takes the instance itself as an argument.

Try to assign this in the field:

district = District.objects.get(pk=District)

Upvotes: 1

Related Questions