“ avatar”属性没有与之关联的文件

时间:2018-08-12 20:46:15

标签: django django-models django-forms django-templates django-views

我无法上传图片,如果删除图片,则会出现此错误!!!

<img src="{{user.teacher.avatar.url}}" class="user-image" alt="User Image">

models.py

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone_regex = RegexValidator(regex=r'^\0?1?\d{11}$')
    mobile = models.CharField(validators=[phone_regex], max_length=11, blank=True)
    avatar = models.ImageField(upload_to='avater', blank=True)

    def __str__(self):
        return self.user.first_name + ' '+self.user.last_name

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Teacher.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.teacher.save()

forms.py

class UserForm(forms.ModelForm):
class Meta:
    model = User
    fields = ( 'username', 'first_name', 'last_name', 'email')

views.py

@login_required
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = TeacherForm(request.POST,request.FILES, instance=request.user.teacher)
        if user_form.is_valid() and profile_form.is_valid():

            user_form.save()
            profile_form.save()
            # if Teacher.avatar is not None:
            #     print (".............img................", Teacher.avatar)
            messages.success(request,('Your profile was successfully updated!'), extra_tags='alert')
            return redirect('Dashboard:profile')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = TeacherForm(instance=request.user.teacher)
    return render(request, 'Dashboard/updateProfile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

这是当前情况,我也无法在与“教师”没有关联的管理面板中以“管理员”身份登录

0 个答案:

没有答案