当试图编辑新的配置文件是在django中创建

时间:2015-03-14 09:44:46

标签: python django edit profile

我是初学者。我的项目是关于公司和客户。我为他们创建了个人资料页面。现在我想创建一个编辑页面,以便公司可以编辑他们的个人资料。 我的模特是:

class Company_Profile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(_('Company Name'), max_length= 30)
    logo = models.FileField(_('Company Logo'), upload_to=get_upload_file_name, null=True, blank=True)
    address = models.TextField(_('Contact Address'), max_length=50)
    phone_no = models.IntegerField(_('Contact No'), max_length=12) 

class Customer_Profile(models.Model):
    user = models.OneToOneField(User)
    first_name = models.CharField(_('First Name'), max_length= 30)
    middle_name = models.CharField(_('Middle Name'), max_length= 30,null =True,blank=True)
    last_name = models.CharField(_('Last Name'), max_length= 30)
    photo = models.ImageField(_('Photo'), upload_to=get_upload_file_name,   null=True, blank=True)
    address = models.TextField(_('Contact Address'), max_length=50)
    phone_no = models.IntegerField(_('Contact No'), max_length=12)

我的views.py是:

def register(request):
  if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
       user = User.objects.create_user(
       username=form.cleaned_data['username'],
       password=form.cleaned_data['password1'],
       email=form.cleaned_data['email']
        )
       return HttpResponseRedirect('/login/')
  else:
    form = RegistrationForm()
  catagories = Company_Profile.objects.all()
  customers = Customer_Profile.objects.all()
  return render_to_response('index1.html',
                      {'form': form, 'catagories': catagories,     'customers' : customers},RequestContext(request))

def edit_company(request, offset):
  if request.method == 'POST':
    company_edit = update_company_prof(request.POST)
    if company_edit.is_valid():
       company_edit.save()
       return HttpResponseRedirect('company/'+str(offset))
  else:
     company_edit = update_company_prof(instance = request.user.company_profile)
  return render_to_response('edit_comp_prof.html', {'company_edit': company_edit}, context_instance=RequestContext(request))

我的html页面是:

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ company_edit.as_p }}
<input type="submit" value="Update" />
 <input type="reset" class="btn" value="cancel">
</form>

我的编辑表格是:

class update_company_prof(forms.ModelForm):
    class Meta:
        model = Company_Profile
        fields =     ('name','logo','address','phone_no','cat_software','cat_electronics','cat_mechanical','cat_civil','cat_other','specialized_in','prev_projects')

当我提交时,会创建一个新的公司资料而不是编辑。我做错了什么。

1 个答案:

答案 0 :(得分:2)

您应该将instance参数传递给method == 'POST'分支中表单的构造函数:

company_edit = update_company_prof(request.POST,
                                   instance=request.user.company_profile)