前提・実現したいこと
Django2で定義したmodelカスタムユーザーのデータを汎用クラスビューListViewを使ってHTMLに表示させたいです。
■■な機能を実装中に以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
runserverすると黄色画面に
AttributeError at /
'User' object has no attribute 'file'
Error during template rendering
In template /Users/VASDAQ/PycharmProjects/20190806hozon【汎用クラスビュー】/mysite/register/templates/register/base.html, error at line 0
'User' object has no attribute 'file'
と表示されます。
<!doctype html> 2 <html lang="ja"> 3 <head> 4 <!-- Required meta tags --> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 7 8 <!-- Bootstrap CSS --> 9 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" 10 integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
該当のソースコード
python
1**models.py** 2 3class User(AbstractBaseUser, PermissionsMixin): 4 """カスタムユーザーモデル.""" 5 6 email = models.EmailField(_('email address'), unique=True) 7 first_name = models.CharField(_('名'), max_length=30, blank=True) 8 last_name = models.CharField(_('姓'), max_length=150, blank=True) 9 nick_name = models.CharField(_('ニックネーム'), max_length=30, blank=False) 10 11 is_staff = models.BooleanField( 12 _('staff status'), 13 default=False, 14 help_text=_( 15 'Designates whether the user can log into this admin site.'), 16 ) 17 is_active = models.BooleanField( 18 _('active'), 19 default=True, 20 help_text=_( 21 'Designates whether this user should be treated as active. ' 22 'Unselect this instead of deleting accounts.' 23 ), 24 ) 25 date_joined = models.DateTimeField(_('date joined'), default=timezone.now) 26 27 objects = UserManager() 28 29 EMAIL_FIELD = 'email' 30 USERNAME_FIELD = 'email' 31 REQUIRED_FIELDS = [] 32 33 class Meta: 34 verbose_name = _('user') 35 verbose_name_plural = _('users') 36 37 def get_full_name(self): 38 """Return the first_name plus the last_name, with a space in 39 between.""" 40 full_name = '%s %s' % (self.first_name, self.last_name) 41 return full_name.strip() 42 43 def get_short_name(self): 44 """Return the short name for the user.""" 45 return self.first_name 46 47 def email_user(self, subject, message, from_email=None, **kwargs): 48 """Send an email to this user.""" 49 send_mail(subject, message, from_email, [self.email], **kwargs) 50 51 def __str__(self): 52 """ファイルのURLを返す""" 53 return self.file.url 54 55 @property 56 def username(self): 57 """username属性のゲッター 58 59 他アプリケーションが、username属性にアクセスした場合に備えて定義 60 メールアドレスを返す 61 """ 62 return self.email 63 64 def save_and_rename(self, url, name=None): 65 res = requests.get(url) 66 if res.status_code != 200: 67 return "No Image" 68 path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/media/image/" 69 if name == None: 70 path += url.split("/")[-1] 71 else: 72 path += name 73 with open(path, 'wb') as file: 74 file.write(res.content) 75 return path 76 77 78 79**views.py** 80 81from django.views.generic import ListView #←読み込めない 82from register.model import User 83from django.conf import settings 84from django.contrib.auth import get_user_model 85from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin 86from django.contrib.auth.views import ( 87 LoginView, LogoutView 88) 89from django.contrib.sites.shortcuts import get_current_site 90from django.core.signing import BadSignature, SignatureExpired, loads, dumps 91from django.http import HttpResponseBadRequest 92from django.shortcuts import redirect, resolve_url 93from django.template.loader import render_to_string 94from django.views import generic 95from .forms import ( 96 LoginForm, UserCreateForm, UserUpdateForm 97) 98 99class ListVie(generic.ListView): 100 model = User 101 template_name = 'register/top.html' 102 103 104**urls.py** 105 106urlpatterns = [ 107 path('', views.ListVie.as_view(), name='top'),] 108
html
1{% extends "register/base.html" %} 2{% block content %} 3 4<div class="container-fluid"> 5 <div class="row"> 6 <div class="col-sm-8" style="background:blue;"> 7 <p>新着フリーランス一覧コンテナ</p> 8 <div class="row"> 9 <div class="col-sm-6" style="background:pink"> 10 <ul> 11 {% for item in user_list %} 12 <li>{{ item }}</li> 13 {% endfor %} 14 </ul> 15 </div> 16 </div> 17 </div> 18 </div> 19</div>
試したこと
def関数などでも試したのですが全くダメです取り出せませんでした。
python
1def product_detail(request, product_id): 2 try: 3 product = User.objects.get(id=user_id) 4 except User.DoesNotExist: 5 raise Http404 6 return TemplateResponse(request, 'register/top.html', 7 {'product': product})
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答1件
あなたの回答
tips
プレビュー