0

ModelForm を保存しようとしていますが、エラーが発生します:

InternalError at /submeter/anuncio/
current transaction is aborted, commands ignored until end of transaction block

私がやっていることを説明しようと思います。

わかりました。一度に 1 つのフォームに保存する必要がある 5 つのモデルがあります。2 つのモデルで保存をテストしていますが、前述のとおり、save メソッドでエラーが発生しています。初心者として、私はタスクを達成するための最良の方法について少し迷っています。

私がやったこと:

テンプレート:

<form method="post" action="/submeter/anuncio/">{% csrf_token %}
    {{form_main}}
    {{form_bicyclead}}
    <input type="hidden" name="section" value="5" />
    <input type="submit">
</form>

Views.py:

def submit_data_entry_view(request):
    if request.method == 'GET': #first time rendering the form
    form_main      = MainForm()
    form_bicyclead = BicycleAdForm()

    return render_to_response('app_t/submit_data_entry.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead}, context_instance=RequestContext(request))

def submit_ad_view(request):
    if request.method == 'POST':
        post_values = request.POST.copy()

        post_values['user'] = request.user.username

        post_values['bicycleadtype']      = 2
        post_values['bicycleaditemkind']  = 4
        post_values['bicycleadcondition'] = 2
        post_values['city']               = 4803854  

        form_main      = MainForm(post_values)
        form_bicyclead = BicycleAdForm(post_values)

    if form_main.is_valid() and form_bicyclead.is_valid():
        form_main.save()
        #form_bicyclead.save()

        resultado = 'valid'
    else:
        resultado = 'n_valid'
    pdb.set_trace()

    return render_to_response('app_t/submit_ad.html', {'resultado': resultado}, context_instance=RequestContext(request))

Forms.py:

class MainForm(forms.ModelForm):
    class Meta:
    model = Main
    exclude = ('user', 'section')

class BicycleAdForm(forms.ModelForm):
    class Meta:
    model = BicycleAd
    exclude = ('main', 'bicycleadtype', 'bicycleaditemkind', 'bicycleadcondition', 'city')

Models.py:

class Main(models.Model):
    section             = models.ForeignKey(Section)
    user                = models.ForeignKey(User)
    title               = models.CharField(max_length=250)
    date_inserted       = models.DateTimeField(auto_now_add=True)
    date_last_update    = models.DateTimeField(auto_now=True)

    def __unicode__(self):
    return self.title

    class Meta:
    ordering = ['date_inserted']

class BicycleAd(models.Model):
    main                = models.ForeignKey(Main)
    bicycleadtype       = models.ForeignKey(BicycleAdType)
    bicycleaditemkind   = models.ForeignKey(BicycleAdItemKind) # MPTT Model
    bicycleadcondition  = models.ForeignKey(BicycleAdCondition)
    country             = models.ForeignKey(GeonamesCountry)       
    city                = models.ForeignKey(GeonamesLocal) 
    date_inserted       = models.DateTimeField(auto_now_add=True)
    date_last_update    = models.DateTimeField(auto_now=True)

    class Meta:
    ordering = ['date_inserted']  

私の質問は次のとおりです:views.pyのform_main.save()を「オーバーライド」して、モデル「セクション、ユーザー、タイトル」にあるすべてのフィールドを伝えるにはどうすればよいですか? エラーは、保存メソッドに渡されていないフィールド「セクション」と「ユーザー」が原因だと思います。この値を渡すにはどうすればよいですか?

別の質問: 私はこれを正しい方法で行っていますか、それとも私が達成しようとしていることを達成するためのより簡単で簡単な方法はありますか?

よろしくお願いします

4

2 に答える 2

2

モデルフォームを次のように変更します。

class MainForm(forms.ModelForm):
    def __init__(self, *args, **kw):
        self.user = kw.pop('user')
        self.section = kw.pop('section')
        super(MainForm).__init__(*args, **kw)

    class Meta:
        model = Main
        exclude = ('user', 'section')

    def save(self, *args, **kw):
        instance = super(MainForm).save(commit=False)
        instance.user = self.user
        instance.section = self.section
        instance.save()
        return instance

次に、ビューでフォームのインスタンスを作成するときに、userを渡す必要があります。section

form_main = MainForm(request.POST or None, user=request.user, section=section)
于 2013-01-04T16:25:45.870 に答える
2

私のアプローチは、このコードを置き換えることです。

def submit_ad_view(request):
    if request.method == 'POST':
        post_values = request.POST.copy()

        post_values['user'] = request.user.username

        post_values['bicycleadtype']      = 2
        post_values['bicycleaditemkind']  = 4
        post_values['bicycleadcondition'] = 2
        post_values['city']               = 4803854  

        form_main      = MainForm(post_values)

に:

def submit_ad_view(request):
    if request.method == 'POST':

        model = Main()  #if model exists get it!
                        #Notice, Main is the name of your model.

        model.user = request.user.username
        ...
        model.bicycleaditemkind = 4
        ...        
        form_main      = MainForm(request.POST, instance = model )

モデルdjangodocからのフォームの作成について詳しく知ることができます。

于 2013-01-04T16:30:43.053 に答える