在Django中按字符串过滤

时间:2018-08-13 11:44:30

标签: python django django-rest-framework

我有2个模型:UserProfile和User_Details,我想显示一个用户的详细信息。我认为问题出在过滤器上,我不知道如何在字符串后面进行过滤,这是django的新手。我该如何解决?

class ShowProfile(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'profile.html'


    def get(self, request, pk, format=None):
        details=User_Details.objects.all().filter(user=request.user.username)
        serializer = ProfileSerializer2(details, many=True)
        pprint.pprint(json.loads(JSONRenderer().render(serializer.data)))
        return Response({'fields ': serializer})

    def post(self, request):
        serializer = CreatePostSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({'fields': serializer })

        user = UserProfile.objects.filter(username=request.user.username).first()
        serializer.save(user=user)
        pprint.pprint(json.loads(JSONRenderer().render(serializer.data)))
        return redirect('mainPage')

型号:

class UserProfile(AbstractUser):
    pass


class User_Details(models.Model):
    user = models.OneToOneField(UserProfile, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50, blank = True)
    last_name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=6, blank=True, default='')
    public_info=models.CharField(max_length=100, blank=True, default='')

模板:

{% extends 'base2.html' %}
{% load rest_framework %}
{% block content %}
<div class="container">


    <div class="row">
        <div class="col-md-3 ">
             <div class="list-group ">
              <a href="#" class="list-group-item list-group-item-action active">Profile</a>
              <a href="{% url 'show_my_posts'  pk=user.id %}" class="list-group-item list-group-item-action">My Posts</a>
         </div>
</div>
{% for d in fields %}
  {{d.firs_name }}<h1>a</h1>
{% endfor %}


{% endblock %}

0 个答案:

没有答案