簡體   English   中英

Django將對象傳遞給另一種形式的模型

[英]Django pass object to model of another form

我已經實現了一個 Python 表單/視圖/模板,可讓您為產品配置不同的通知:

模型.py

class PNotification(models.Model):
    add = models.BooleanField(default=False, help_text='Receive messages when an engagement is 
    added')
    delete = models.BooleanField(default=False, help_text='Receive 


class Product(models.Model):

表格.py

class PNotificationForm(forms.ModelForm):
    class Meta:
        model = PNotification
        exclude = ['']


class ProductForm(forms.ModelForm):

PNotification 有自己的視圖和模板:

<h3> Edit Notifications for {{ product.name }}</h3>
    <form class="form-horizontal" method="post">{% csrf_token %}
        {% include "dojo/form_fields.html" with form=form %}
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input class="btn btn-primary" type="submit" value="Submit"/>
            </div>
        </div>
    </form>

當我調用頁面 (edit/product_id/notifications) 來編輯產品通知時, h3設置正確,因此產品被傳遞到表單/模板。

我的問題是:我需要將 PNotification 與產品相關聯。

如何將product.id傳遞給我的PNotificationForm以便我可以將其保存在那里? 該字段應該是 PNotification 的主鍵。

編輯

這是我的view.py:

def edit_product_notifications(request, pid):
    prod = Product.objects.get(pk=pid)
    logger.info('Editing product')
    if request.method == 'POST':
        pnotification = PNotificationForm(request.POST, instance=prod)
        if pnotification.is_valid():
            pnotification.save()
            logger.info('saved')
        
    else:
        pnotification = PNotificationForm()
        if pnotification.is_valid():
            pnotification.save()
            logger.info('saved')

logger.info(PNotification.objects.get(id=1).msteams)
logger.info('returning')
return render(request,
              'dojo/edit_product_notifications.html',
              {'form': pnotification,
               'product': prod
               }). 

我正在傳遞產品 ID,然后從objects.get()獲取它。

urls.py中,該視圖的路徑需要具有<int:pk> 路徑看起來像這樣edit/<int:pn_pk>/notifications

在您看來,您需要獲取kwargs ,它是 url 傳遞的參數。

在基於函數的視圖中:

def your_view_name(request, pk):
    # use pk how you want.
    PN = PNotification.objects.get(pk=pn_pk)
    return render(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM