我想在模板上显示图像

2024-04-26 00:10:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Form.py中创建了一个ImageFields

class ProPic(forms.Form):
     image = forms.ImageField(help_text="Upload Profile Picture: ", required=False)

我的观点是

def Profile(request): 
    context = {} 
    context['image'] = ProPic() 
    return render( request, "profile.html", context) 

我的模板profile.html

{% extends 'base.html' %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
    {% load crispy_forms_tags %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile</title>
</head>
<style>
    .align-middle {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .card {
        width: auto;
    }
</style>
<body>
    <div class="card align-middle">
         <!-- I want to Display the picture here  -->
        <div class="card-body">
        </div>
        <ul class="list-group list-group-flush">
          <li class="list-group-item">Username: {{ user.username|title }}</li>
          <li class="list-group-item">Emai: {{ user.email }}</li>
          <li class="list-group-item">Vestibulum at eros</li>
        </ul>
        <div class="card-body">
          <a href="{% url 'logout' %}" class="card-link">Logout</a><br>
          {{ image }}
        </div>
      </div>
</body>
</html>
{% endblock content %}

我上传的时候看不到我的图片,如果可能的话,我不想使用模型 我希望我的图像出现在我在下面代码中添加注释的地方


1条回答
网友
1楼 · 发布于 2024-04-26 00:10:56

型号.py

class ProfilePicture(models.Model):  # your model
    image = models.ImageField(upload_to='images')
    
    profile = models.ForeignKey(User, on_delete=models.CASCADE) # here user is your default auth user model

forms.py

class ProfilePictureForm(forms.ModelForm):
    
    class Meta:
        model = ProfilePicture
        fields = ('image', ) # here is important to place a comma after image since fields argument expects an iterable

url.py

urlpatterns = [
    path('profile/<int:pk>', views.profile, name='profile'), # pass pk as argument to your url in here **<int:pk>**
    path('all-users', views.all_users, name='all_users'),
    path('upload-avatar', views.upload_avatar, name='upload_avatar'),
]

视图.py

def all_users(request): 
    users = User.objects.all()
    return render(request, 'all_users.html', {'users': users})


def upload_avatar(request):
    if request.method == 'POST':
        form = ProfilePictureForm(request.POST, request.FILES)
        if form.is_valid():
            new_profile_picture = form.save(commit=False) # commit=False because we need to assign the user to the picture before saving
            new_profile_picture.user = request.user
            new_profile_picutre.save()
            return redirect('profile', pk=request.user.pk)
        else:
            return HttpResponse('Form invalid, please select a valid picture')
    else:
        form = ProfilePictureForm()
    return render(request, 'upload_profile_picture.html', {'form': form})


def profile(request, pk): # accept **pk** of a user you want to get profile data for 
    user = User.objects.get(pk=pk) # get the user with the passed **pk**
    profile_picture = ProfilePicture.objects.get(user=user) # get the user profile picture
    context = {}
    context['profile_picture'] = profile_picture
    context['user'] = user
    return render(request, 'pprofile.html', context)

所有用户.html

"""
List all usernames as the links to their profiles.
"""


{% for user in users %}
    <a href="{% url 'profile' user.pk %}">{{ user.username }}</a> # here is where you pass a parameter to the url
{% endfor %}

profile.html

<h1>This is the profile of {{ user.username }} </h1> # user from context
{% if profile_picture %}
    <img src="{{ profile_picture.image.url }}" alt='/'> # image from context (here you get the image field url attribute and pass it to img tag for display)
{% else %}
    <p> This user doesn't have a picture yet </p>
{% endif %}

upload\u profile\u picture.html

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Add Profile Picture</button>
</form>

p.S.snake_case表示regular views,用PascalCase表示Class-Based-Views

相关问题 更多 >