无法从Django ModelForm保存到数据库

时间:2017-10-18 11:59:35

标签: python django django-forms django-views

没有错误,但表单不保存到数据库。否则,可以从django admin。

添加数据

网址和重定向也很有效,我可以打开表单,编辑/放置数据并点击提交,但数据库没有反映。

models.py

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

class RPAS(models.Model):
    user = models.OneToOneField(User)
    manufacturer = models.CharField(max_length = 100, default = '')
    model_name = models.CharField(max_length = 100, default = '')
    serial_no = models.CharField(max_length = 50, default='')
    reg_mark = models.CharField(max_length = 50, default='')

    def __str__(self):
        return self.user.rpas.manufacturer

# RPAS.profile = property(lambda u: RPAS.objects.get_or_create(user=u)[0])

def edit_rpas_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = RPAS(user=kwargs['instance'])

post_save.connect(edit_rpas_profile, sender=User)

views.py

from .forms import RPASForm
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied

def edit_rpas(request):
        if request.user.is_authenticated():
            if request.method == "POST":
                form = RPASForm(request.POST,instance=request.user)
                if form.is_valid():
                    form.save(commit=False)
                    return redirect ('/account/rpas/')

            else:
                form = RPASForm(instance=request.user)
                args = {'form': form}
                return render(request, "accounts/edit_rpas.html", args)
        else:
            raise PermissionDenied

forms.py

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

from django.forms import ModelForm
from accounts.models import RPAS

class RPASForm(ModelForm):
    class Meta:
        model = RPAS
        fields = (
        'manufacturer',
        'model_name',
        'serial_no'
        )

模板

<form action="." method="POST" class="padding">
            {% csrf_token %}

            {{ form.as_p }}

            <input type="submit" value="Submit">

</form>

最后这是我的admin.py

from .models import RPAS
class RpasAdmin(admin.ModelAdmin):
    list_display = ('manufacturer','model_name','reg_mark','serial_no')

    def user_info(self, obj):
        return obj.description

admin.site.register(RPAS, RpasAdmin)

1 个答案:

答案 0 :(得分:2)

您正在使用commit=False保存,因此实​​例永远不会保存到数据库中。去掉它。您还应该传递RPAS个实例,而不是User,因为该表单适用于RPAS模型。

if request.method == "POST":
    form = RPASForm(request.POST,instance=request.user.rpas)
    if form.is_valid():
        form.save()
        return redirect ('/account/rpas/')
else:
    form = RPASForm(instance=request.user.rpas)

如果要在保存之前编辑对象,则只需要commit=False,例如设置user字段。在这种情况下,您不需要这样做,因为user字段已设置。

if form.is_valid():
    instance = form.save(commit=False)
    instance.user = request.user
    instance.save()
    return redirect ('/account/rpas/')