首页 \ 问答 \ Django:使用外键保存动态表单(Django: saving dynamic forms with foreign key)

Django:使用外键保存动态表单(Django: saving dynamic forms with foreign key)

我想为我的问题寻求帮助和指导。

我有以下型号:

class myinfo(models.Model):
    name = models.CharField(max_length=30, null=True)


class mynumbers(models.Model):
    fkey = models.ForeignKey("myinfo")
    Job_Position = models.CharField(max_length=30, null=True)

mynumbers模型是通过django-dynamic-formset动态生成的。

我的表格

class info(ModelForm):
    name= forms.CharField( max_length=20)

    class Meta:
        model = APPLICANT_DATA
        fields = ('name',)

class numbers(ModelForm):
    number = forms.CharField( max_length=20)

    class Meta:
        model = APPLICANT_DATA
        fields = ('number',)

如果要保存动态表单字段,则必须在视图中执行此操作

for field in formset:
    field.save()

我的观点:

def index(request):

    aformset = formset_factory(numbers)
    formset = aformset(request.POST)
    form = info(request.POST)

    if request.method == 'POST':

        if form.is_valid():
            if formset.is_valid():
                for field in formset:
                    formset.save()

                form.save()

但是当我的动态生成的字段有一个外键( mynumbers )引发错误must be a myinfo instance时,问题就开始must be a myinfo instance 。 我如何保存mynumbers有一个myinfo密钥到myinfo的2个表单? 对我的所作所为有更好的方法吗? 先谢谢你,


I would like to seek assistance and guidance to my problem.

I have the following models:

class myinfo(models.Model):
    name = models.CharField(max_length=30, null=True)


class mynumbers(models.Model):
    fkey = models.ForeignKey("myinfo")
    Job_Position = models.CharField(max_length=30, null=True)

The mynumbers model is dynamically generated via django-dynamic-formset.

My form

class info(ModelForm):
    name= forms.CharField( max_length=20)

    class Meta:
        model = APPLICANT_DATA
        fields = ('name',)

class numbers(ModelForm):
    number = forms.CharField( max_length=20)

    class Meta:
        model = APPLICANT_DATA
        fields = ('number',)

If you want to save your dynamic form fields you have to do this in views

for field in formset:
    field.save()

My views:

def index(request):

    aformset = formset_factory(numbers)
    formset = aformset(request.POST)
    form = info(request.POST)

    if request.method == 'POST':

        if form.is_valid():
            if formset.is_valid():
                for field in formset:
                    formset.save()

                form.save()

But the problem starts when my dynamically generated field has a foreign key(mynumbers) which raises an error must be a myinfo instance. How would I save the 2 forms where mynumbers has a foriegn key to myinfo? Is there a better way to what I did? Thank you in advance,


原文:https://stackoverflow.com/questions/34837936
更新时间:2022-09-21 19:09

最满意答案

这是使用inlineformset_factory地方。 这允许您拥有父模型和许多子模型(通过外键与父模型相关)并将它们保存在一起。 有许多参数可以传递给inlineformset_factory以自定义行为(例如允许的最小和最大内联表单数,用户是否可以删除内联表单等),但是关键字如下所示。

# views.py

from django.forms.models import inlineformset_factory
from my_app.forms import numbers as NumberForm
from my_app.forms import info as InfoForm
from my_app import models

myFormset = inlineformset_factory(models.myinfo,
    models.mynumbers,
    form=NumberForm
)

def index(request):
    if request.POST:
        form = InfoForm(request.POST)
        if form.is_valid():
            info = form.save(commit=False)
            formset = myFormset(request.POST, instance=info)
            if formset.is_valid():
                info.save()
                formset.save()
                return HttpResponse('saved successfully')
    else:
        form = InfoForm()
        formset = myFormset(instance=models.myinfo())
    return render_to_response("recipes/submit.html", {
                                                    "form": form,
                                                    "formset":formset,    
                                                    }, 
                            context_instance=RequestContext(request))

