Dileep Kommineni
Dileep Kommineni

Reputation: 84

Check the form input value to existing value in Django

In in my database there are some emails those should be checked with the form value which is entered in email field

models.py

class Friend(models.Model):
    email = models.EmailField(max_length=100)

forms.py

class FriendForm(forms.ModelForm):

    class Meta:
        model = Friend
        fields = ['email']

views.py

def check(request):
     if request.method == "POST":
        form = FriendForm(request.POST)
        if form.is_valid():
            queryset = Friend.objects.all
            return render(request,"two.html",{"queryset":queryset})
     else:
        form = FriendForm()
    return render(request, 'emaill.html', {'form': form})

emaill.html

<body>
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" name="Submit">
    </form>
 </body>

two.html

<body>
 <h1>found</h1>
 {% for obj in queryset %}
 {{obj.email}} </br>
 {% endfor %}
</body>

when user submited any email that should be checked with models email that means with existing one if matches in should render to two.html it should show connect if mail does not match with mail that is in database it should show no such mail

Upvotes: 1

Views: 2623

Answers (1)

unlockme
unlockme

Reputation: 4235

Okay, I understand what you are trying to do. You are doing an email search.

def check(request):
    if request.method == "POST":
        form = FriendForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data("email")
            try:
                 friend = Friend.objects.get(email=email)
                 return render(request,"email1.html",
                       {"friend":friend})
            except Friend.DoesNotExist:
                return render(request, "email1.html", {"form":form})

If you are interested in connecting them, then you should use the get method of the ModelManager (objects). That will return a single object if it exists. In your template. As you can see I have saved some typing on an extra template by using conditions in the template.

{% if form %}
  #display your form
{% else %}
  #display the friend as you want
{% endif %}

I recommend you go slow and do more reading of the documentation. I am here. Note that I changed your queryset to friend. queryset is misleading as it points that you want multiple objects. So in your template you cant iterate, instead you display friend without iterating.

{{ friend }}

Upvotes: 3

Related Questions