2

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__'```
1
  • You're trying to access objects on Form class which does not contain objects attribute Commented Nov 30, 2021 at 18:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.