请注意 :在您的问题中,您for field in formset: formset.save()键入for field in formset: formset.save() 。 formset是表单的集合,而不是字段的集合。

Formset可能很棘手,需要使用不属于常规表单的其他模板组件正确呈现模板(例如允许Django正确处理已添加/删除/移动/更改内容的management_form变量)。 绝对值得做一些教程,以便了解最佳实践,这样您就不会使用自定义实现进行故障排除。 我建议查尔斯·莱弗Charles Leifer)的这篇文章是了解基础知识的一个很好的条目。


This is where inlineformset_factory would be used. This allows you to have a parent model and a number of child models (related w/ parent via a foreignkey) and save them together. There are many arguments that can be passed to the inlineformset_factory in order to customize behavior (such as the minimum and maximum number of inline forms allowed, whether the user can delete inline forms, etc.) but the crux is shown below.

# views.py

from django.forms.models import inlineformset_factory
from my_app.forms import numbers as NumberForm
from my_app.forms import info as InfoForm
from my_app import models

myFormset = inlineformset_factory(models.myinfo,
    models.mynumbers,
    form=NumberForm
)

def index(request):
    if request.POST:
        form = InfoForm(request.POST)
        if form.is_valid():
            info = form.save(commit=False)
            formset = myFormset(request.POST, instance=info)
            if formset.is_valid():
                info.save()
                formset.save()
                return HttpResponse('saved successfully')
    else:
        form = InfoForm()
        formset = myFormset(instance=models.myinfo())
    return render_to_response("recipes/submit.html", {
                                                    "form": form,
                                                    "formset":formset,    
                                                    }, 
                            context_instance=RequestContext(request))

Please note: In your question, you typed for field in formset: formset.save(). A formset is a collection of forms, not a collection of fields.

Formsets can be tricky and require the template rendered correctly with additional template components that are not part of regular forms (such as the management_form variable that allows for Django to properly process what has been added/deleted/moved/changed). It's definitely worth doing some tutorials in order to get an idea of best practices so that you don't go down a troubleshooting rabbithole w/ your custom implementation. I suggest this post from Charles Leifer as a good entry to get acquainted with the basics.

相关问答

