2016-02-13 4 views
1

, поэтому я довольно новичок в Django, и для меня жизнь не может понять, что здесь происходит. У меня была форма, работающая и появившаяся на веб-странице, и мне удалось создать базу данных, которая будет создана и отображаться в SQL. Однако, когда я пытался получить формы для сохранения информации в базе данных, поля, которые я начал тестировать, исчезли, и ничего не записано в базу данных.AttributeError: type object 'Team' не имеет атрибута '_meta'

я постоянно получаю эту ошибку: AttributeError: type object 'Team' has no attribute '_meta'

отслеживающий:

Unhandled exception in thread started by <function wrapper at 0x108cbd050> 
Traceback (most recent call last): 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper 
    fn(*args, **kwargs) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run 
    self.check(display_num_errors=True) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check 
    include_deployment_checks=include_deployment_checks, 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks 
    new_errors = check(app_configs=app_configs) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config 
    return check_resolver(resolver) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver 
    for pattern in resolver.url_patterns: 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ 
    res = instance.__dict__[self.name] = self.func(instance) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns 
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ 
    res = instance.__dict__[self.name] = self.func(instance) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module 
    return import_module(self.urlconf_name) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module 
    __import__(name) 
    File "/Users/alicen/git/first_robotics/frcstats/urls.py", line 18, in <module> 
    from .views import get_name # , post_new 
    File "/Users/alicen/git/first_robotics/frcstats/views.py", line 4, in <module> 
    from .forms import * 
    File "/Users/alicen/git/first_robotics/frcstats/forms.py", line 14, in <module> 
    class TeamForm(ModelForm): 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/forms/models.py", line 247, in __new__ 
    opts.field_classes) 
    File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/forms/models.py", line 144, in fields_for_model 
    opts = model._meta 
AttributeError: type object 'Team' has no attribute '_meta' 

models.py

from django.db import models 


class Team(models.Model): 
    team_number = models.IntegerField() 
    team_name = models.CharField(max_length=30) 
    robot_weight = models.FloatField() 
    robot_height = models.IntegerField() 
    team_location = models.CharField(max_length=30) 
    team_notes = models.CharField(max_length=150) 

    posted_on = models.DateTimeField('Posted On') 

    def __unicode__(self): 
      return self.team_number 

    class Meta: 
     db_table = 'teams' 
     app_label = 'frcstats' 

views.py

from django.http import HttpResponseRedirect 
from django.shortcuts import render 

from .forms import * 


def get_name(request): 
    # if this is a POST request we need to process the form data 
    if request.method == 'POST': 
     # create a form instance and populate it with data from the request: 
     team = Team(request.POST) 
     match = Match(request.POST) 
     auto = Autonomous(request.POST) 
     teleop = Teleoperated(request.POST) 
     # check whether it's valid: 
     if form.is_valid() and auto.is_valid() and match.is_valid() and teleop.is_valid(): 
      form.save() 
      return HttpResponseRedirect(reverse('frcstats:url')) 
     else: 
      return HttpResponseRedirect('/Form not valid/') 

    # if a GET (or any other method) we'll create a blank form 
    else: 
     team = Team() 
     auto = Autonomous() 
     match = Match() 
     teleop = Teleoperated() 

    return render(request, 'name.html', {'team': team, 'auto': auto, 
    'match': match, 'teleop': teleop, }) 

forms.py

from django import forms 
from .models import Team 
from django.forms import ModelForm 


class Team(forms.Form): 
    team_number = forms.IntegerField(label='Team Number ') 
    team_name = forms.CharField(label='Team Name ', max_length=30) 


class TeamForm(ModelForm): 
    class Meta: 
     model = Team 
     fields = ['team_number', 'team_name'] 


class Match(forms.Form): 
    match_playing = forms.IntegerField(label='Match Number ') 

name.html

<form action="/your-name/add/" method="post"> 
    {% csrf_token %} 
    <h1>Match Scouting Form</h1> 
    {{ team.as_p }} 
    {{ match.as_p }} 
    <h3>Autonomous</h3> 
    {{ auto.as_p}} 
    <h3>Teleoperated</h3> 
    {{ teleop.as_p}} 
    <input type="submit" value="Submit" /> 
</form> 

ответ

0

Проблема заключается в вашей forms.py. Смотрите у вас есть эта модель импорт:

from .models import Team 

И затем вы определяете Team форму затенения импортируемая модель:

class Team(forms.Form): 

Затем, когда вы используете model = Team внутри TeamForm было бы реально использовать Team образ формы, а не импортированную модель.


Один из способов исправить это псевдоним вашего оператора импорта:

from .models import Team as TeamModel 

, а затем использовать его, чтобы установить model на форме модели:

class TeamForm(ModelForm): 
    class Meta: 
     model = TeamModel 
     fields = ['team_number', 'team_name'] 
+0

Спасибо! Это сработало, чтобы решить мою ошибку атрибута, теперь я только выяснил, как заставить его писать в мою базу данных – alicen