0

i m trying to make an initialized form if my model object of a purticular user already exists but it is giving an attribute error

my views.py-

def edit_profile(request):
    if request.method == 'POST':
        post = request.POST
        if 'save' in post:
            form = user_profile_form(post)
            if form.is_valid():
                f = form.save(commit = False)
                f.username = request.session.get('username')
                f.save()
                return redirect('wall')
            else:
                return redirect('error')
    else:
        if 'username' in request.session:
            u = user_profile.objects.filter(username = request.session.get('username', ''))
            if u:
                form = user_profile_form(initial = {'last_name': u.last_name})
                u.delete()
            else:
                form = user_profile_form()
            return render(request, 'wall/edit_profile_page.html', {'form': form})
        else:
            return redirect('error')

and my models.py-

class user_profile(models.Model):
    username = models.CharField(max_length = 30, blank = True)
    first_name = models.CharField(max_length = 30, blank = True)
    last_name = models.CharField(max_length = 30, blank = True)

and it is giving error -

'QuerySet' object has no attribute 'last_name'

even if u exists

thanks in advance

2 Answers 2

1

You can try this

try:
   u = user_profile.objects.get(username =request.session.get('username', None))
   form = user_profile_form(initial = {'last_name': u.last_name})
   u.delete()
except ObjectDoesNotExist:
   form = user_profile_form()
Sign up to request clarification or add additional context in comments.

Comments

0

Queryset is a "list" of objects. You should get the first instance from the queryset using the first() method:

u = user_profile.objects.filter(username=request.session.get('username', '')) \
                        .first()

3 Comments

i just tried that using user_profile.get() and it worked..which is better..and what does .get() do??
In addition to the answer, you shouldn't search for an empty string when username is not found. There might be a user with an empty username in your table. Just use request.session.get('username')
If the record is not found then get() throws the ObjectDoesNotExist exception. first() in this case just returns None.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.