简体   繁体   中英

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__'```

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM