2017-10-18 43 views
0

這已經超過7小時沒有成功。現在我不知道爲什麼。Django:無法從選項菜單中預先選擇開機自檢後

我有兩種形式,this screenshot應該給我找的流動非常好的跡象。

因此,基本上,用戶從BottleForm的下拉菜單中現有的項目之一(標示的截圖爲「1」)要麼,或者他選擇單擊Add按鈕,打開另一種形式BrandForm的模式(在截圖中標記爲「2」),這應該讓他填補一個新的品牌名稱。

我想要的是,當一個新的品牌名稱在BrandForm提交併重新加載頁面,該品牌已經在下拉菜單中預選。我讀過無數個帖子,但沒有關於在現場工作中設置initial的建議答案。

爲什麼它不起作用?

views.py(add_brand對於BrandForm提交名稱)

# Add brand form 
     elif 'add_brand' in request.POST: 
      brand_name = request.POST['name'] # this is the brand name we submitted 
      context['form'] = BottleForm(initial={'brand': brand_name}) 
      context['form2'] = BrandForm(request.POST) 
      the_biz = Business.objects.filter(owner=user.id).first() 


      if context['form2'].is_valid(): 
       print("brand for valid!") 
       brand = context['form2'].save(commit=False) 
       brand.business = the_biz 
       brand.save() 
       return render(request, template_name="index.pug", context=context) 

bottle_form.pug:

//- Create New Brand Modal 
div.modal.fade.create-new-brand(tabindex="-1" role="dialog") 
    div.modal-dialog.modal-sm(role="document") 
     div.modal-content 
      div.modal-header 
       H3 Enter the Brand's name here: 
      div.modal-body 
       form.form-horizontal(method="post" action=".") 
        | {% csrf_token %} 
        | {{ form2.as_p }} 
        hr 
        btn.btn.btn-default(type="button" data-dismiss="modal") Close 
        input.btn.btn-primary(type="submit" value="submit")(name="add_brand") Add Brand 

models.py:

class Brand(models.Model): 
    name = models.CharField(max_length=150, blank=False) 
    business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name="brands") 

    permissions = (
     ('view_brand', 'View the brand'), 
     ('del_brand', 'Can delete a brand'), 
     ('change_brand', 'Can change a brand\'s name'), 
     ('create_brand', 'Can create a brand'), 
    ) 

    def __str__(self): 
     return self.name 


class Bottle(models.Model): 
    name = models.CharField(max_length=150, blank=False, default="") 
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="bottles") 
    vintage = models.IntegerField('vintage', choices=YEAR_CHOICES, default=datetime.datetime.now().year) 
    capacity = models.IntegerField(default=750, 
            validators=[MaxValueValidator(2000, message="Must be less than 2000") 
            ,MinValueValidator(50, message="Must be more than 50")]) 

    slug = models.SlugField(max_length=550, default="") 

    @property 
    def age(self): 
     this_year = datetime.datetime.now().year 
     return this_year - self.vintage 


    permissions = (
     ('view_bottle', 'View the bottle'), 
     ('del_bottle', 'Can delete a bottle'), 
     ('change_bottle', 'Can change a bottle\'s name'), 
     ('create_bottle', 'Can create a bottle'), 
    ) 

    def __str__(self): 
     return self.name + " " + self.brand.name + " " + str(self.capacity) + " " + str(self.vintage) 


    def save(self, *args, **kwargs): 
     # if there's no slug, add it: 
     if self.slug == "": 
      self.slug = str(slugify(str(self.name)) + slugify(str(self.brand)) + str(self.vintage) + str(self.capacity)) 
     super(Bottle, self).save(*args, **kwargs) 

如果需要更多細節,請告訴我。這真讓我抓狂。

BTW:我不知道Django是如何加載選項的下拉菜單。

回答

2

它看起來像你的Brand模型具有brand字段作爲一個ForeignKey。這意味着,當你傳遞brand_name作爲初始值brandBottleForm,它不知道該怎麼辦,因爲它期待一個ForeignKey,而不是一個字符串。在這種情況下,當你添加一個新的brand_name,你必須首先創建並保存Brand模型實例,然後讓你剛剛保存的實例,然後把它傳遞給你的initial參數是你應該做的是。

下面是一些代碼,從開始:

elif 'add_brand' in request.POST: 
    brand_name = request.POST['name'] # this is the brand name we submitted 
    b = Brand(name=brand_name, business=...) # you will have to figure out what Business object to set considering that is a ForeignKey. 
               # Alternatively, you can define a default for your `business` field, 
               # e.g. default=1, where 1 refers to the pk of that business object 
    b.save() 
    new_brand = Brand.objects.last() # grabs the last Brand object that was saved 
    context['form'] = BottleForm(initial={'brand': new_brand}) 
    ... # rest of the magic here 
相關問題