Home > Net >  matching query does not exist. Django Error
matching query does not exist. Django Error

Time:11-15

this is my code for my project, I just get this error I tried to figure it out but I don't get it,

Django Error:

DoesNotExist at /save_post/

Profile matching query does not exist.

views.py, line 75, in save_post form.authore = Profile.objects.get(user=request.user)

views.py

    @login_required
    def save_post(request):
        if request.method == "POST":
            form = Post(content=request.POST['content'])
            form.authore = Profile.objects.get(user=request.user)
            form.save()
        elif request.method == "PUT":
            data = json.loads(request.body)
            post_id = int(data["post_id"])
            new_content = data["new_content"]
            post = Post.objects.filter(id=post_id).first()
            if post.authore.user != request.user:
                return HttpResponse(status=401)
            post.content = new_content
            post.save()
            return JsonResponse({
                "result": True
            }, status=200)
        else:
            return JsonResponse({
                "error": "post not found"
            }, status=400)
        return index(request)

models.py

    class User(AbstractUser):
    pass


class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)


class Post(models.Model):
    content = models.TextField()
    timestamp = models.DateTimeField(default=timezone.now)
    authore = models.ForeignKey(Profile, on_delete=models.CASCADE)
    likes = models.PositiveIntegerField(default=0, blank=True, null=True)

    def serialize(self):
        return {
            "id": self.id,
            "content": self.content,
            "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"),
            "authore": self.authore.id,
            "username": self.authore.user.username,
            "likes": self.likes.count(),
        }

CodePudding user response:

this seems correct but you already this user you are using doesn't have profile so here my notes :

You can use get_object_or_404 this if profile not found will return not found

from django.shortcuts import  get_object_or_404
form.authore =  get_object_or_404(Profile, user=request.user)

when user-created no logic here profile must created so it is logical user doesn't have profile

it is better to use one_to_one relation ship when creating user profile as each user has only one profile and vice versa

to make it correct working refer here https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

go to Extending User Model Using a One-To-One Link in previous link

field execute this tutorial and user profile will created auto when user created

  • Related