使用Django ModelForm创建新对象

时间:2014-02-09 00:02:24

标签: django forms model

我创建了一个视图,用户可以在其中更新其配置文件中的订阅,但是当我去添加新用户时,我意识到我没有想到创建新订阅。所以我拥有的是:

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/')

3 个答案:

答案 0 :(得分:1)

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 %}

答案 1 :(得分:0)

通常,使用DoesNotExists检查get failure。用它包裹get get。

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

答案 2 :(得分:0)

您可以使用get_or_create;

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

创建Customer_Subscription对象(如果它不存在)。