如何使用Django

时间:2018-10-25 06:59:30

标签: django

我想在我的应用程序上创建一个推荐引擎。我可以为帖子评分,但是我已经能够创建推荐引擎,向用户推荐应用程序中几乎具有相似评分的类似帖子。我已经有一个RESTAPI。我该如何解决? 这是我的模型。py

from django.db import models
from django.contrib.auth.models import User
from django.db.models import Avg
from tinymce.models import HTMLField
import numpy as np

# Create your models here.
class Profile(models.Model):
profile_photo = models.ImageField(upload_to ='prof_pictures/')
bio = HTMLField()
phone = models.IntegerField(default=0) 
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)

def save_profile(self):
    self.save()

def delete_profile(self):
    self.delete()

@classmethod
def get_profile(cls,id):
    profile = Profile.objects.get(user = id)
    return profile

@classmethod
def filter_by_id(cls,id):
    profile = Profile.objects.filter(user=id).first()
    return profile

# @classmethod
# def search_profile(cls,name):
#     profile = Profile.objects.filter(user__username__icontains = name)
#     return profile



class Project(models.Model):
photo = models.ImageField(upload_to ='prof_pictures/')
project_name = models.CharField(max_length = 100)
project_caption =  models.CharField(max_length = 100)
user_profile = models.ForeignKey(User, on_delete=models.CASCADE, related_name='projects', default="")

def save_project(self):
    self.save()

def delete_project(self):
    self.delete()

@classmethod
def search_project(cls,search_term):
    projects = cls.objects.filter(project_name__icontains=search_term)
    return projects

@classmethod
def get_project(cls, id):
    project = Project.objects.get(pk=id)
    return project

@classmethod
def get_images(cls):
    projects = Project.objects.all()
    return projects

@classmethod
def get_profile_image(cls,profile):
    projects = Project.objects.filter(user_profile__pk=profile)
    return projects

def design_rating(self):
    all_designs =list( map(lambda x: x.design, self.reviews.all()))
    return np.mean(all_designs)

def usability_rating(self):
    all_usability =list( map(lambda x: x.usability, self.reviews.all()))
    return np.mean(all_usability)

def content_rating(self):
    all_content =list( map(lambda x: x.content, self.reviews.all()))
    return np.mean(all_content)



class Reviews(models.Model):
RATING = (
    (1, '1'),
    (2, '2'),
    (3, '3'),
    (4, '4'),
    (5, '5'),
    (6, '6'),
    (7, '7'),
    (8, '8'),
    (9, '9'),
    (10, '10'),
)
comment = HTMLField()
project = models.ForeignKey(Project,on_delete=models.CASCADE, related_name='reviews',null=True)
design = models.IntegerField(choices=RATING,default=0)
usability = models.IntegerField(choices=RATING,default=0)
content = models.IntegerField(choices=RATING,default=0)
user = models.ForeignKey(User, on_delete=models.CASCADE,null=True)

def save_review(self):
    self.save()

@classmethod
def get_reviews(cls,id):
    reviews = Reviews.objects.filter(project_id = id)
    return reviews

@classmethod
def get_average(cls):
    usability =Reviews.objects.all().aggregate(Avg('usability'))
    return usability

这是我的views.py:

 from django.http import HttpResponse
 from django.shortcuts import render, redirect,get_object_or_404
 from django.contrib.auth.models import User
 from django.contrib.auth.decorators import login_required
 from .forms import RegistrationForm, ProjectForm, ReviewForm, ProfileForm
 from .models import Profile,Project,Reviews
 from rest_framework.response import Response
 from rest_framework.views import APIView
 from rest_framework import status
 from .serializer import ProfileSerializer, ProjectSerializer
 from .permissions import IsAdminOrReadOnly
 import numpy as np


 # Create your views here.

def home(request):
images = Project.get_images()


return render(request, 'home.html', {'images':images})

def register(request):
if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            redirect('login.html')
else:
    form=RegistrationForm()
    return render(request, 'registration/registration_form.html', {'form':form})



def profile(request, username):
profile = User.objects.get(username=username)
try:
    profile_info = Profile.get_profile(profile.id)
except:
    profile_info = Profile.filter_by_id(profile.id)
