2014-01-13 2 views
0

User 모델의 모델에 OneToOneField가 User 인 '계정'앱이 있습니다. 사용자 인스턴스가 생성되면 관련 프로필 인스턴스도 자동으로 만들어집니다.django 1.6.1, 양식 오래된 데이터를 렌더링하고 모델에서 오래된 데이터를 편집하는 우아한 방법이 있습니까?

이제 기존 사용자의 프로필 3 개를 편집하기위한 양식이 포함 된 페이지를 디자인합니다. 사용자가 'accounts/profile_edit/1 /'과 같은 url을 요청하면 요청한 사용자가 합법적 인 경우 세 필드의 이전 프로필 데이터를 얻은 다음 이전 데이터가있는 편집 페이지에 대한 응답을 형태.

현재의 솔루션이 제대로 작동하지만 우아하지 않다고 생각합니다. 불필요한 데이터베이스 쿼리 낭비가있을 수 있습니다. 주로 두 가지 방법이 있습니다 :

프로필 편집 양식의 초기 값으로 오래된 프로파일 데이터를 얻는 방법.

기존 프로필의 편집 데이터를 저장하는 방법입니다.

누군가 내게 조언을 해줄 수 있으면 평가 절하됩니다.

urls.py, views.py, models.py 및 forms.py fiels은 다음과 같습니다 양식을 인스턴스화하는 동안 당신은 instance 매개 변수를 전달할 수 있습니다

#urls.py 
urlpatterns = patterns('accounts.views', 
#... 
    url(r'^profile_edit/(?P<user_id>\d+)/$', 
     'profile_edit', 
     {'template_name': 'accounts/profile_edit.html'}, 
     name='profile_edit'), 
#... 
) 


#views.py 
def profile_edit(request, 
    template_name, 
    user_id, 
    edit_form=ProfileForm,): 

    if not request.user.is_authenticated(): 
     return HttpResponseRedirect(reverse('accounts:login'), 
     ) 

    #ensure the request user is the edit user 
    if request.user.pk!=int(user_id): 
     raise Http404 

    if request.method == 'POST': 
     form = edit_form(data=request.POST) 
     if form.is_valid(): 
      form.edit(profile=request.user.profile) 
      return HttpResponseRedirect(reverse('accounts:profile',kwargs={'user_id':user_id})) 
    else: 
     #render old profile data, also seems not elegant...how to solve it? 
     profile = request.user.profile 
     old_profile={'location':profile.location, 
     'description':profile.description, 
     'signature':profile.signature, 
     } 
     form = edit_form(data=old_profile) 
    context = { 
    'form': form, 
    } 
    return TemplateResponse(request, template_name, context,) 

#models.py 
class User(AbstractBaseUser, PermissionsMixin): 
    #lots of definations here...not related to this question 

class Profile(models.Model): 
    user = models.OneToOneField(User) 
    location = models.CharField(max_length=10,blank=True) 
    description = models.CharField(max_length=200,blank=True) 
    signature = models.CharField(max_length=30,blank=True) 

#forms.py 
class ProfileForm(forms.ModelForm): 

    class Meta: 
     model = Profile 
     fields = ['location', 'description', 'signature'] 

    #this is not elegant..how to solve it? 
    def edit(self,profile): 
     profile.location = self.cleaned_data['location'] 
     profile.description = self.cleaned_data['description'] 
     profile.signature = self.cleaned_data['signature'] 
     profile.save() 

답변

1

. 이 경우 양식을 채우기 위해 사전을 만들거나 필드를 반복하여 저장할 필요가 없습니다.

로보기는 대단히 감사합니다

def profile_edit(request, 
    template_name, 
    user_id, 
    edit_form=ProfileForm,): 

    if not request.user.is_authenticated(): 
     return HttpResponseRedirect(reverse('accounts:login'), 
     ) 

    #ensure the request user is the edit user 
    if request.user.pk!=int(user_id): 
     raise Http404 

    if request.method == 'POST': 
     form = edit_form(data=request.POST, instance=request.user.profile) 
     if form.is_valid(): 
      #no need for edit method 
      updated_profile = form.save() 
      return HttpResponseRedirect(reverse('accounts:profile',kwargs={'user_id':user_id})) 
    else: 
     #no need to crate dict 
     form = edit_form(instance=request.user.profile) 
     context = { 
      'form': form, 
     } 
     return TemplateResponse(request, template_name, context,) 
+0

으로 변경 될 수 있습니다. 다른 전문가의 경우 오타가있는 것 같습니다 :'updated_profile = edit_form.save()'는'updated_profile = form.save()'이어야합니다. – tcpiper

+0

@Pythoner, 오 감사합니다. 답변을 업데이트했습니다! – Rohan

관련 문제