获得与表单验证无关的错误

时间:2017-01-28 05:44:48

标签: django django-models django-forms

我正在尝试将之前网站的id(brand_id)注入表单,因为我尝试在DB上创建的对象取决于该foreignkey关系。这是代码

from brand.models import Brand
from .models import Campaign
from .forms import CampaignForm
# Create your views here.

def campaign_create(request):
   previous_website = request.META['HTTP_REFERER']
   brand_id = int(previous_website.rsplit('/', 1)[-1])
   print(brand_id)
   brand_object = Brand.objects.get(id=brand_id)

   # if not request.user.is_staff or not request.user.is_superuser:
   #     raise Http404

   title = "Create Campaign"
   form = CampaignForm(request.POST or None)

    # check whether it's valid:

   if form.is_valid(): #Checking that form is valid
        instance = form.save(commit=False) # saving the form as an instance object
        instance.user = request.user
        instance.brand = brand_object #adding the brand object
        instance.save() # saving in the database

        # redirect to a new URL:

        return HttpResponseRedirect(instance.get_absolute_url())
     context = {
    "form": form,
    "title": title,
    }

   return render(request, "campaign_form.html", context)

在代码之外(在shell中),这完美无缺,问题是当我尝试提交代码时,虽然我得到正确的ID号(在日志中打印正确的值)并且我得到了正确的brand_object,我是得到一个ValueError

/ dashboard / campaign / create /的ValueError 对于带有基数为10的int(),文字无效:''

因为元值在提交表单之前更改为当前网站(new previous_website现在是当前网站)。我怎样才能在变化之前获取META值,或者我可以使用哪些其他方法来获取此对象创建所依赖的品牌对象而不动态更改?

我的流程是:

  • 创建品牌 - >本地主机:/仪表板/品牌/创建
  • 品牌创建后重定向到该品牌 - >本地主机:/仪表板/品牌/细节/(brand_id)
  • 创建广告系列(与品牌相关联)localhost:/ dashboard / campaign / create

品牌和广告系列是作为ForeignKey连接的应用程序(一个品牌可以有多个活动但一个广告系列不能拥有多个品牌)

1 个答案:

答案 0 :(得分:0)

您可以将brand_id放在campaign_create的网址

url(r'^dashboard/campaign/create/(?P<brand_id>[0-9]+)/', views.campaign_create),

并在视图中使用get_object_or_404函数:

def campaign_create(request, brand_id):
    brand_object = get_object_or_404(Brand, pk=brand_id)
    # ...