Django實現教育平臺全程記錄-----後臺管理

旅行耗發表於2018-05-20

課程機構列表頁面資料展示

本地圖片上傳至Django專案中

model

class CourseOrg(models.Model):
    city = models.ForeignKey(CityDict,verbose_name=u"所在城市")
    name = models.CharField(max_length=100,verbose_name=u"機構名稱")
    category = models.CharField(default='pxjg',choices=(("pxjg",u"培訓機構"),("gx",u"高校"),("gr",u"個人")),max_length=10,verbose_name=u"機構類別")
    desc = models.TextField(verbose_name=u"機構描述")
    fav_nums = models.IntegerField(default=0,verbose_name=u"收藏人數")
    click_nums = models.IntegerField(default=0,verbose_name=u"點選人數")
    addr = models.CharField(max_length=100,verbose_name=u"機構地址")
    image = models.ImageField(upload_to="org/%Y%m",verbose_name="logo")
    add_time = models.DateTimeField(default=datetime.now,verbose_name=u'新增時間')

通過xadmin插入img,從本地上傳檔案,需要在setting中配置MEDIA_ROOT,並在Django目錄下新建“media”目錄。(MEDIA_URL配置url會用到),


MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

這樣點選“選擇檔案”上傳,本地圖片會傳到Django的media中。


顯示本地上傳的圖片

在settings中的TEMPLATES中新增

'django.core.context_processors.media',
這樣在前端的{{ MEDIA_URL }}才能轉換成 “/media/”。
            {% for obj in queryOrg %}
                 <a href="org-detail-homepage.html">
                     <img width="200" height="120"   src="{{ MEDIA_URL }}{{ obj.image }}"/>
                  </a>
            {% endfor %}

此時,雖然前端顯示的url正確了,,但是還是不能顯示圖片,需要在前端配置url,才能正常顯示圖片。

from django.views.static import serve
from settings import MEDIA_ROOT

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

實現分頁

https://blog.csdn.net/qq_34964399/article/details/79596428

按照點選量前3進行排序
hot_orgs = CourseOrg.objects.all()order_by("-click_nums")[:3]
按照城市和類別並聯篩選 課程機構
class OrgView(View):
    def get(self,request):
        Citys = CityDict.objects.all()
		Orgs =  CourseOrg.objects.all()
		
        # 城市篩選
        cur_city = request.GET.get('city','')
        if cur_city:
            Orgs = Orgs.filter(city__id=int(cur_city))
			
        # 類別篩選
        cur_category = request.GET.get('category',"")
        if cur_category:
            Orgs = Orgs.filter(category=cur_category)

        return render(request,'org-list.html',{"Citys":Citys,"orgs":orgs,
                                               'OrgsNum':OrgsNum,
                                               "cur_city":cur_city,
                                               "cur_category":cur_category,
                                               })

前端

<li>
	<h2>機構類別</h2>
	<div class="cont">
		<a href="?city={{ cur_city }}&category="><span {% ifequal cur_category "" %}class="active2"{% endifequal %}>全部</span></a>
		<a href="?city={{ cur_city }}&category=pxjg"><span {% ifequal cur_category "pxjg" %}class="active2"{% endifequal %}>培訓機構</span></a>
		<a href="?city={{ cur_city }}&category=gx"><span {% ifequal cur_category "gx" %} class="active2"{% endifequal %}>高校</span></a>
		<a href="?city={{ cur_city }}&category=gr"><span {% ifequal cur_category "gr" %} class="active2"{% endifequal %}>個人</span></a>
	</div>
</li>
<li>
	<h2>所在地區</h2>
	<div class="more">更多</div>
	<div class="cont">
		<a href="?city=&category={{ cur_category }}"><span class="{% ifequal cur_city "" %}active2{% endifequal %}">全部</span></a>
		{% for city in Citys %}
			<a href="?city={{ city.id }}&category={{ cur_category }}" ><span class="{% ifequal city.id|stringformat:'i' cur_city %}active2{% endifequal %}">{{ city.name }}</span></a>
		{% endfor %}
	</div>
</li>

這樣就可以並聯篩選了

Ajax和ModelForm寫使用者諮詢表單

https://blog.csdn.net/qq_34964399/article/details/80416365

通過Ajax實現使用者對機構的收藏

model

class UserFavorite(models.Model):
    user = models.ForeignKey(UserProfile,verbose_name=u"使用者")
    fav_id = models.IntegerField(default=0,verbose_name=u"資料id")
    fav_type = models.CharField(max_length=10,choices=((1,u"課程"),(2,u"課程機構"),(3,u"講師")),default=1,verbose_name=u"收藏類別")
    add_time = models.DateTimeField(default=datetime.now,verbose_name=u"新增時間")

views

class AddFavView(View):
    def post(self,request):
        ret = {'status':True,'data':None,'error':None}
        if not request.user.is_authenticated():
            ret['status'] = False
            return HttpResponse(json.dumps(ret))
        # 判斷該機構是否已經被收藏,如果已收藏:資料庫刪除該記錄,變成未收藏
        org_id = request.POST.get("fav_id",0)   # 如果不寫0,如果未取到fav_id則為None,下面的filter中fav_id=None的話會錯
        fav_type = request.POST.get("fav_type",0)
        exist_record = UserFavorite.objects.filter(user=request.user,fav_id=int(org_id),fav_type=int(fav_type))
        # 該機構已經被使用者收藏則取消收藏
        if exist_record:
            exist_record.delete()
            ret['data'] = "收藏"
            return HttpResponse(json.dumps(ret))
        # 該機構未被使用者收藏
        else:
            if int(org_id) > 0 and int(fav_type) > 0:
                userFav = UserFavorite()
                userFav.user = request.user
                userFav.fav_id = int(org_id)
                userFav.fav_type = int(fav_type)
                userFav.save()
                ret['data'] = "已收藏"
                return HttpResponse(json.dumps(ret))
            else:
                ret['status'] = False
                ret['data'] = "收藏出錯"
                return HttpResponse(json.dumps(ret))

前端Ajax

$('.collectionbtn').on('click',function(){
    $.ajaxSetup({
        beforeSend:function(xhr,settings){
            xhr.setRequestHeader('X-CSRFtoken',"{{csrf_token}}");
            }
        });
    $.ajax({
        url:'{% url 'org:add_fav' %}',
        type:'POST',
        data:{'fav_id':{{ course_org.id }},'fav_type':2},  
        success:function(data){  // 這個data是上面的data傳送給服務端後,服務端返回的值
            var ret = JSON.parse(data);
                        if(ret['status'])
                        {$(".collectionbtn").html(ret['data'])}
                        else
                        {if(ret['data'] == "收藏出錯" ){
                            alert(ret['data']);
                        }
                            else{
                                window.location.href="/login/";
                            }
                        }
        },
        error:function(){
            alert('error')  // 如果後端發生了未知錯誤(捕獲到的錯誤不是未知錯誤),則會執行這裡。比如 return HttpResponse(json.dumps(a1qdwq))
        }
    })
});

這樣就可以收藏和取消收藏了


新增學習使用者

https://blog.csdn.net/qq_34964399/article/details/79515440     第一段

機構,教師,課程搜尋

https://blog.csdn.net/qq_34964399/article/details/80568374

相關文章