更多
  • 我会让自己的生活变得轻松,并使用Versionable行为 。 Specification: actAs: Versionable: versionColumn: version className: %CLASS%Version auditLog: true columns: #your columns here 如果你使用SpecificationForm作为主窗体并将RevisionForm嵌入其中,那说这应该是开箱Specificati ...
  • 我也在Django IRC上发布了这个问题,有人帮我解决了这个问题! 我最初犯了两个错误: 我在模特中加了一个'_id'。 这已经自动完成,所以我的数据库中的变量实际上被称为'movie_id_id'。 我已经删除了多余的'_id'。 以下行中的'.movie'是不必要的。 post.movie = Entry.objects.get(slug = slug).movie 正确的工作视图如下: def lets_vote(request, slug): entry = Entry.objects.get ...
  • 我假设您不想在表单上显示产品字段,因此您应该将其从表单中排除,以便验证通过: class ResourceForm(forms.ModelForm): resource = forms.MultipleChoiceField(choices=ProductResource.CHOICES, widget = forms.CheckboxSelectMultiple) class Meta: model = ProductResource exclude = [ ...
  • 您在错误的表单上执行commit = False,并且将外键设置到MN表单上,而不是模型实例。 model_instance = form_cs.save() mn_instance = form_mn.save(commit=False) mn_instance = customer_system_serial_number = model_instance mn_instance.save() return HttpResp ...
  • 如果你想在Django Admin上有这个,那么你需要使用内联模型 。 如果您计划创建自己的表单(使用ModelForms),则需要使用内联formets 。 If you want to have this on the Django Admin, then you need to use inline models. If you plan to create your own form (using ModelForms), then you need to use inline formets.
  • 你可以试试这个 if request.method == 'POST': spf = StudentPotentialForm(request.POST) if spf.is_valid(): osp = spf.save() else : #raise error student = Student.objects.get(id=student_id) scf = StudentCorrespondenceForm(request.P ...
  • 易俗。 def master_detail(request): def get_new_voucher_id(): temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct() logger.info('Voucher ID already present %s', temp_vid) if not temp_vid: ...
  • 这是使用inlineformset_factory地方。 这允许您拥有父模型和许多子模型(通过外键与父模型相关)并将它们保存在一起。 有许多参数可以传递给inlineformset_factory以自定义行为(例如允许的最小和最大内联表单数,用户是否可以删除内联表单等),但是关键字如下所示。 # views.py from django.forms.models import inlineformset_factory from my_app.forms import numbers as NumberF ...
  • 您将数据传递回studio_form : def studio_register(request): # other view code studio_form.user_id=user.id studio_form.save() 实际上,您需要将数据传递给Studios模型,以便将其保存到数据库中。 Form仅用于清理数据并临时保存,直到您访问模型以将数据保存到数据库。 所以如果你在这里建模 : from django.contrib.auth.models import Use ...
  • 该行不正确: openinghours_form.content_object = restrant 应该是这样的: openinghours = openinghours_form.save(commit = False) openinghours.establishment = restraunt openinghours.save() 您还可以使用更明确的名称: class OpeningHours(models.Model): establishment_type = models.Fo ...

相关文章

更多

最新问答

更多
  • 关于计划在cuFFT中重用(On plans reuse in cuFFT)
  • 在类实例中调用getter时如何将列表作为字符串返回(How to return a list as a string when calling a getter in a class instance)
  • 电子邮件不是使用php发送的(Email is not sending using php)
  • 使用按钮来创建/追加数组(Use button to create/append array)
  • 如何获取字符数限制,包括默认名称-Reactjs(How to get character count limitation including default name-Reactjs)
  • 为什么NSMutableDictionary不想写入文件?(Why NSMutableDictionary don't want write to file?)
  • Swift删除宽高比约束(Swift remove aspect ratio constraint)
  • 与IE7 Angularjs的兼容性(Compatibility with IE7 Angularjs)
  • oracle查看text文件内容有哪些命令
  • 使用带有flex的minHeight会创建意外的填充(Using minHeight with flex creates unexpected padding)
  • text-align / align-content不起作用(text-align / align-content doesnt work)
  • 分层数据结构设计(嵌套集)(Hierarchical Data Structure Design (Nested Sets))
  • Riak Java HTTPClientAdapter TCP CLOSE_WAIT(Riak Java HTTPClientAdapter TCP CLOSE_WAIT)
  • 如果字段不是字符串,则将SqlDataReader字段强制转换为字符串(Cast SqlDataReader field to a string if the field is not a string)
  • 莱宁根新抛出异常(leiningen new throws exception)
  • 在javascript中修复不正确的转义字符串(fixing improperly escaped string in javascript)
  • Web Audio API参数调制在Safari中无法正常工作(Web Audio API parameter modulation not working in Safari)
  • 长沙岳麓区有没有书法培训学校?
  • pro/engineer视频教程下载
  • 九游游戏中心下载的安装包为什么安装不上
  • 外键问题(foreign key issue)
  • ASP.NET动态用户控件可以保存数据问题(ASP.NET Dynamic user controls save data issue)
  • 不确定如何使用FluentValidation测试此.NET字符串(Not sure how to test this .NET string with FluentValidation)
  • 最新时间从两个型号更新(Latest time updated from two models)
  • 扭曲的自定义CancelledError(Twisted custom CancelledError)
  • jQuery动画在Firefox中不起作用(jQuery animation not working in Firefox)
  • 通过Facebook登录评论社交插件不会触发事件?(Login via Facebook comments social plugin does not trigger an event?)
  • HttpWebRequest没有发布(HttpWebRequest not posting)
  • 更改Google Maps V2中的标记颜色(Change marker color in Google Maps V2)
  • ASP.Net下拉列表不会重新显示我选择的选项(ASP.Net Dropdown List Doesn't Re-Display My Selected Option)