How to filter queryset in django inline form?How to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Filtering for empty or NULL names in a querysetDoes Django scale?Saving form data rewrites the same rowdifferentiate null=True, blank=True in djangorelated name in parent model in django if inherited in other modelHow to define Mode with generic ForeignKey in DjangoDjango Model Issue In Multilevel Inheritance.How to check if Django Signal works?
Can a Gentile theist be saved?
How to check participants in at events?
How can a jailer prevent the Forge Cleric's Artisan's Blessing from being used?
I2C signal and power over long range (10meter cable)
Can a malicious addon access internet history and such in chrome/firefox?
Bob has never been a M before
node command while defining a coordinate in TikZ
Can I rely on these GitHub repository files?
Books on the History of math research at European universities
Lifted its hind leg on or lifted its hind leg towards?
Why isn't KTEX's runway designation 10/28 instead of 9/27?
Science Fiction story where a man invents a machine that can help him watch history unfold
Are Warlocks Arcane or Divine?
What will be the benefits of Brexit?
Can the harmonic series explain the origin of the major scale?
Adding empty element to declared container without declaring type of element
What if somebody invests in my application?
Simple recursive Sudoku solver
Simple image editor tool to draw a simple box/rectangle in an existing image
Is there enough fresh water in the world to eradicate the drinking water crisis?
Partial sums of primes
My boss asked me to take a one-day class, then signs it up as a day off
Superhero words!
What was required to accept "troll"?
How to filter queryset in django inline form?
How to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Filtering for empty or NULL names in a querysetDoes Django scale?Saving form data rewrites the same rowdifferentiate null=True, blank=True in djangorelated name in parent model in django if inherited in other modelHow to define Mode with generic ForeignKey in DjangoDjango Model Issue In Multilevel Inheritance.How to check if Django Signal works?
I want to filter certain modelfield in my inlineform to specific user and company.
But was unable to do in django inline formset.
This are my models:
class Purchase(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True)
party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger')
purchase = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger')
total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) purchases
class Stock_total(models.Model):
purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal')
stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock')
quantity_p = models.PositiveIntegerField()
rate_p = models.DecimalField(max_digits=10,decimal_places=2)
grand_total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)
My views:
class Purchase_createview(ProductExistsRequiredMixin,LoginRequiredMixin,CreateView):
form_class = Purchase_form
template_name = 'stockkeeping/purchase/purchase_form.html'
def get_context_data(self, **kwargs):
context = super(Purchase_createview, self).get_context_data(**kwargs)
context['profile_details'] = Profile.objects.all()
company_details = get_object_or_404(Company, pk=self.kwargs['pk'])
context['company_details'] = company_details
if self.request.POST:
context['stocks'] = Purchase_formSet(self.request.POST)
else:
context['stocks'] = Purchase_formSet()
return context
def form_valid(self, form):
form.instance.user = self.request.user
c = Company.objects.get(pk=self.kwargs['pk'])
form.instance.company = c
context = self.get_context_data()
stocks = context['stocks']
with transaction.atomic():
self.object = form.save()
if stocks.is_valid():
stocks.instance = self.object
stocks.save()
return super(Purchase_createview, self).form_valid(form)
In my forms I have tried this:
class Stock_Totalform(forms.ModelForm):
class Meta:
model = Stock_Total
fields = ('stockitem', 'Quantity_p', 'rate_p', 'Disc_p', 'Total_p')
def __init__(self, *args, **kwargs):
self.User = kwargs.pop('purchases.User', None)
self.Company = kwargs.pop('purchases.Company', None)
super(Stock_Totalform, self).__init__(*args, **kwargs)
self.fields['stockitem'].queryset = Stockdata.objects.filter(User = self.User, Company= self.Company)
self.fields['stockitem'].widget.attrs = 'class': 'form-control select2',
self.fields['Quantity_p'].widget.attrs = 'class': 'form-control',
self.fields['rate_p'].widget.attrs = 'class': 'form-control',
self.fields['Total_p'].widget.attrs = 'class': 'form-control',
Purchase_formSet = inlineformset_factory(Purchase, Stock_Total,
form=Stock_Totalform, extra=6)
But the filtering of queryset is not showing any item if it is present under specific User and also under specific company.
Can anyone help me with the exact query that will filter objects under specific user and company.
Thank you
django django-models django-forms django-views
add a comment |
I want to filter certain modelfield in my inlineform to specific user and company.
But was unable to do in django inline formset.
This are my models:
class Purchase(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True)
party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger')
purchase = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger')
total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) purchases
class Stock_total(models.Model):
purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal')
stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock')
quantity_p = models.PositiveIntegerField()
rate_p = models.DecimalField(max_digits=10,decimal_places=2)
grand_total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)
My views:
class Purchase_createview(ProductExistsRequiredMixin,LoginRequiredMixin,CreateView):
form_class = Purchase_form
template_name = 'stockkeeping/purchase/purchase_form.html'
def get_context_data(self, **kwargs):
context = super(Purchase_createview, self).get_context_data(**kwargs)
context['profile_details'] = Profile.objects.all()
company_details = get_object_or_404(Company, pk=self.kwargs['pk'])
context['company_details'] = company_details
if self.request.POST:
context['stocks'] = Purchase_formSet(self.request.POST)
else:
context['stocks'] = Purchase_formSet()
return context
def form_valid(self, form):
form.instance.user = self.request.user
c = Company.objects.get(pk=self.kwargs['pk'])
form.instance.company = c
context = self.get_context_data()
stocks = context['stocks']
with transaction.atomic():
self.object = form.save()
if stocks.is_valid():
stocks.instance = self.object
stocks.save()
return super(Purchase_createview, self).form_valid(form)
In my forms I have tried this:
class Stock_Totalform(forms.ModelForm):
class Meta:
model = Stock_Total
fields = ('stockitem', 'Quantity_p', 'rate_p', 'Disc_p', 'Total_p')
def __init__(self, *args, **kwargs):
self.User = kwargs.pop('purchases.User', None)
self.Company = kwargs.pop('purchases.Company', None)
super(Stock_Totalform, self).__init__(*args, **kwargs)
self.fields['stockitem'].queryset = Stockdata.objects.filter(User = self.User, Company= self.Company)
self.fields['stockitem'].widget.attrs = 'class': 'form-control select2',
self.fields['Quantity_p'].widget.attrs = 'class': 'form-control',
self.fields['rate_p'].widget.attrs = 'class': 'form-control',
self.fields['Total_p'].widget.attrs = 'class': 'form-control',
Purchase_formSet = inlineformset_factory(Purchase, Stock_Total,
form=Stock_Totalform, extra=6)
But the filtering of queryset is not showing any item if it is present under specific User and also under specific company.
Can anyone help me with the exact query that will filter objects under specific user and company.
Thank you
django django-models django-forms django-views
add a comment |
I want to filter certain modelfield in my inlineform to specific user and company.
But was unable to do in django inline formset.
This are my models:
class Purchase(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True)
party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger')
purchase = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger')
total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) purchases
class Stock_total(models.Model):
purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal')
stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock')
quantity_p = models.PositiveIntegerField()
rate_p = models.DecimalField(max_digits=10,decimal_places=2)
grand_total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)
My views:
class Purchase_createview(ProductExistsRequiredMixin,LoginRequiredMixin,CreateView):
form_class = Purchase_form
template_name = 'stockkeeping/purchase/purchase_form.html'
def get_context_data(self, **kwargs):
context = super(Purchase_createview, self).get_context_data(**kwargs)
context['profile_details'] = Profile.objects.all()
company_details = get_object_or_404(Company, pk=self.kwargs['pk'])
context['company_details'] = company_details
if self.request.POST:
context['stocks'] = Purchase_formSet(self.request.POST)
else:
context['stocks'] = Purchase_formSet()
return context
def form_valid(self, form):
form.instance.user = self.request.user
c = Company.objects.get(pk=self.kwargs['pk'])
form.instance.company = c
context = self.get_context_data()
stocks = context['stocks']
with transaction.atomic():
self.object = form.save()
if stocks.is_valid():
stocks.instance = self.object
stocks.save()
return super(Purchase_createview, self).form_valid(form)
In my forms I have tried this:
class Stock_Totalform(forms.ModelForm):
class Meta:
model = Stock_Total
fields = ('stockitem', 'Quantity_p', 'rate_p', 'Disc_p', 'Total_p')
def __init__(self, *args, **kwargs):
self.User = kwargs.pop('purchases.User', None)
self.Company = kwargs.pop('purchases.Company', None)
super(Stock_Totalform, self).__init__(*args, **kwargs)
self.fields['stockitem'].queryset = Stockdata.objects.filter(User = self.User, Company= self.Company)
self.fields['stockitem'].widget.attrs = 'class': 'form-control select2',
self.fields['Quantity_p'].widget.attrs = 'class': 'form-control',
self.fields['rate_p'].widget.attrs = 'class': 'form-control',
self.fields['Total_p'].widget.attrs = 'class': 'form-control',
Purchase_formSet = inlineformset_factory(Purchase, Stock_Total,
form=Stock_Totalform, extra=6)
But the filtering of queryset is not showing any item if it is present under specific User and also under specific company.
Can anyone help me with the exact query that will filter objects under specific user and company.
Thank you
django django-models django-forms django-views
I want to filter certain modelfield in my inlineform to specific user and company.
But was unable to do in django inline formset.
This are my models:
class Purchase(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True)
party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger')
purchase = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger')
total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) purchases
class Stock_total(models.Model):
purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal')
stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock')
quantity_p = models.PositiveIntegerField()
rate_p = models.DecimalField(max_digits=10,decimal_places=2)
grand_total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)
My views:
class Purchase_createview(ProductExistsRequiredMixin,LoginRequiredMixin,CreateView):
form_class = Purchase_form
template_name = 'stockkeeping/purchase/purchase_form.html'
def get_context_data(self, **kwargs):
context = super(Purchase_createview, self).get_context_data(**kwargs)
context['profile_details'] = Profile.objects.all()
company_details = get_object_or_404(Company, pk=self.kwargs['pk'])
context['company_details'] = company_details
if self.request.POST:
context['stocks'] = Purchase_formSet(self.request.POST)
else:
context['stocks'] = Purchase_formSet()
return context
def form_valid(self, form):
form.instance.user = self.request.user
c = Company.objects.get(pk=self.kwargs['pk'])
form.instance.company = c
context = self.get_context_data()
stocks = context['stocks']
with transaction.atomic():
self.object = form.save()
if stocks.is_valid():
stocks.instance = self.object
stocks.save()
return super(Purchase_createview, self).form_valid(form)
In my forms I have tried this:
class Stock_Totalform(forms.ModelForm):
class Meta:
model = Stock_Total
fields = ('stockitem', 'Quantity_p', 'rate_p', 'Disc_p', 'Total_p')
def __init__(self, *args, **kwargs):
self.User = kwargs.pop('purchases.User', None)
self.Company = kwargs.pop('purchases.Company', None)
super(Stock_Totalform, self).__init__(*args, **kwargs)
self.fields['stockitem'].queryset = Stockdata.objects.filter(User = self.User, Company= self.Company)
self.fields['stockitem'].widget.attrs = 'class': 'form-control select2',
self.fields['Quantity_p'].widget.attrs = 'class': 'form-control',
self.fields['rate_p'].widget.attrs = 'class': 'form-control',
self.fields['Total_p'].widget.attrs = 'class': 'form-control',
Purchase_formSet = inlineformset_factory(Purchase, Stock_Total,
form=Stock_Totalform, extra=6)
But the filtering of queryset is not showing any item if it is present under specific User and also under specific company.
Can anyone help me with the exact query that will filter objects under specific user and company.
Thank you
django django-models django-forms django-views
django django-models django-forms django-views
asked Mar 8 at 8:07
Niladry KarNiladry Kar
1
1
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You need to remove queryset
in __init__
of the form and pass instance
parameter while creating inlineformset_factory
.
Purchase_formSet = inlineformset_factory(
Purchase,
Stock_Total,
form=Stock_Totalform,
extra=6,
)
PurchaseForm = Purchase_formSet(instance=Stockdata.objects.filter(User='1'))
This is static method which means, the filter will be fixed and won't be changed based on user input in form.
If you want to have dynamic filter based on user input in some of the form fields, this article explains it very well and in detail.
Now I am getting this errorTypeError: inlineformset_factory() got an unexpected keyword argument 'instance'
– Niladry Kar
Mar 8 at 9:28
@NiladryKar I've updated the answer. Please check.
– Abbas
Mar 8 at 10:00
How can I put something likeUser = request.user
instead ofUser='1'
. here?
– Niladry Kar
Mar 8 at 11:26
That's where you need to follow the tutorial I pointed out. Dynamic filtering could be achieved using AJAX requests.
– Abbas
Mar 8 at 11:37
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55059020%2fhow-to-filter-queryset-in-django-inline-form%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to remove queryset
in __init__
of the form and pass instance
parameter while creating inlineformset_factory
.
Purchase_formSet = inlineformset_factory(
Purchase,
Stock_Total,
form=Stock_Totalform,
extra=6,
)
PurchaseForm = Purchase_formSet(instance=Stockdata.objects.filter(User='1'))
This is static method which means, the filter will be fixed and won't be changed based on user input in form.
If you want to have dynamic filter based on user input in some of the form fields, this article explains it very well and in detail.
Now I am getting this errorTypeError: inlineformset_factory() got an unexpected keyword argument 'instance'
– Niladry Kar
Mar 8 at 9:28
@NiladryKar I've updated the answer. Please check.
– Abbas
Mar 8 at 10:00
How can I put something likeUser = request.user
instead ofUser='1'
. here?
– Niladry Kar
Mar 8 at 11:26
That's where you need to follow the tutorial I pointed out. Dynamic filtering could be achieved using AJAX requests.
– Abbas
Mar 8 at 11:37
add a comment |
You need to remove queryset
in __init__
of the form and pass instance
parameter while creating inlineformset_factory
.
Purchase_formSet = inlineformset_factory(
Purchase,
Stock_Total,
form=Stock_Totalform,
extra=6,
)
PurchaseForm = Purchase_formSet(instance=Stockdata.objects.filter(User='1'))
This is static method which means, the filter will be fixed and won't be changed based on user input in form.
If you want to have dynamic filter based on user input in some of the form fields, this article explains it very well and in detail.
Now I am getting this errorTypeError: inlineformset_factory() got an unexpected keyword argument 'instance'
– Niladry Kar
Mar 8 at 9:28
@NiladryKar I've updated the answer. Please check.
– Abbas
Mar 8 at 10:00
How can I put something likeUser = request.user
instead ofUser='1'
. here?
– Niladry Kar
Mar 8 at 11:26
That's where you need to follow the tutorial I pointed out. Dynamic filtering could be achieved using AJAX requests.
– Abbas
Mar 8 at 11:37
add a comment |
You need to remove queryset
in __init__
of the form and pass instance
parameter while creating inlineformset_factory
.
Purchase_formSet = inlineformset_factory(
Purchase,
Stock_Total,
form=Stock_Totalform,
extra=6,
)
PurchaseForm = Purchase_formSet(instance=Stockdata.objects.filter(User='1'))
This is static method which means, the filter will be fixed and won't be changed based on user input in form.
If you want to have dynamic filter based on user input in some of the form fields, this article explains it very well and in detail.
You need to remove queryset
in __init__
of the form and pass instance
parameter while creating inlineformset_factory
.
Purchase_formSet = inlineformset_factory(
Purchase,
Stock_Total,
form=Stock_Totalform,
extra=6,
)
PurchaseForm = Purchase_formSet(instance=Stockdata.objects.filter(User='1'))
This is static method which means, the filter will be fixed and won't be changed based on user input in form.
If you want to have dynamic filter based on user input in some of the form fields, this article explains it very well and in detail.
edited Mar 8 at 10:00
answered Mar 8 at 8:36
AbbasAbbas
16512
16512
Now I am getting this errorTypeError: inlineformset_factory() got an unexpected keyword argument 'instance'
– Niladry Kar
Mar 8 at 9:28
@NiladryKar I've updated the answer. Please check.
– Abbas
Mar 8 at 10:00
How can I put something likeUser = request.user
instead ofUser='1'
. here?
– Niladry Kar
Mar 8 at 11:26
That's where you need to follow the tutorial I pointed out. Dynamic filtering could be achieved using AJAX requests.
– Abbas
Mar 8 at 11:37
add a comment |
Now I am getting this errorTypeError: inlineformset_factory() got an unexpected keyword argument 'instance'
– Niladry Kar
Mar 8 at 9:28
@NiladryKar I've updated the answer. Please check.
– Abbas
Mar 8 at 10:00
How can I put something likeUser = request.user
instead ofUser='1'
. here?
– Niladry Kar
Mar 8 at 11:26
That's where you need to follow the tutorial I pointed out. Dynamic filtering could be achieved using AJAX requests.
– Abbas
Mar 8 at 11:37
Now I am getting this error
TypeError: inlineformset_factory() got an unexpected keyword argument 'instance'
– Niladry Kar
Mar 8 at 9:28
Now I am getting this error
TypeError: inlineformset_factory() got an unexpected keyword argument 'instance'
– Niladry Kar
Mar 8 at 9:28
@NiladryKar I've updated the answer. Please check.
– Abbas
Mar 8 at 10:00
@NiladryKar I've updated the answer. Please check.
– Abbas
Mar 8 at 10:00
How can I put something like
User = request.user
instead of User='1'
. here?– Niladry Kar
Mar 8 at 11:26
How can I put something like
User = request.user
instead of User='1'
. here?– Niladry Kar
Mar 8 at 11:26
That's where you need to follow the tutorial I pointed out. Dynamic filtering could be achieved using AJAX requests.
– Abbas
Mar 8 at 11:37
That's where you need to follow the tutorial I pointed out. Dynamic filtering could be achieved using AJAX requests.
– Abbas
Mar 8 at 11:37
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55059020%2fhow-to-filter-queryset-in-django-inline-form%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown