2014-02-09 105 views
0

我創建了一個視圖,用戶可以在其配置文件中更新訂閱,但是當我去添加新用戶時,我意識到我沒有想到創建新的訂閱。所以我不得不爲:使用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/') 

回答

0

您可以使用get_or_create;

Customer_Subscription.objects.get_or_create(user=request.user) 

創建Customer_Subscription對象如果它不存在。

+0

謝謝。在實際中Subbing給了我一個錯誤,因爲我沒有意識到它返回了一個元組。通過聲明爲cust_subscription_instance解決,創建= Customer_Subscription.objects.get_or_create(user = request.user) – user3184033

+0

是的,對不起,我忘了提及:/ – iskorum

0

一般情況下,使用DoesNotExists檢查得到的失敗。只用它包裹獲得電話。

try: 
    cust_subscription_instance = Customer_Subscription.objects.get(user=request.user.id) 
except Customer_Subscription.DoesNotExists: 
    cust_subscription_instance = None 
0

views.py

class ViewSuccess(TemplateView): 
    template_name = 'frontend/view_success.html' 

class CreateCustomerSubscription(UpdateView): 
    template_name = 'frontend/create_customer_subscription.html' 
    success_url = 'frontend:view_success' 

    def get_success_url(self): 
     return reverse('frontend:view_success') 

    def get_object(self, queryset=None): 
     try: 
      return self.request.user.customersubscription 
     except CustomerSubscription.DoesNotExist: 
      return CustomerSubscription.objects.create(user=self.request.user) 


    def get_form_class(self): 
     class _Form(forms.ModelForm): 
      class Meta: 
       model = CustomerSubscription 
       fields = ['customers'] 

     return _Form 

    def form_valid(self, form): 
     self.object = form.save(commit=False) 

     self.object.user = self.request.user    
     self.object.save() 

     form.save_m2m() 

     return super(ModelFormMixin, self).form_valid(form) 

    @method_decorator(login_required) 
    def dispatch(self, request, *args, **kwargs): 
     return super(CreateCustomerSubscription, self).dispatch(request, *args, **kwargs) 

models.py

class CustomerSubscription(models.Model): 
    user = models.OneToOneField(User) 
    customers = models.ManyToManyField('Customer', blank=True) 

    def __unicode__(self): 
     return self.user.username 

class Customer(models.Model): 
    name = models.CharField(max_length=255) 

urls.py

urlpatterns = patterns('', 
    url(r'^create/$', CreateCustomerSubscription.as_view(), name='create_customer_subscription'), 
    url(r'^success/$', ViewSuccess.as_view(), name="view_success") 
) 

和create_customer_subscription.html

{% extends 'base.html' %} 
{% block content_main %} 
    <form method="post"> 
     {% csrf_token %} 
     {{ form }} 
     <input type="submit"/> 
    </form> 
{% endblock %} 
相關問題