如何在OneToOneField中保存用户数据Django的?

时间:2017-10-31 04:31:44

标签: python django python-2.7 django-1.11

我有两个模型(UserProfile)。在Profile模型中,您可以看到我有idx字段用于排序。在我的项目中,我显示了配置文件列表,管理员可以通过拖放对它们进行排序。为什么我使用idx。此字段也是不可见的,管理员不会手动更改其值。

问题:如何按个人资料ID修改用户数据。正如我之前所说,我显示了个人资料列表。现在我有编辑表单,我按个人资料ID显示用户数据。当我尝试在更改后提交表单时出现问题。

models.py:

# -*- coding: utf-8 -*-

from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    idx = models.IntegerField(verbose_name='Field for sorting, default=0, blank=True,)

    class Meta:
        ordering = ['idx', 'pk']
        db_table = 'user_profile'


@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

@receiver(post_delete, sender=Profile)
def delete_user(sender, instance=None, **kwargs):
    try:
        instance.user
    except User.DoesNotExist:
        pass
    else:
        instance.user.delete() 

forms.py:

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

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = '__all__'

views.py:

class UserEditView(UpdateView):
    template_name = 'users/edit_user.html'
    form_class = UserForm
    model = User

    def get(self, request, *args, **kwargs):
        data = dict()
        profile = Profile.objects.get(pk=self.kwargs['pk'])
        user_edit_form = UserForm(instance=profile.user)
        context = {
            'profile': profile,
            'user_edit_form': user_edit_form
        }
        data['html_user_edit_form'] = render_to_string(
            'users/edit_user.html', context, request=request
        )
        return JsonResponse(data)

    def form_valid(self, form):
        form.save()
        data = dict()
        data['form_is_valid'] = True
        context = {'users': User.objects.all()}
        data['html_users'] = render_to_string('users/users.html', context)
        return JsonResponse(data)

错误:

LevelName: WARNING | Module: base | Process: 662 | Thread: 123145371320320 | Message: Not Found: /user/31/edit/
LevelName: WARNING | Module: basehttp | Process: 662 | Thread: 123145371320320 | Message: "POST /user/31/edit/ HTTP/1.1" 404 1800

1 个答案:

答案 0 :(得分:0)

最后我发现了自己的错误。 从url我获取配置文件的id,然后在模板中我需要发送用户的id。

我只需添加context = {'user': profile.user,},然后使用模板user.id代替profile.id