上传下载图片,django-filter

2019-09-26  本文已影响0人  快去学习不然怎么去看aimer

上传下载图片

上传图片

在models中:
avatar = models.ImageField(verbose_name="头像", upload_to='users/%Y/%m/%d/', 
    max_length=128, null = True, blank = True)

在settings.py中
MEDIA_ROOT = os.path.join(BASE_DIR,"media") 

MEDIA_URL = '/media/'

在html中
<form action="{% url 'users:usersreg' %}" method="POST" enctype="multipart/form-data" >
<div class="form-group">
                            <label for="id_avatar">头像</label>
                            <input type="file" class="form-control" name="avatar" id="id_avatar">
                            {% if form.errors.avatar %}
                            <div class="alert alert-danger" role="alert">{{ form.errors.avatar.0 }}</div>
                            {%  endif  %}
                        </div>
</from>

下载图片

在settings.py:
TEMPLATES = [{
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.media',
         ],
      },
  },
]


在项目根目录urls.py:
from qfgp01site.settings import MEDIA_ROOT
from django.views.static import serve

urlpatterns = [
    re_path(r'^media/(?P<path>.*)$', serve, {"document_root": MEDIA_ROOT}),
]

在html中
<img src="{{ MEDIA_URL }}{{ request.user.avatar }}" alt="头像" class="img-circle naver">

django-filter

进行信息过滤

流程:
html的ajax请求-->views-->cmdb_django_filter(filter的过滤选项)-->views.reutrn-->html

pip3 install django-filter
pip3 install django-widget-tweaks


在settings中注册应用:
'django_filters',
'widget_tweaks',

在views:
def server_list(request):
    f = ServerFilter(request.GET, queryset=Server.objects.all())
    return render(request, 'cmdb/server-list.html', {"filter": f}) 

在cmdb_django_filter:
class ServerFilter(django_filters.FilterSet):
    class Meta:
        model = Server
        fields = {
            'host_name': ['exact', ],
            'physical_count': ['lt', 'gt'],
            'kernel': ['exact']
        }

html中:
{% load widget_tweaks %}

<div class="col-md-11">
                {{ filter.form.host_name.label_tag }}
                {{ filter.form.host_name|add_class:"form-control" }}    
                {{ filter.form.physical_count__lt.label_tag }}
                {{ filter.form.physical_count__lt|add_class:"form-control" }}
                {{ filter.form.physical_count__gt.label_tag }}
                {{ filter.form.physical_count__gt|add_class:"form-control" }}
</div>
上一篇下一篇

猜你喜欢

热点阅读