3

forms.py

class KomForm(forms.ModelForm):
    class Meta:
        model = Kom
        fields = ('company', 'title',)

models.py

class Company(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title


class Kom(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

views.py

def kommpred_new(request):
    if request.method == "POST":
        user = request.user if request.user.is_authenticated() else None
        form = KommpredForm(request.POST)
        if form.is_valid():
            kp = form.save(commit=False)
            kp.author = request.user
            kp.company=forms.ModelChoiceField(queryset=Company.objects.filter(author_id = self.user.id))
            kp.published_date = timezone.now()
            kp.save()
            return redirect('kommpred_detail', pk=kp.pk)
    else:
        form = KommpredForm()
    return render (request, 'by/kommpred_new.html', {'form': form})

I'm trying to implement a user-choice when creating a new object through a form field ModelChoiceField only those of which he is. So far, the method of trial and error, I can not do it. I was advised this:

class KomForm (forms.ModelForm):
    class Meta:
        model = Kom
        fields = ( 'company', 'title',)

    def __init __ (self, * args, ** kwargs):
        # Call the constructor form and maintain user
        super (KomForm, self) .__ init __ (* args, ** kwargs)
        if 'user' in kwargs and kwargs [ 'user'] is not None:
            user = kwargs.pop ( 'user')
            qs = Company.objects.filter (author__id = user.id)
            self.fields [ 'company']. queryset = qs

def your_view (request):
    user = request.user if request.user.is_authenticated () else None
    form = KomForm (user = user)
    return render ( 'template.html' { 'form': form})

But still I do not go out ...

how transfer in the field ModelChoiceField only those objects, the author of which is the object of creating a company user?

Evans Murithi
  • 3,197
  • 1
  • 21
  • 26
  • Your question is a bit confusing, is it possible to clarify a bit more what exactly you are trying to do? – Hybrid Nov 28 '16 at 17:27
  • The user first creates, for example, two companies. Companies in the database there are countless. The user then creates Kom object associated with the object of the Company. In the form of object creation whom I would like to show the user the choice of companies created only by that user. – Алексей Nov 28 '16 at 17:41

1 Answers1

1

I'm not sure I understand perfectly, however, it looks like you are looking for the user argument in the form, but not passing it from the view.

First I'd change in the view

form = KommpredForm(request.POST)

to

form = KommpredForm(request.POST, user=user)

and inside the form, put the super after you pop off the user from the kwargs. KomForm won't be expecting the user keyword, so pop it off before calling super.

def __init __ (self, * args, ** kwargs):
    # Call the constructor form and maintain user

    if 'user' in kwargs and kwargs [ 'user'] is not None:
        user = kwargs.pop ( 'user')
        qs = Company.objects.filter (author__id = user.id)
    else:
        qs = .... what you want when no user was passed in ...

    super (KomForm, self) .__ init __ (* args, ** kwargs)
    self.fields [ 'company']. queryset = qs

Give that a try and post back with result.

AMG
  • 1,606
  • 1
  • 14
  • 25
  • 'UnboundLocalError at /by/kp/new/ local variable 'qs' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/by/kp/new/ Django Version: 1.10.3 Exception Type: UnboundLocalError Exception Value: local variable 'qs' referenced before assignment Exception Location: C:\Users\АРС\proba\by\forms.py in __init__, line 42' – Алексей Nov 29 '16 at 05:16
  • Try self.user= and self.qs= – AMG Nov 29 '16 at 11:00
  • see http://stackoverflow.com/a/14094400/4872140 for a quick note on when to use self. – AMG Nov 29 '16 at 13:43
  • what do you want the company field to have if there is no user? Populate qs with that in an else branch and keep the variables local to the init (don't include the self.) – AMG Nov 29 '16 at 13:46
  • Many thanks for your help! Fortunately, I was wrong to apply your advice the first time. Through this I have learned a lot of new and gradually throughout understand. Good luck to you, my good man. – Алексей Dec 01 '16 at 04:40