projects = Project.get_profile_image(profile.id)
title = f'@{profile.username}'
return render(request, 'profile/profile.html', {'title':title, 'profile':profile, 'profile_info':profile_info, 'projects':projects})  

@login_required(login_url='/accounts/login')
def project(request):
if request.method == 'POST':
    form = ProjectForm(request.POST, request.FILES)
    if form.is_valid():
        upload = form.save(commit=False)
        upload.user_profile = request.user
        upload.save()
        return redirect('profile', username=request.user)
else:
    form = ProjectForm()

return render(request, 'profile/uploadproject.html', {'form':form})

@login_required(login_url='/accounts/login')
def project_review(request, project_id):
project = Project.get_project(project_id)
reviews = Reviews.get_reviews(project_id)
if request.method == 'POST':
    form = ReviewForm(request.POST)
    if form.is_valid():
        design = form.cleaned_data['design']
        usability = form.cleaned_data['usability']
        content = form.cleaned_data['content']
        review = form.save(commit=False)
        review.project = project
        review.user = request.user
        review.design = design
        review.usability = usability
        review.content = content
        review.save()
        return redirect('project_review', project_id=project_id)
else:
    form = ReviewForm()
    return render(request,'review.html',{'project':project ,'form':form, 'reviews':reviews})

@login_required(login_url='/accounts/login')
def edit_profile(request):

if request.method == 'POST':
    form = ProfileForm(request.POST, request.FILES)
    if form.is_valid():
        edit = form.save(commit=False)
        edit.user = request.user
        edit.save()
        return redirect('profile', username=request.user)

else:
    form = ProfileForm()

return render(request, 'profile/editprofile.html', {'form':form, 'profile':profile})

def search_project(request):
if 'project' in request.GET and request.GET["project"]:
    search_term = request.GET.get("project")
    found_project = Project.search_project(search_term)
    message = f'{search_term}'

    return render(request, 'search.html',{'message':message, 'projects':found_project})
else:
    message = 'Enter term to search'
    return render(request, 'search.html', {'message':message})


class ProfileList(APIView):
def get(self, request, format=None):
    all_profiles = Profile.objects.all()
    serializers = ProfileSerializer(all_profiles,many=True)
    return Response(serializers.data)

def post(self, request, format=None):
    serializers = ProfileSerializer(data=request.data)
    if serializers.is_valid():
        serializers.save()
        return Response(serializers.data, status=status.HTTP_201_CREATED)
    return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)



class ProjectList(APIView):
def get(self, request, format=None):
    all_projects = Project.objects.all()
    serializers = ProjectSerializer(all_projects,many=True)
    return Response(serializers.data)


def post(self, request, format=None):
    serializers = ProjectSerializer(data=request.data)
    if serializers.is_valid():
        serializers.save()
        return Response(serializers.data, status=status.HTTP_201_CREATED)
    return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)

class ProfileDescription(APIView):
permission_classes = (IsAdminOrReadOnly,)
def get_profile(self, pk):
    try:
        return Profile.objects.get(pk=pk)
    except Profile.DoesNotExist:
        return Http404

def get(self, request, pk, format=None):
    profile = self.get_profile(pk)
    serializers = ProfileSerializer(profile)
    return Response(serializers.data)

def put(self, request, pk, format=None):
    profile = self.get_profile(pk)
    serializers = ProfileSerializer(profile, request.data)
    if serializers.is_valid():
        serializers.save()
        return Response(serializers.data)
    else:
        return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)

def delete(self, request, pk, format=None):
    profile = self.get_profile(pk)
    profile.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)

class ProjectDescription(APIView):
permission_classes = (IsAdminOrReadOnly,)
def get_project(self, pk):
    try:
        return Project.objects.get(pk=pk)
    except Project.DoesNotExist:
        return Http404

def get(self, request, pk, format=None):
    project= self.get_project(pk)
    serializers = ProjectSerializer(project)
    return Response(serializers.data)


def put(self, request, pk, format=None):
    project = self.get_project(pk)
    serializers = ProjectSerializer(project, request.data)
    if serializers.is_valid():
        serializers.save()
        return Response(serializers.data)
    else:
        return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)


def delete(self, request, pk, format=None):
    project = self.get_project(pk)
    project.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)

0 个答案:

没有答案