2

如果用户单击“配置文件/编辑/”链接,则会加载模板。

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

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

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))
4

2 回答 2

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})
于 2012-04-27T10:39:15.657 回答
0

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

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)
于 2012-04-27T07:55:55.730 回答