我創建了一個視圖,用戶可以在其配置文件中更新訂閱,但是當我去添加新用戶時,我意識到我沒有想到創建新的訂閱。所以我不得不爲:使用Django ModelForm創建新對象
models.py
class Customer_Subscription(models.Model):
user = models.ForeignKey(User)
customers = models.ManyToManyField('Customers', blank=True)
def __unicode__(self):
return (self.user)
forms.py
class CustomerSubscriptionForm(forms.ModelForm):
class Meta:
model = Customer_Subscription
fields = ['customers']
views.py
def profile(request):
if request.method == 'POST':
cust_subscription_instance = Customer_Subscription.objects.get(user=request.user.id)
customer_subscription = CustomerSubscriptionForm(request.POST, instance=cust_subscription_instance)
if customer_subscription.is_valid() and level_subscription.is_valid() and profile_form.is_valid():
customer_subscription.save(commit=True)
return HttpResponseRedirect('/profile/')
由於沒有了Customer_Subscription對象的實例查詢失敗。我已經嘗試了幾個作爲「例外」的東西,但似乎沒有任何工作,而且我不知道哪些東西接近正確。尋找一些幫助。
views.py
try:
cust_subscription_instance = Customer_Subscription.objects.get(user=request.user.id)
customer_subscription = CustomerSubscriptionForm(request.POST, instance=cust_subscription_instance)
if customer_subscription.is_valid() and level_subscription.is_valid() and profile_form.is_valid():
customer_subscription.save(commit=True)
return HttpResponseRedirect('/profile/')
except:
customer_subscription = CustomerSubscriptionForm(request.user.id, request.POST)
if customer_subscription.is_valid():
customer_subscription.save(commit=True)
level_subscription.save(commit=True)
return HttpResponseRedirect('/profile/')
謝謝。在實際中Subbing給了我一個錯誤,因爲我沒有意識到它返回了一個元組。通過聲明爲cust_subscription_instance解決,創建= Customer_Subscription.objects.get_or_create(user = request.user) – user3184033
是的,對不起,我忘了提及:/ – iskorum