Get value from django form and use to find data in sql

Daniela :

I want the user to insert name in the form and after submitting the program goes to the DB and find certain values for this specific name and return to the user. This view.py does not work. How can i make it work and be able obj to identify id based on inserted name and go and find the specific values?

  view.py


def home(request):

        if request.method == 'POST':
              form=PersonForm(request.POST)
              if form.is_valid():
                  form1=form.save(commit=True)
                  name=form1.name


                obj=School.objects.get(id=1)


                context={
                            'name':name,
                            'object':obj
                            }
                return render(request, 'first/results.html', context)

         else:
             form = PersonForm()
            return render(request, 'first/search.html', {'object':obj})

models.py

class School(models.Model):
    student=models.CharField(max_length=200)
    schgroup=models.CharField(max_length=200)

    class Meta:
        managed=False
        db_table='school'


class Person(models.Model):
    name= models.CharField(max_length=150)

forms.py

class PersonForm(forms.ModelForm):
    name = forms.CharField(max_length=150, label='',widget= forms.TextInput)
    class Meta:
        model = Person
        fields = ('name',)

Could you please help me. I will be happy for any help and advise.

Gunel :

You can try this :

def home(request):

        if request.method == 'POST':
              form=PersonForm(request.POST)
              if form.is_valid():
                  form1=form.save(commit=True)
                  name=form1.name


                obj=School.objects.get(student=name)


                context={
                            'object':obj
                            }
                return render(request, 'first/results.html', context)

         else:
             form = PersonForm()
            return render(request, 'first/search.html', {'object':obj})

and in template:

{{object.name}}

{{object.schgroup}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19478&siteId=1