Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django上发布图片?_Python_Html_Django_Django Forms_Django Views - Fatal编程技术网

Python 如何在django上发布图片?

Python 如何在django上发布图片?,python,html,django,django-forms,django-views,Python,Html,Django,Django Forms,Django Views,我一直在尝试使我的代码能够发布图像,但是当我创建帖子时,图片没有显示,但是图像保存在媒体/图像上。我想知道是否有任何方法可以使代码工作,当我调用图像{{request.user.image.url}时,base.html中可能有错误 views.py def create(request): if request.method == 'POST': created_date = timezone.now() header1

我一直在尝试使我的代码能够发布图像,但是当我创建帖子时,图片没有显示,但是图像保存在媒体/图像上。我想知道是否有任何方法可以使代码工作,当我调用图像{{request.user.image.url}时,base.html中可能有错误

views.py

     def create(request):
        if request.method == 'POST':
            created_date = timezone.now()
            header1 = request.POST['header']
            content1 = request.POST['content']
            user = request.user
            uploded_file = request.FILES['image']
            created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user, image=uploded_file)
            created_obj.save()
            print('create created')
            return redirect('home')
        else:
            print('create not created')
            return render(request, 'create.html')
models.py

    class Create(models.Model):
        added_date = models.DateTimeField()
        title = models.CharField(max_length=200)
        content = models.CharField(max_length=200)
        image = models.ImageField(null=True, blank=True, upload_to='images/')
        user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1)

    class Profile(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        image = models.ImageField(default='default.jpg', upload_to='profile_pics')

        def __str__(self):
            return f'{self.user.username} Profile'
create.html

    {% extends 'home.html' %}
    {% block body %}
    <div style="margin-top: 200px; margin-left:200px;">
        <form action="create" method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <input type="text" name="header" placeholder="Add here...">
            <input type="text" name="content" placeholder="Add here...">
            <input type="file" name="image">
            <button type="submit"name="action" class="btn btn-primary mb-2">submit</button>
        </form>
    </div>
    {% endblock %}
{%extends'home.html%}
{%block body%}
{%csrf_令牌%}
提交
{%endblock%}
base.html

    {% extends 'home.html' %}
    {% block body %}
    <ul action="{% url 'create' %}" class="container-sm list-group" style="margin-top: 200px;">
        {% for created_post in created_posts %}
        <li class="list-group-item">{{ created_post.title }}
          <a href="{% url 'profile_pk' pk=created_post.user.pk %}">{{ created_post.user }}</a>
          <img class="image" src="{{ create.image.url }}">
          <p>{{ created_post.content }}</p>
          <div class="float-right">
            <form action="delete_create/{{ created_post.id }}/" action="post">
              <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
            </form>
          </div>
          <div class="float-right">
            <a href="{% url 'edit' created_post.id %}" class="btn btn-outline-warning btn-sm" style="margin-right: 5px;" role="button">Edit</a>
          </div>
        </li>     
        {% endfor %}            
    </ul>
    {% endblock %}
{%extends'home.html%}
{%block body%}
    {created_posts%%中created_post的百分比}
  • {{created_post.title} {{created_post.content}}

    删除
  • {%endfor%}
{%endblock%}
在大多数网站中,我们经常处理媒体数据,如图像、文件等。在django,我们可以借助模型字段ImageField来处理图像

在本文中,我们在一个名为image\u upload的示例项目中创建了app image\u app

第一步是在settings.py文件中添加以下代码

filter_none
brightness_4
MEDIA_ROOT =  os.path.join(BASE_DIR, 'media') 
MEDIA_URL = '/media/'
MEDIA_ROOT用于在计算机中存储文件的服务器路径。 MEDIA_URL是浏览器通过Http访问文件的参考URL

在url.py中,我们应该像这样编辑配置

如果设置为.DEBUG:

urlpatterns+=静态(settings.MEDIA\u URL, document\u root=settings.MEDIA\u root)

示例models.py应该是这样的,因为我们已经创建了一个包含酒店名称及其图像的酒店模型。 在这个项目中,我们从酒店预订网站的用户那里获取酒店名称和形象

filter_none
brightness_4
# models.py 
 class Hotel(models.Model): 
    name = models.CharField(max_length=50) 
    hotel_Main_Img = models.ImageField(upload_to='images/') 
//Here upload_to will specify, to which directory the images should reside, by default django creates the directory under media directory which will be automatically created when we upload an image. No need of explicit creation of media directory.
我们必须在image_app下创建一个forms.py文件,这里我们处理的是模型表单,以使内容更容易理解

filter_none
brightness_4
# forms.py 
from django import forms 
from .models import *



class HotelForm(forms.ModelForm): 

    class Meta: 
        model = Hotel 
        fields = ['name', 'hotel_Main_Img'] 
Django将隐式处理表单验证,而不在脚本中显式声明,它将根据models.py文件中指定的模型字段在页面中创建类似的表单字段。 这就是模型形式的优点

现在在image_app下创建一个templates目录,我们需要创建一个用于上传图像的html文件。HTML文件应该如下所示

filter_none
edit
play_arrow

brightness_4
<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Hotel_image</title> 
</head> 
<body> 
    <form method = "post" enctype="multipart/form-data"> 
        {% csrf_token %} 
        {{ form.as_p }} 
        <button type="submit">Upload</button> 
    </form> 
</body> 
</html> 
无论何时点击hotel_image_视图并且该请求是POST,我们都会创建一个模型表单form=HotelForm(request.POST,request.FILES)的实例,该图像将存储在request.FILES下。如果有效,则保存到数据库中并重定向到成功url,该url指示图像成功上载。如果方法不是POST,我们将使用创建的html模板进行渲染

url.py将如下所示-

filter_none
brightness_4
from django.contrib import admin 
from django.urls import path 
from django.conf import settings 
from django.conf.urls.static import static 
from .views import *

urlpatterns = [ 
    path('image_upload', hotel_image_view, name = 'image_upload'), 
    path('success', success, name = 'success'), 
] 

if settings.DEBUG: 
        urlpatterns += static(settings.MEDIA_URL, 
                              document_root=settings.MEDIA_ROOT) `enter code here`

在大多数网站中,我们经常处理媒体数据,如图像、文件等。在django中,我们可以借助模型字段ImageField来处理图像

在本文中,我们在一个名为image\u upload的示例项目中创建了app image\u app

第一步是在settings.py文件中添加以下代码

filter_none
brightness_4
MEDIA_ROOT =  os.path.join(BASE_DIR, 'media') 
MEDIA_URL = '/media/'
MEDIA_ROOT用于在计算机中存储文件的服务器路径。 MEDIA_URL是浏览器通过Http访问文件的参考URL

在url.py中,我们应该像这样编辑配置

如果设置为.DEBUG:

urlpatterns+=静态(settings.MEDIA\u URL, document\u root=settings.MEDIA\u root)

示例models.py应该是这样的,因为我们已经创建了一个包含酒店名称及其图像的酒店模型。 在这个项目中,我们从酒店预订网站的用户那里获取酒店名称和形象

filter_none
brightness_4
# models.py 
 class Hotel(models.Model): 
    name = models.CharField(max_length=50) 
    hotel_Main_Img = models.ImageField(upload_to='images/') 
//Here upload_to will specify, to which directory the images should reside, by default django creates the directory under media directory which will be automatically created when we upload an image. No need of explicit creation of media directory.
我们必须在image_app下创建一个forms.py文件,这里我们处理的是模型表单,以使内容更容易理解

filter_none
brightness_4
# forms.py 
from django import forms 
from .models import *



class HotelForm(forms.ModelForm): 

    class Meta: 
        model = Hotel 
        fields = ['name', 'hotel_Main_Img'] 
Django将隐式处理表单验证,而不在脚本中显式声明,它将根据models.py文件中指定的模型字段在页面中创建类似的表单字段。 这就是模型形式的优点

现在在image_app下创建一个templates目录,我们需要创建一个用于上传图像的html文件。HTML文件应该如下所示

filter_none
edit
play_arrow

brightness_4
<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Hotel_image</title> 
</head> 
<body> 
    <form method = "post" enctype="multipart/form-data"> 
        {% csrf_token %} 
        {{ form.as_p }} 
        <button type="submit">Upload</button> 
    </form> 
</body> 
</html> 
无论何时点击hotel_image_视图并且该请求是POST,我们都会创建一个模型表单form=HotelForm(request.POST,request.FILES)的实例,该图像将存储在request.FILES下。如果有效,则保存到数据库中并重定向到成功url,该url指示图像成功上载。如果方法不是POST,我们将使用创建的html模板进行渲染

url.py将如下所示-

filter_none
brightness_4
from django.contrib import admin 
from django.urls import path 
from django.conf import settings 
from django.conf.urls.static import static 
from .views import *

urlpatterns = [ 
    path('image_upload', hotel_image_view, name = 'image_upload'), 
    path('success', success, name = 'success'), 
] 

if settings.DEBUG: 
        urlpatterns += static(settings.MEDIA_URL, 
                              document_root=settings.MEDIA_ROOT) `enter code here`

什么是
context2
,它的赋值在哪里?看一看。这是现场抱歉,上下文2不应该在那里什么是
context2
,它的分配在哪里?请看。这里是现场抱歉我的上下文2不应该在那里我已经尝试过这种方式,但不知为什么它不适合我,这就是为什么我尝试与我张贴的代码。我已经试过了,但不知怎么的,它对我不起作用,这就是为什么我要尝试我发布的代码。有没有办法使它起作用。