Z
Z
zelsky2016-06-19 18:04:43
Django
zelsky, 2016-06-19 18:04:43

How to get an object from another model in a form?

Given two models, form and view. The task is as follows, the user writes an id (article) in the form, shows the similarity from the datalist, selects the id, writes the quantity and sends it. The question in the next form does not pass before saving because of its check, because in value is a string type, and already inside the check if the form is valid then . So here's how to skip the data in validation so that the data can be saved. Thank you.
new_form.good = form['good'].value()

class Sale(models.Model):
    good = models.ForeignKey(Good)
    seller = models.ForeignKey(User)
    time_selling = models.DateField(auto_now_add=True, editable=False)
class Good(models.Model):
    article = models.CharField('Артикул товару', max_length=100)
    name = models.CharField('Назва товару', max_length=100)
    count = models.PositiveSmallIntegerField(default=1)

Forms.pi
from django import forms
from core.models import Sale
from djangoformsetjs.utils import formset_media_js


class SaleForm(forms.ModelForm):
    good = forms.CharField(widget=forms.TextInput(attrs={'list': 'goods'}))
    class Meta:
        model = Sale
        fields = ('good', 'count')
        js = formset_media_js + ()

and I twist
@login_required
def index(request):
    "TODO"
    "Check for count can`t be lower than 0"
        shop = Shop.objects.get(owner=request.user.parent)
        goods = Good.objects.filter(shop=shop, count__gt=0)
        saleformset = formset_factory(SaleForm)
        if request.method == 'POST':
            formset = saleformset(request.POST)
            for form in formset.forms:
                if form.is_valid():
                    new_form = form.save(commit=False)
                    new_form.seller = request.user
                    new_form.good = form['good'].value()
                    new_form.save()
                    good_object = Good.objects.get(pk=new_form.good.pk)
                    own_count = good_object.count - new_form.count
                    good_object = Good.objects.filter(pk=new_form.good.pk).\
                        update(count=own_count)
            return render(request, 'all_ok.html', {'data': 'lil'})
        else:
            formset = saleformset()


        return render(request, 'base_vendor.html',
                      {'context': goods, 'formset': formset})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question