django_day10_项目相关
-
展示数据的方法
-
数据对象obj
- 普通字段
- obj.字段名 ====》 数据库该字段的值
-
带choices参数的
- obj.字段名 ====》 数据库该字段的值
obj.get_字段名_display() ====》 要显示的结果
-
外键
- obj.外键====》 所关联的对象
__str__
方法 - obj.外键.字段
- obj.外键====》 所关联的对象
-
自定义方法
from django.utils.safestring import mark_safe def show_publish_status(self): color_dict = {True:'green',False:'#772a4d'} return mark_safe('<span style="background: {};color: white;padding: 3px">{}</span>'.format(color_dict[self.publish_status],self.get_publish_status_display()))
-
-
定义modelform
class ArticleForm(forms.ModelForm): class Meta: model = models.Article#只能是model fields = "__all__" exclude = ['detail'] # widgets = { # 'title':forms.TextInput(attrs={'class':'form-control'}) # } def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs)#执行父类方法 #自定义的操作 # self.fields 是个有序字典 字典中的值就是字段的对象 for field in self.fields.values():#field 就是models中定义的字段 field.widget.attrs['class'] = 'form-control'#field.widgrt # 是拿到对应的插件的对象field.widget.attrs 然后拿到对应的属性做修改
-
使用form
def article_add(request): form_obj = ArticleForm()#什么都不传 if request.method == 'POST': form_obj = ArticleForm(request.POST)#拿到form表单 #开始校验 if form_obj.is_valid(): #获取文章详情字符串 detail = request.POST.get('detail') # 创建文章详情对象 detail_obj = models.ArticleDetail.objects.create(content=detail) form_obj.instance.detail_id = detail_obj.pk form_obj.save() # form_obj.instance.save() return redirect('article_list') return render(request, 'article_add.html', {'form_obj': form_obj}) #关联了俩个表 def article_edit(request, pk): obj = models.Article.objects.filter(pk=pk).first() # 查到一个queryset对象 first拿到第一个 如果没有则返回为null form_obj = ArticleForm(instance=obj) #传了个instance对象 if request.method == 'POST': form_obj = ArticleForm(request.POST, instance=obj) # 包含数据库没修改之前的数据 以及表单提交的数据 if form_obj.is_valid(): # 通过校验 form_obj.instance.detail.content = request.POST.get('detail') form_obj.instance.detail.save()# 修改以后 还要保存 文章详情 form_obj.save()# 保存文章的信息 return render(request, 'article_edit.html', {'form_obj': form_obj, 'obj': obj}) #HTML <form class="form-horizontal" method="post" action="" novalidate> {% csrf_token %} {% for field in form_obj %} {{ field.id_for_label }} # 拿到id {{ field.label }} #提示信息 models中的 verbose_name {{ field }} #生成input框 {{ field.errors.0 }} #错误 {% endfor %} </form>
-
让用户上传图像
#model中添加ImageField avatar = models.ImageField(upload_to='img/avatar',default='img/avatar/default.jpg') #ImageField 依赖pillow模块 #settings.py中的配置 MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') #urls.py中的配置 from django.views.static import serve from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('app01.urls')), url(r'^media/(?P<path>.*)',serve,{'document_root':settings.MEDIA_ROOT}), ] #模板中使用 注册时:form中加上 enctype="multipart/form-data" 显示时:<img width="20px" src="/media/img/avatar/张伟.jpg" alt=""> #views中 form_ojb = RegForm(request.POST,request.FILES)
-
使用django-ckeditor
-
下载pip install django-ckeditor
-
注册app
INSTALLED_APPS = [ ........ 'ckeditor', 'ckeditor_uploader', ]
-
urls.py
urlpatterns = [ ......................... url(r'^ckeditor/', include('ckeditor_uploader.urls')), ]
-
models.py
class ArticleDetailForm(forms.ModelForm): class Meta: model = models.ArticleDetail # 只能是model fields = "__all__" form_obj = ArticleDetailForm()#实例化
-
html
{{ form_obj.content }}
引用静态文件
{% block js %} {% load static %} <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> {% endblock %}
-
上传需要认证,取消认证
#将staff_member_required这个装饰器取消掉 urlpatterns = [ url(r'^upload/', staff_member_required(views.upload), name='ckeditor_upload'), url(r'^browse/', never_cache(staff_member_required(views.browse)), name='ckeditor_browse'), ] #改为下面这样 from ckeditor_uploader import views urlpatterns = [ url(r'^upload/', views.upload, name='ckeditor_upload'), url(r'^browse/', never_cache(views.browse), name='ckeditor_browse'), ]
-