maria_hoffman
maria_hoffman

Reputation: 51

AttributeError at / type object 'Form' has no attribute 'objects', how to fix?

AttributeError at / type object 'Form' has no attribute 'objects', I'm new to django, I'd appreciate a brief explanation

views.py


from django.shortcuts import render,redirect
from django.contrib import messages
from .forms import *


def main(request):
    if request.method == "POST":
        form = Form(request.POST)
        if form.is_valid():
            Form.objects.get_or_create(
                name=form.cleaned_data['name'],
                email=form.cleaned_data['email'],
                phone=form.cleaned_data['phone']
            )
            messages.success(request, 'Form has been submitted')
            return redirect('/')
        else:
            return HttpResponse("Invalid data")
    else:
        form = Form()
    return render(request, 'app/main.html', {'form': form})

models.py


class ModelsForm(models.Model):
    name = models.CharField(max_length=30)
    email = models.CharField(max_length=30)
    phone = models.CharField(max_length=30)

    objects = models.Manager()

forms.py

from .models import ModelsForm

class Form(ModelForm):
    class Meta:
        model = ModelsForm
        fields = '__all__'```

Upvotes: 2

Views: 1940

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

You are making things confusing: your model named ModelsForm which suggests that it is a form, not a model. If you thus want to obtain the objects you can work with:

ModelsForm.objects.get_or_create(
    name=form.cleaned_data['name'],
    email=form.cleaned_data['email'],
    phone=form.cleaned_data['phone']
)

But I strongly advise to rename your models to names that do not hint these are forms, views, admins, etc.

Upvotes: 1

Related Questions