将编辑过的信息保存在Django中

时间:2012-07-05 07:44:02

标签: django django-forms

我在我的应用程序中创建了一个表单,我可以在其中详细介绍一个suer。现在我能够编辑表单,但我无法保存数据。我想保存更改的数据并继续。

它说:此用户的成人已经存在。

我的urls.py:

url(r'^home/editform/(?P<userpk>[^/]+)/$', 'lexuseditform', name='lexuseditform'),
url(r'^home/edited/(?P<userpk>[^/]+)/$', 'lexusedited', name='lexusedited')

我的views.py:

@login_required                              
def lexuseditform(request,userpk):
    if int(userpk) != request.user.pk:
        return HttpResponseForbidden()
    else:
        adult = Adult(user=request.user)
        if request.method == 'POST': # If the form has been submitted...
            form = AdultForm(request.POST,instance=adult) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass
              form.save()
              redirect_url = reverse('lexusedited')
              return HttpResponseRedirect(redirect_url) # Redirect after POST
        else:
           form = AdultForm(instance=adult) # An unbound form

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

@login_required                              
def lexusedited(request,userpk):
    return render(request,'lexus/lexusedited.html')

我的forms.py:

从模型导入成人 来自django.forms import ModelForm

class AdultForm(ModelForm):
    """
    Edit Profile Information
    """
    class Meta:
        model = Adult
        fields = ('user', 'email','fullname')

我的models.py:

from django.db import models
from django.contrib.auth.models import User

class Adult(models.Model):
    """
    Adult Information
    """
    user = models.OneToOneField(User)
    fullname = models.CharField(max_length=100)
    email = models.EmailField()

    def __unicode__(self):
        return self.user.username

不确定我的错误在哪里。需要一些指导..谢谢..

3 个答案:

答案 0 :(得分:1)

虽然您没有显示Adult模型结构,但我敢打赌它有类似

的结构
class Adult(models.Model):
    user = models.ForeignKey(User, unique=True)

这就是为什么你不能用相同的用户(名字)保存新的Adult()。因此,您必须更改模型,或者为指定用户加载现有成人:

if Adult.objects.filter(user=request.user).exists():
    adult = Adult.objects.get(user=request.user) # load existing Adult
else:
    adult = Adult(user=request.user) # create new Adult

但我不知道你的表格和型号是怎样的。

更新:

或使用:

adult, is_created = Adult.objects.get_or_create(user=request.user)

答案 1 :(得分:1)

因为您没有发布表单和模型的代码,所以有点猜测,但假设表单是常规模型表单,那么您的问题很可能来自您对User的唯一约束的Adult模型(或者OneToOneField或带有unique=True的ForeignKey。由于您为表单创建了新的Adult实例,因此它违反了唯一约束。假设(再次)这个约束是您想要的,并且您的视图应该为用户创建相关的Adult实例(如果它尚不存在)或编辑现有的实例,您需要首先检查是否存在Adult实例对于用户:

@login_required                              
def lexuseditform(request):
    try:
        adult = Adult.objects.get(user=request.user)
    except Adult.DoesNotExist:
       adult = Adult(user=request.user)
    #... your code here

另请注意,我删除了userpk参数并对request.user.pk进行了测试,如果您考虑它,这将无用。

答案 2 :(得分:0)

正确版本(参考Tisho的答案):

我的views.py:

@login_required                              
def lexuseditform(request,userpk):
    if Adult.objects.filter(user=request.user).exists():
        adult = Adult.objects.get(user=request.user) # load existing Adult
    else:
        adult = Adult(user=request.user) # create new Adult
    if request.method == 'POST': # If the form has been submitted...
        form = AdultForm(request.POST,instance=adult) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            redirect_url = reverse('lexusedited')
            return HttpResponseRedirect(redirect_url) # Redirect after POST
    else:
           form = AdultForm(instance=adult) # An unbound form

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