Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

python - How do you add an avatar profile to django inbuilt forms?

How can you add a field to add images on a inbuilt Django form? Here is the code of my form.py:

class CreateUserForm(UserCreationForm):

    password1 = forms.CharField(
        label="Password",
        widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Password'}),
    )
    password2 = forms.CharField(
        label="Confirm password",
        widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Confirm Password'}),
    )

    class Meta(UserCreationForm.Meta):
        model = get_user_model()
        widgets = {
            'username': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Username'}),
            'first_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'First Name'}),
            'last_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Last Name'}),
            'email': EmailInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Email Address'}),
        }

        fields = ['username', 'first_name', 'last_name', 'email']
question from:https://stackoverflow.com/questions/65836483/how-do-you-add-an-avatar-profile-to-django-inbuilt-forms

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I assume you are using the build-in django User model. Django User model doesn't have an avatar field. So what you should do is extend your default User model by creating a One-to-one relationship to another model with the avatar field

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
    avatar = models.ImageField(upload_to = "avatars/", null=True, blank=True)

then use the django post_save signal to automatically create the UserProfile modal instance when a User instance is created.

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from yourapp.models import UserProfile

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

after that you'll be able to access the avatar field with the Modal Forms...

~hope that helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...