سؤال

Im trying to make a simple voting app.

The user should be presented with a blank form at first, but when the user has filled in the form, the user should be presented with the same form, but with the data they filled in.

How can I present the data they put in, on the same form?

My model:

class Vote(models.Model):
    user = models.ForeignKey(User)
    vote_1 = models.ForeignKey(Song, null=True, blank=True, related_name="voted_1")
    vote_2 = models.ForeignKey(Song, null=True, blank=True, related_name="voted_2")
    vote_3 = models.ForeignKey(Song, null=True, blank=True, related_name="voted_3")
    creation_date = models.DateTimeField(auto_now_add=True)
    edited = models.DateTimeField(auto_now=True)

My view:

def show_voteform(request):

    if request.method == 'POST':

        form = VoteForm(request.POST)

        if form.is_valid():

            form.save()

            messages.success(request, "Vote saved", extra_tags='alert-success')

            #Return the user to same page
            return HttpResponseRedirect('/vote/')

    else:
        form = VoteForm(initial={'user':request.user, 'vote_1':???, 'vote_2':???, 'vote_3':???,})

    return render(request, 'vote/form.html', {
        'form': form,
    })

Is this something I could provide in initial, or do I have to do this another way?

Edit:

Changed it to this:

else:
    try:
        vote = Vote.objects.filter(user=request.user).latest('creation_date')
        form = VoteForm(instance=vote)
    except Vote.DoesNotExist:        
        form = VoteForm(initial={'user':request.user})
هل كانت مفيدة؟

المحلول

If your VoteForm is a ModelForm, then you can show the form with data from a model instance filled in using:

# get the most recent Vote by this user
vote = Vote.objects.filter(user=request.user).latest('creation_date')
# fill in the form with data from the instance
form = VoteForm(instance=vote)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top