简体   繁体   English

如何修复matchong查询不存在错误?

[英]How to fix matchong query does not exist error?

I have been working on a like system using django and ajax, this like system is very similar to instagram's one.我一直在使用 django 和 ajax 开发类似的系统,这个类似的系统与 instagram 的系统非常相似。 After finishing with the code I started to get a Post matching query does not exist error which has been a pain.完成代码后,我开始收到一个Post matching query does not exist错误,这一直很痛苦。 I dont see the wrong in my code but I think the problem is on the views.py file because the traceback is triggering a line there.我在我的代码中没有看到错误,但我认为问题出在 views.py 文件上,因为回溯在那里触发了一行。 How can i fix this error?我该如何解决这个错误?

models.py模型.py

class Post(models.Model):
      text = models.CharField(max_length=200)
      user = models.ForeignKey(User, on_delete=models.CASCADE, default='username')
      liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')

      def __str__(self):
        return str(self.id)

views.py (upload view uploades the form, home displays the uploaded form, like_post is the view in charged of liking and unliking posts and home_serialized os the one that contains the json so that the page doesnt reload when the like button is clicked) views.py (upload view 上传表单,home 显示上传的表单,like_post 是负责喜欢和不喜欢帖子的视图,home_serialized os 包含 json 以便点击like按钮时页面不会重新加载)

def upload(request):
      print("toro")
      if request.method == 'POST':
        print("caballo")
        form = PostForm(request.POST)
        if form.is_valid():
          instance = form.save(commit=False)
          instance.user = request.user
          instance.save()
          return redirect('home')
          print('succesfully uploded')
      else:
        form = PostForm()
        print('didnt upload')
      return render(request, 'home.html', {'form': form})

def home(request):
    contents = Post.objects.all()
    args = {
        'contents': contents,
    }
    return render(request, 'home.html', args)

def like_post(request):
    user = request.user
    if request.method == 'POST':
        pk = request.POST.get('post_pk')
        post_obj = Post.objects.get(pk=pk)

        if user in post_obj.liked.all():
            post_obj.liked.remove(user)
        else:
            post_obj.liked.add(user)

    return HttpResponse()

def home_serialized(request):
    data = list(Post.objects.values())
    return JsonResponse(data, safe=False)


urls.py网址.py

urlpatterns = [
    path('', views.home, name='home'),
    path('upload', views.upload, name='upload'),
    path('like/', views.like_post, name='like-post'),
    path('serialized/', views.home_serialized, name='serialized-view'),
]

home.html主页.html

    <form method='post'  action="{% url 'upload' %}">
        {% csrf_token %}
        <input type="text" name="text" placeholder="Add a comment..." required="" id="id_text">
        <button class="submit-button" type="submit">Save</button>
    </form>
    {% for content in contents %}
        {% if content %}
        <ul class="list-group">
            <li class="list-group-item">{{ content.text }}</li>
            <form action="{% url 'like-post' %}" class='like-form' method="POST" id={{content.id}}>
                {% csrf_token %}
                <input type='hidden' name="post_ok" value="{{ content.ok }}">
                <button class='like-btn{{ content.id }}'>
                  {% if request.user in content.liked.all %}
                      Unlike
                  {% else %}
                      Like
                  {% endif %}
                </button>
              </form>
              <strong>{{ content.liked.all.count }}</strong>
        </ul>
        {% endif %}
    {% endfor %}
    <script type='text/javascript'>
        $(document).ready(function(){
            $('.like-form').submit(function(e){
              e.preventDefault()
              console.log('works')
              const post_id = $(this).attr('id')
              console.log(this)
              console.log(post_id)
              const likeText = $(`.like-btn${post_id}`).text()
              console.log(likeText)
              const trim = $.trim(likeText)
              console.log(trim)
              const url = $('.like-form').attr('action')
              console.log(url)

              $.ajax({
                type: 'POST',
                url: url,
                data : {
                  'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
                  'post_pk': post_id,
                },
                success: function(error){
                  console.log('success')

                  $.ajax({
                    type: 'GET',
                    url: 'http://127.0.0.1:8000/serialized/',
                    success: function(response){
                      console.log(response)
                      $.each(response, function(index, element){
                        console.log(index)
                        console.log(element.content)
                        if (post_id == element.id) {
                          if(trim == 'Like') {
                            console.log('unlike')
                            $(`.like-btn${post_id}`).html('Unlike')
                          } else if (trim == 'Unlike') {
                            console.log('like')
                            $(`.like-btn${post_id}`).html('Like')
                          } else {
                            console.log('ups')
                          }
                        }
                      })
                    },
                    error: function(error){
                      console.log('error')
                    }
                  })
                },
                error: function(error){
                  console.log('error', error)
                }
              })
            })
        });
    </script>

traceback追溯

Traceback (most recent call last):
  File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\MaríaPaola\projects\nwpc\like\views.py", line 65, in like_post
    post_obj = Post.objects.get(pk=pk).exists()
  File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 415, in get
    raise self.model.DoesNotExist(
like.models.Post.DoesNotExist: Post matching query does not exist.

I'm not sure what it says in the traceback.我不确定它在回溯中说了什么。 If you could provide that, maybe it'll make more sense.如果你能提供它,也许它会更有意义。 But I assume it's because of the like post_obj = Post.objects.get(pk=pk) in def like_post(request) function.但我认为这是因为def like_post(request) function 中的 like post_obj = Post.objects.get(pk=pk)

Post with the given primary key does not exist.具有给定主键的帖子不存在。 What you can do is to check if the pk exists.您可以做的是检查 pk 是否存在。

if Post.objects.filter(pk=pk).exists():
    # it exist

or you can do a try except method或者你可以try except方法

try:
    post_obj = Post.objects.get(pk=pk)

    if user in post_obj.liked.all():
        post_obj.liked.remove(user)
    else:
        post_obj.liked.add(user)
except:
    # what happens if post does not exist

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 Typescript 中的“元素”类型错误不存在属性? - How to fix property does not exist on type 'Element' error in Typescript? 当 object 确实存在时,如何修复 404 错误? - How to fix a 404 error when the object does exist? 尝试在 Vue.js 中显示 highcharts 图时,如何修复错误 #17“请求的系列类型不存在”错误? - How can I fix the error #17 "The requested series type does not exist" error when trying to display a highcharts graph in Vue.js? 离子3中“对象”类型中不存在如何修复属性? - how to fix property does not exist on type 'Object' in ionic 3? 如何修复“类型&#39;typeof firestore&#39;上不存在属性&#39;getAll&#39;” - How to fix "Property 'getAll' does not exist on type 'typeof firestore'" 如何修复 typeScript 中的“对象”类型上不存在“属性”拨号 - how to fix 'Property 'dials' does not exist on type 'Object' in typeScript 如何修复反应中的“MutableRefObject”类型上不存在“setOption” - How to fix the 'setOption' does not exist on type 'MutableRefObject in react Vue i18n中带有TypeScript的错误:类型&#39;VueConstructor&#39;上不存在属性&#39;$ t&#39;。 ”。 我该如何解决? - Error in Vue i18n with TypeScript: “Property '$t' does not exist on type 'VueConstructor'. ” . How can I fix it? 如何使用 javascript 修复类型 never[] 的错误属性不存在? - How to fix the error property doesnt exist with type never[] using javascript? postgreSQL错误:“约束不存在”(但确实存在……) - postgreSQL error: “constraint does not exist” (but it does exist…)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM