mercredi 30 décembre 2020

Displaying user uploaded image in Python Django

I am creating a website using the Django python framework and am currently stuck on a problem. I am using function views to display a page called myaccount, and on 'myaccount' i would like all user details to be displayed using context objects, for this page it is 'user'. I also have another model called Profile, which holds the profile picture and date of birth of the user. However when i attempt to display the image which has been uploaded during the account creation into the media folder named '/media/%y/%m/%d/imagename.filextension' i receive an error saying "The 'profilepicture' attribute has no file associated with it." I have been searching vastly for fixes to this issue and have so far found no result which has worked, i have tried to create a property function which gets the url from the image called 'get_absolute_url' by doing user.profile.profilepicture.get_absolute_url but it fails to work and displays the same error. I was wondering if anyone could point me in the direction of a fix for this or a solution.

The code to display the image, views.py and urls.py is down below

views.py

@login_required
def myaccount(request):
    return render(request, 'account/myaccount.html', {'section': 'myaccount'})

urls.py

path('', views.myaccount, name='myaccount'),

myaccount.html

<img src="" width="260" height="234"/>

Profile model

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date_of_birth = models.DateField(blank =True, null =True)
    profilepicture = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
    def __str__(self):
        return f'Profile for user {self.user.username}'

The model for User is from 'django.contrib.auth.models'

To confirm whether it was a problem with the context object I tried to display the users first name which worked as expected.

The account register view

def register(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        if user_form.is_valid():
            # Create a new user object but avoid saving it yet
            new_user = user_form.save(commit=False)
            # Set the chosen password
            new_user.set_password(
                user_form.cleaned_data['password'])
            # Save the User object
            new_user.save()
            Profile.objects.create(user=new_user)
            # Create the user profile
            return render(request,
                          'account/register_done.html',
                          {'new_user': new_user})
    else:
        user_form = UserRegistrationForm()
    return render(request,
                  'account/register.html',
                  {'user_form': user_form})

If any other code or information is needed please ask.




Aucun commentaire:

Enregistrer un commentaire