/profile/ 处的 ValueError:“图像”属性没有与之关联的文件

Nil*_*Kar 3 django django-models django-forms django-filter django-template-filters

当用户注册我的应用程序时,当他到达个人资料页面时收到此错误

 'ValueError at /profile/:The 'image' attribute has no file associated with 
  it.'
Run Code Online (Sandbox Code Playgroud)

这是我的个人资料模型:

class Profile(models.Model):
Full_Name = models.CharField(max_length=32,blank=True)
Name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
E_mail = models.EmailField(max_length=70,blank=True)
Qualification = models.CharField(max_length=32,blank=True)
Permanant_Address = models.TextField(blank=True)
image = models.ImageField(upload_to='user_images', null=True, blank=True)

def __str__(self):
    return str(self.Name)


def get_absolute_url(self):
    return reverse("userprofile:profiledetail")

@property
def image_url(self):
    if self.image and hasattr(self.image, 'url'):
        return self.image_url
Run Code Online (Sandbox Code Playgroud)

这是我的表格:

class profileform(forms.ModelForm)"


class Meta:
    model = Profile
    fields = ('Full_Name','Name', 'E_mail','Qualification','Permanant_Address','image')
Run Code Online (Sandbox Code Playgroud)

这是我的观点:

from django.shortcuts import render
from django.views.generic import DetailView,UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from userprofile.models import Profile
from userprofile.forms import profileform

# Create your views here.

class profiledetailview(LoginRequiredMixin,DetailView):
    context_object_name = 'profile_details'
    model = Profile
    template_name = 'userprofile/profile.html'

    def get_object(self):
       return self.request.user.profile

  class profileupdateview(LoginRequiredMixin,UpdateView):
     model = Profile
     form_class = profileform
     template_name = 'userprofile/profile_form.html'

     def get_object(self):
         return self.request.user.profile
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我做了这样的事情:

<img class="profile-user-img img-responsive img-circle" src="{{ 
  profile_details.image.url|default_if_none:'#' }}/" alt="User profile 
  picture">
Run Code Online (Sandbox Code Playgroud)

我一直在阅读内置模板标签和过滤器的文档,我认为这里的解决方案是使用,我认为我似乎无法正确使用模板标签。

如何配置此模板以使图片成为选项。如果他们没有图片,请留下它但显示人名。

谢谢

Nav*_*pak 5

您正在尝试获取不存在的图像的 url。

基本上,如果您要检查图像是否存在,那么您必须这样做:

if profile_details.image:
    url = profile_details.image.url
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下:

src={% if profile_details.image %}{{ profile_details.image.url }}{% else %}#{% endif %}
Run Code Online (Sandbox Code Playgroud)