Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function view throws an exception of UnboundLocalError at /group/share/42/ when a user tries share a post

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading