如果存在记录,则预先填充的表单

时间:2012-04-27 07:39:14

标签: django django-forms django-views

如果用户点击“个人资料/编辑/”链接,则会加载模板。

但是如果记录已经存在,我希望预先填充模板中的字段。

我尝试了这个,但它似乎不起作用。

def editprofile(request):
    if request.user.is_authenticated():
        try:
            userprofile = UserProfiles.objects.get(user=request.user)
            form = UserProfileForm(request.POST, instance=userprofile)
        except UserProfiles.DoesNotExist:
            userprofile = None
        if userprofile:
            return render_to_response('profile_edit.html', {'form':form}, context_instance=RequestContext(request))
        else:
            return render_to_response('profile_edit.html', {'form':UserProfileForm()}, context_instance=RequestContext(request))

2 个答案:

答案 0 :(得分:2)

您的代码不起作用,因为您无法同时使用dict和实例初始化表单(form = UserProfileForm(request.POST, instance=userprofile))。您只能提供覆盖实例的初始值。

请改为尝试:

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required
def editprofile(request):
    try:
       userprofile = UserProfiles.objects.get(user=request.user)
    except UserProfiles.DoesNotExist:
       return render(request, 'profile_edit.html', {'form':UserProfileForm()})
    form = UserProfileForm(instance=userprofile)
    return render(request, 'profile_edit.html', {'form':form})

答案 1 :(得分:0)

我使用基于类的视图并使用需要的登录包装dispatch方法,有点像这样:

class ProfileView(TemplateView, ProcessFormView):

    template_name = "profile.html"

def post(self, request, *args, **kwargs):
    context = self.get_context_data()
    # Validate the form
    form = ProfileForm(request.POST, request.FILES)
    if form.is_valid():
        profile = get_object_or_404(UserProfile, user=request.user)
        if form.cleaned_data['avatar']:
            profile.avatar = form.cleaned_data['avatar']
        profile.bio = form.cleaned_data['bio']
        profile.save()

        context['form'] = ProfileForm(initial={'bio':UserProfile.objects.get(user=request.user).bio})

        # Add message
        messages.add_message(request, messages.SUCCESS, _(u"Profile saved."))

    else:
        # Add message
        messages.add_message(request, messages.ERROR, _(u"Something went wrong..."))

        context['form'] = form
    return self.render_to_response(context)

def get(self, request, *args, **kwargs):
    context = self.get_context_data()
    context['form'] = ProfileForm(initial={'bio':UserProfile.objects.get(user=request.user).bio})
    return self.render_to_response(context)

def get_context_data(self, **kwargs):
    context = super(ProfileView, self).get_context_data(**kwargs)
    context['title'] = 'profile'
    return context

@method_decorator(login_required(login_url='/'))
def dispatch(self, *args, **kwargs):
    return super(ProfileView, self).dispatch(*args, **kwargs)