【问题标题】:Updating A Profile Model Object in Django在 Django 中更新配置文件模型对象
【发布时间】:2018-08-18 11:41:11
【问题描述】:

我进行了多次搜索,试图找出我的问题或我需要在这里做什么。我是 Django 新手,还没有完全掌握允许用户通过表单更改数据库的模型对象的窍门。

每当用户使用以下代码注册时,我的代码正在创建一个默认的“个人资料”数据库:

模型.py:

    class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    state = models.CharField(max_length= 20, choices=STATE_CHOICES,default='N/A',)
    city = models.CharField(max_length=30,null=True, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    Primary_Campaign_Interest = models.CharField(max_length=30, choices=Interest_choices, null='000')
    Secondary_Campaign_Interest = models.CharField(max_length=30, choices=Interest_choices, null='000')

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

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

这会在我的数据库中生成一个空表,我希望用户随后能够通过表单对其进行编辑。但是,我只希望用户能够编辑州和城市字段以及一些用户字段,而不是用户名。

forms.py

class ProfileForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = ('state','city')

views.py

@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        user_form = SignUpForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, _('Your profile was successfully updated!'))
            return redirect('home')
        else:
            return render(request, 'Users/profile.html')
    else:
        user_form = SignUpForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'accounts/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

accounts/profile.html

    <form method="post">{% csrf_token %}
  <h3>First name:</h3>
  {{ user_form.first_name }}<br>
  <h3>Last name:</h3>
  {{ user_form.last_name }}<br>
  <h3>Email Address:</h3>
  {{ user_form.email }}<br>
  <h3>State:</h3>
  {{ profile_form.state }}<br>
  <h3>City:</h3>
  {{ profile_form.city}}<br>
  <h3>Primary Campaign Interest:</h3>
  {{ profile_form.Primary_Campaign_Interest}}<br>
  <h3>Secondary Campaign Interest:</h3>
  {{profile_form.Secondary_Campaign_Interest}}<br>
  <button type="submit">Save changes</button>
</form>

我相信我的问题是,每当用户提交这些表单时,这些表单都无效并返回页面 Users/Profile.html。关于使表格有效的任何建议?还是编辑数据库中已有对象的更好方法?

感谢您的帮助。

【问题讨论】:

  • 您是否遇到任何错误?另外我认为return render 语句应该在最后的else 语句中,您可能希望将user_formprofile_form 作为上下文或参数传递给它,只是为了稍微清理一下

标签: python django object models


【解决方案1】:

我个人认为你应该把你的任务分成两个任务。首先,您创建一个新用户(您的注册表单),将其保存到数据库(任务 1)。如果保存成功,那么您应该能够使用更新视图从数据库中查询该用户,然后对其进行更新并保存(任务 2)。

【讨论】:

    【解决方案2】:

    不久前想通了。我刚刚创建了一个新表单,将其传递到视图中,然后将初始值设置为模型对象中当前的值。 同样重要的是要注意用户实例的使用。

    @login_required
    def signuptwo(request):
        if request.method == 'POST':
            form = EditProfileForm(request.POST, instance=request.user.profile)
            profile = form.save(commit=False)
            profile.user = request.user
            if form.is_valid():
                form.save()
                return redirect('profile')
        else:
            user_profile = Profile.objects.get(user=request.user)
            form = EditProfileForm(initial={'state':user_profile.state,'city':user_profile.city,'birth_date':user_profile.birth_date,'Primary_Campaign_Interest':user_profile.Primary_Campaign_Interest,'Secondary_Campaign_Interest':user_profile.Secondary_Campaign_Interest})
            return render(request, 'Accounts/Editprofile.html', {'form':form})
    

    感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 2017-05-05
      • 2022-01-02
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多