相當好奇的問題:我的模態完美工作,直到將包含它的模板與CreateView關聯!因此,例如如果我將BrandCreateView
中的template_name
更改爲new_brand_form1.html
,new_brand_form2.html
將在模式中完美加載。但就目前而言,當我點擊觸發模式的按鈕時,就可以使用這個按鈕。Django CreateView會自動啓動引導模式
views.py
:
class BrandCreateView(SuccessMessageMixin ,generic.edit.CreateView):
template_name = 'new_brand_form2.html'
model = Brand
fields = ['name']
def get_success_url(self):
current_business = Business.objects.filter(owner=self.request.user).first()
current_business.brands.add(self.object.pk)
return reverse_lazy('index', kwargs={'pk': self.object.pk})
# pre assign-current business to the business field
def get_initial(self):
initial = super().get_initial()
initial['business'] = Business.objects.filter(owner=self.request.user).first()
self.business_name = initial['business']
return initial
def form_valid(self, form):
form.instance.user = self.request
form.instance.business = self.business_name
try:
return super(BrandCreateView, self).form_valid(form)
except IntegrityError:
form.add_error('name' ,'You already have a brand by that name')
return self.form_invalid(form)
new_brand_form2.html
:
<div class="modal fade" tabindex="-1" role="dialog" id="createbrand">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
{{ form.as_p }}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
編輯:
也許這是問題嗎?觸發模式的按鈕顯然指向與urls.py
(名爲'createbrand`)中的CreateView相關聯的URL,也許它正在進入一個無止境的循環......?
這裏的觸發模式
<button class="btn btn-default btn-sm" type="button" data-toggle="modal" href="{% url "createbrand" %}" data-target="#createbrand">
<span class="glyphiconglyphicon-plus">Add New</span>
</button>
感謝。同樣的問題。我照原樣複製你的代碼,刪除評論。當我訪問實際的'CreateView' URL(顯示錯誤,成功重定向,保存模型)時,它正在工作,但是在調用模式時它根本不顯示,所以獲得與以前相同的屏幕。 – zerohedge
順便說一下,模式*是*在頁面源中「加載」。當我按下按鈕時,它的屬性也在改變。 [這是一個截圖](https://imgur.com/a/eetBF)。 – zerohedge
我可以100%確認模態被調用。如果我將數據目標從'#createbrand'更改爲'#justastring',那麼當我單擊按鈕時絕對沒有任何反應,但是如果它被正確設置爲'#createbrand',那麼屏幕會變暗,但模態永不會實際上顯示出來(即使它的屬性顯示在源文件中)。我現在非常想要做什麼。 [這是我的完整頁面源代碼](https://pastebin.com/AgvrecH7)。 – zerohedge