0

im following Add image/avatar to users in django tip to have users upload their profile pictures, and to display the user's profile picture when a user log in.

Adding profile picture to django user

But for some reason, it comes with an error saying "Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserProfileForm needs updating."

Is there anyway i can directly modify the django.contrib.auth.models's User model so that i can add only the profile picture and have it displayed on index.html?

there is not a whole lot of information regarding this profile picture system.

and it's only been days since i started learning about django and python.

could anyone explain with examples, how i can achieve this?

Thanks.

(this is the forms.py that's implementing the tip above)

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, get_user_model, login, logout

class UserSignupForm(forms.ModelForm):
    email = forms.EmailField(label='Confirm Email')
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'password'
        ]
    def clean_email(self):
        email = self.cleaned_data.get('email')
        email_qs = User.objects.filter(email=email)
        if email_qs.exists():
            raise forms.ValidationError("This email has already been registered")
        return email



from django.core.files.images import get_image_dimensions
from .models import UserProfile


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile

    def clean_avatar(self):
        avatar = self.cleaned_data['avatar']

        try:
            w, h = get_image_dimensions(avatar)

            #validate dimensions
            max_width = max_height = 100
            if w > max_width or h > max_height:
                raise forms.ValidationError(
                    u'Please use an image that is '
                     '%s x %s pixels or smaller.' % (max_width, max_height))

            #validate content type
            main, sub = avatar.content_type.split('/')
            if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
                raise forms.ValidationError(u'Please use a JPEG, '
                    'GIF or PNG image.')

            #validate file size
            if len(avatar) > (20 * 1024):
                raise forms.ValidationError(
                    u'Avatar file size may not exceed 20k.')

        except AttributeError:
            """
            Handles case when we are updating the user profile
            and do not supply a new avatar
            """
            pass

        return avatar
Community
  • 1
  • 1
Mark Kang
  • 131
  • 1
  • 1
  • 14
  • Please post your forms.py file – Prateek Jul 22 '16 at 09:58
  • I think the problem is with the import of your "UserProfile" model, Please import your models correctly. – Prateek Jul 22 '16 at 10:07
  • @Prateek what do you mean? this is the userprofile from models.py which is correct. – Mark Kang Jul 22 '16 at 10:09
  • class UserProfile(models.Model): user = models.OneToOneField(User) avatar = models.ImageField() – Mark Kang Jul 22 '16 at 10:10
  • 1
    You are using "from .models import UserProfile" where .models is not getting resolved and your model is not getting imported, I mean to say that. – Prateek Jul 22 '16 at 10:11
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118003/discussion-between-prateek-and-mark-kang). – Prateek Jul 22 '16 at 10:12
  • You need to create model image field, add image field to Meta fields, then add to template, when user upload his image you get this from model with queryset. –  Jul 22 '16 at 10:33
  • @VolodymyrKirichinets could you elaborate more on that using an example of it? sorry, i cannot follow what you are saying as im relatively new to this environment. – Mark Kang Jul 22 '16 at 10:35
  • @Prateek that is not only incorrect but completely irrelevant. – Daniel Roseman Jul 22 '16 at 10:35
  • @DanielRoseman: Okay, I feel the error is asking to add fields = ['avatar'] below the model = 'UserProfile' – Prateek Jul 22 '16 at 10:38
  • Roseman what You mind? –  Jul 22 '16 at 10:42

1 Answers1

4

Example: models.py:

class YouModel(models.Model):
    .............You field ................
    user_avatar = models.ImageField((upload_to="You/media/uploads", blank=True) # You need to configure media in settings.py
    ........... You fields ..............

class YouModelForm(ModelForm)
    class Meta:
        model = YouModel
        fields = ['user_avatar']

views.py:

from .models import YouModel, YouModelForm

def youfunc(request):
    youtemplate = YouModelForm()
    if request.method == POST:
        youform = YouModelForm(request.POST, request.FILES)
        if youform.is_valid():
           youform.save()
           return HttpResponseRedirect('http://www.You.url') # or other
    youquery = .objects.order_by('user_avatar').last()
    return render(request, "YouProject/YouHtml.html", {'youtemplate': youtemplate, 'youquery': youquery})

I tired to write. You need configure django and write first file upload from user. You can visit to my website and look and decide - this is what You want? my website http://www.webmamoffice.org/en and go to UperVote or http://www.webmamoffice.org/en/upervote

haccks
  • 104,019
  • 25
  • 176
  • 264