Django form for single key

Asked

Viewed 34 times

1

Good afternoon, everyone.

I have a model in Django with a field - phone - which is a unique key:

phone = models.CharField(max_length=11, unique=True)

I’m trying to generate a form in which the user enters the site and puts the phone, but I’m getting error saying that the phone is already at the base. My goal is precisely that the phone is at the base.

form py.

class ClientForm(forms.ModelForm):

    class Meta:
        model = Client
        fields = ('phone', )

html template.

<form method="POST" class="client-form">
    {% csrf_token %}    
    {{ form.phone }}    
    <button type="submit" class="save btn">CONTINUAR</button>
</form>

py views.

def get_phone(request):
    if request.method == "POST":
        if form.is_valid():
            phone = form.cleaned_data['phone']
            client = Client.objects.filter(phone=phone).first()

The problem is he’s just form.is_valid(). What I have to do differently for him to understand that I want to make a query of a number that already exists?

1 answer

1


I’m not sure I fully understood your context, but it seems that you already have the phones recorded in the bank and you want the user to type the phone as if it were a credential for entry into some part of the system, is that it? If that’s it, you’re using the verb http wrong, actually not directly related to Django and yes to web development, try to change the method post by the method get

<form method="GET" class="client-form">
    {% csrf_token %}    
    {{ form.phone }}    
    <button type="submit" class="save btn">CONTINUAR</button>
</form>

Of course you’ll have to change the view too.

The ideal would be to do all the documentation tutorial, if you want to see directly the topic of Formularios point to https://docs.djangoproject.com/pt-br/2.1/intro/tutorial04/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.