Home > Software design >  Function view throws an exception of UnboundLocalError at /group/share/42/ when a user tries share a
Function view throws an exception of UnboundLocalError at /group/share/42/ when a user tries share a

Time:12-25

What could possibly be the course of this exception UnboundLocalError at /group/share/42/ when i try sharing post of another user in a group.The exception trace seems to be on the the first line of the forloop ( new = new_post.video.add(img) ) Here is my view for users to share post


def share_post(request, pk):
    original_post = Post.objects.get(pk=pk)
    form = ShareForm(request.POST)
    if form.is_valid():
        new_post = Post(
            shared_body = request.POST.get('description'),
            description = original_post.description,
            username = original_post.username,
            date_posted = original_post.date_posted,
            shared_on = timezone.now(),
            shared_user = request.user)
        new_post.save()
    for img in original_post.video:
        shared  = new_post.video.add(img)
        shared.save()
    return redirect('group:main',original_post.group.pk)

Here is my model Post.

CodePudding user response:

new_post will only be assigned a value if the form is valid, so you should indent the for loop:

def share_post(request, pk):
    original_post = Post.objects.get(pk=pk)
    form = ShareForm(request.POST)
    if form.is_valid():
        new_post = Post(
            shared_body = request.POST.get('description'),
            description = original_post.description,
            username = original_post.username,
            date_posted = original_post.date_posted,
            shared_on = timezone.now(),
            shared_user = request.user
        )
        new_post.save()
        for img in original_post.video:
            new_post.video.add(img)
    return redirect('group:main',original_post.group.pk)
  • Related