I tried this in my modelform:
class Ledgerform(forms.ModelForm):
class Meta:
model = ledger1
fields = ('name', 'group1_Name')
def __init__(self, User, Company, *args, **kwargs):
self.User = kwargs.pop('User', None)
self.Company = kwargs.pop('Company', None)
super(Ledgerform, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs = {'class': 'form-control',}
self.fields['group1_Name'].queryset = group1.objects.filter(User= self.User,Company = self.Company)
In my views.py I have done something like this:
class ledger1ListView(LoginRequiredMixin,ListView):
model = ledger1
paginate_by = 15
def get_queryset(self):
return ledger1.objects.filter(User=self.request.user, Company=self.kwargs['pk'])
class ledger1CreateView(LoginRequiredMixin,CreateView):
form_class = Ledgerform
def form_valid(self, form):
form.instance.User = self.request.user
c = company.objects.get(pk=self.kwargs['pk'])
form.instance.Company = c
return super(ledger1CreateView, self).form_valid(form)
I want to perform the the same query that I have passed in my ledger1ListView by using queryset in my modelform but my kwargs.pop is not returning the current user or the company...
This is my models.py:
class ledger1(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,related_name='Companys')
name = models.CharField(max_length=32)
group1_Name = models.ForeignKey(group1,on_delete=models.CASCADE,blank=True,null=True)
Do any one know what I am doing wrong in my code?
Thank you in advance
You can override the FormMixin.get_form_kwargs [Django-doc] in your view, that it constructs a dictionary with the parameters necessary to initialize the form, like:
class ledger1CreateView(LoginRequiredMixin,CreateView):
form_class = Ledgerform
def get_form_kwargs(self):
data = super(ledger1CreateView, self).get_form_kwargs()
data.update(
User=self.request.User,
Company=company.objects.get(pk=self.kwargs['pk'])
)
return data
The form_valid function is called after the form is constructed, validated and appears to be valid. Typically it is used to redirect the user to the "success page".
Related
I wanto to display the current user in the form before submitting.
views.py
class PostEncabezadoReporte(LoginRequiredMixin, CreateView):
login_url = '/login/'
redirect_field_name = 'redirect_to'
form_class = PostEncabezadoReporteForm
template_name = "crear_reporte.html"
def form_valid(self, form):
object = form.save(commit=False)
object.user = self.request.user
object.startweek, object.endweek = self.weekdatetimeconverter(
object.semana)
object.folio = self.getfolio(
object.user, object.semana, object.tipo_reporte)
self.validar_unico = self.reporte_unico(
object.user, object.semana, object.cliente)
if self.validar_unico == 0:
object.save()
else:
return self.form_invalid(form)
return super(PostEncabezadoReporte, self).form_valid(form)
forms.py
class PostEncabezadoReporteForm(forms.ModelForm):
class Meta:
model = EncabezadoReporte
fields = ('user', 'tipo_reporte', 'tipo_gasto', 'cliente',
'semana', 'folio')
widgets = {'semana': forms.DateInput(attrs={'type': 'week'}),
}
I alreayd tried to override the init in the form and is not working, I can select the user in the field but I want it to be displayed at init.
I have tried to override the init in the form but I had a problem, I was missing a line after the super, this is an example of another form init that I did:
def __init__(self, *args, **kwargs):
self.carro = kwargs.pop('encabezado')
super(AgregarGastoReporte, self).__init__(*args, **kwargs)
self.fields['encabezado'].initial = self.carro
I have a question for you. I have the following Model:
class Centro_di_costo(models.Model):
centro_di_costo = models.CharField('Centro di costo', max_length=30)
def __str__(self):
return self.centro_di_costo
class AltriCosti(models.Model):
STATUS_CHOICES= [
('VARIABILE', 'VARIABILE'),
('FISSO', 'FISSO'),
]
centro_di_costo = models.ForeignKey(Centro_di_costo)
sub_centro_di_costo = models.CharField('Categoria', max_length=30)
status = models.CharField(choices=STATUS_CHOICES)
price=models.DecimalField()
quantity=models.IntegerField()
I use it in a lot of view, but in one of them I wanna set the value without passing from the POST request.
So I have tried to set the ModelForm in the following manner:
class ModCollaboratori(forms.ModelForm):
class Meta:
model = AltriCosti
fields = "__all__"
def __init__(self, *args, **kwargs):
super(ModCollaboratori, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
self.fields['centro_di_costo'].value= "Servizi di Produzione"
self.fields['sub_centro_di_costo'].value = "Collaboratori esterni"
self.fields['status'].value = "VARIABILE"
But It does not work. How could I fix the code to work?
You can exclude fields from your form:
class ModCollaboratori(forms.ModelForm):
class Meta:
model = AltriCosti
exclude = ['centro_di_costo', 'sub_centro_di_costo', 'status']
Then in your view you can "inject" value for these fields:
def some_view(request):
if request.method == 'POST':
form = ModCollaboratori(request.POST, request.FILES)
if form.is_valid():
form.instance.sub_centro_di_costo = 'Collaboratori esterni'
form.instance.status = 'VARIABILE'
form.instance.centro_di_costo = Centro_di_costo.objects.get_or_create(
centro_di_costo='Servizi di Produzione'
)[0]
form.save()
return redirect('name-of-some-view')
else:
form = ModCollaboratori()
return render(request, 'some_template.html', {'form': form})
for your code
self.fields['status'].value = "VARIABLE"
to make it work change to
self.instance.status = "VARIABLE"
Result:
Status: VARIABLE
basically ModelForm.__init__() will populate instance values into form.
but if we add extra field to this form, we will need to populate it by ourself in kwargs["initial"],
because this field not include in the model.
class SomeForm(forms.ModelForm):
custom_field = forms.CharField()
def __init__(self, *args, **kwargs):
kwargs["initial"]["custom_field"] = "xxxxx"
super().__init__(*args, **kwargs)
I am restricting access to the posted edit screen.
I want to make sure that only the user who posted or the super user can edit the post.
For that purpose, "UserPassesTestMixin" is used.
However, there is no limit.
And I think that my own "OnlyRecordEditMixin" is not responding. If you understand, thank you.
#mixin
class OnlyRecordEditMixin(UserPassesTestMixin):
raise_exception = True
def test_func(self):
user = self.request.user
id = self.kwargs['id']
print(id)
return user.pk == URC.objects.get(id=id).user or user.is_superuser
#view
class RecordDetailEdit(UpdateView,OnlyRecordEditMixin):
template_name = 'records/detail_edit.html'
model = URC
pk_url_kwarg = 'id'
form_class = RecordDetailEditForm
success_url = reverse_lazy('person:home')
def get_object(self, queryset=None):
obj = URC.objects.get(id=self.kwargs['id'])
return obj
#url
path('<id>/edit/', views.RecordDetailEdit.as_view(), name='record_detail_edit'),
#model
class URC(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
A mixin should be put before the base view class, to construct a good MRO here.
class RecordDetailEdit(OnlyRecordEditMixin, UpdateView):
template_name = 'records/detail_edit.html'
model = URC
pk_url_kwarg = 'id'
form_class = RecordDetailEditForm
success_url = reverse_lazy('person:home')
You should not override the get_object(..) method here. The get_object(..) method is defined in terms of get_queryset(..): it filters the get_queryset(..) with the given primary key (and/or slug).
You can however easily restrict access by restricting the get_queryset:
class OnlyRecordEditMixin(LoginRequiredMixin):
def get_queryset(self, *args, **kwargs):
qs = super().get_queryset(*args, **kwargs)
if not self.user.is_superuser:
return qs.filter(user=self.request.user)
return qs
or even more generic:
class OnlyRecordEditMixin(LoginRequiredMixin):
user_field = 'user'
def get_queryset(self, *args, **kwargs):
qs = super().get_queryset(*args, **kwargs)
if not self.user.is_superuser:
return qs.filter(**{self.user_field: self.request.user})
return qs
Here we can thus change the user_field to point to the name that is the owner of the object.
This will return a HTTP 404 response if a user that is not a superuser, nor the "owner" of the object aims to update that object.
This is cheaper, since you prevent fetching the object multiple times.
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
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.
Using inlineformset_factory I am able to add / remove phone numbers related to a single customer. Only problem is, I want to require at least 1 valid phone number for each customer.
Here is some demo code:
Models:
class Customer( models.Model ):
name = models.CharField( max_length=255 )
class PhoneNumber( models.Model ):
customer = models.ForeignKey( Customer )
number = models.CharField( max_length=10 )
Forms:
class CustomerForm( ModelForm ):
class Meta:
model = Customer
fields = ['name']
class PhoneNumberForm( ModelForm ):
class Meta:
model = PhoneNumber
fields = ['number']
Ok, so that's pretty straight forward.
Then in my view:
class Create( View ):
template_name = 'path_to_template'
CustomerForm = forms.CustomerForm
PhoneNumberFormSet = inlineformset_factory (
parent_model = Customer,
model = PhoneNumber,
form = PhoneNumberForm,
extra = 1,
)
def get(self, request):
# Return empty forms
context = {
'customer_form': self.CustomerForm,
'phone_number_formset': self.PhoneNumberFormSet
}
render( request, self.template_name, context)
def post(self, request):
this_customer_form = self.CustomerForm( request.POST )
if this_customer_form.is_valid():
new_customer.save(commit=False)
this_phone_number_formset = self.PhoneNumberFormSet(request.POST, instance=new_customer)
if this_phone_number_formset.is_valid():
new_customer.save()
this_phone_number_formset.save()
return HttpResponseRedirect(reverse_lazy('customer-detail', kwargs={'pk': new_customer.pk}))
# Something is not right, show the forms again
this_phone_number_formset = self.PhoneNumberFormSet(request.POST)
context = {
'customer_form': this_customer_form,
'phone_number_formset': this_phone_number_formset
}
render( request, self.template_name, context)
You get the point I think. Same thing for the Edit/Update view of the customer. Only then the forms are prepopulated.
At this point all I need is a way to require at least 1 valid PhoneNumber per Customer.
I found something like:
class RequiredFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(RequiredFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
from https://stackoverflow.com/questions/2406537/django-formsets-make-first-required
but it doesnt seem to work when I apply this on a BaseInlineFormSet class.
Django 1.7 seems to answer my wishes, but not for a InlineModelFormSet so far..
Any ideas?
If you just want to set the minimum or maximum, you can set them directly in inlineformset_factory, here's my code for minimum of one entry
from django.forms import inlineformset_factory
SubUnitFormSet = inlineformset_factory(
Unit, SubUnit, form=SubUnitForm, min_num=1, validate_min=True, extra=0)
You need to properly handle this in your view. I'm using CBV and this is my code for your reference
class UnitCreateView(PermissionRequiredMixin, SuccessMessageMixin, CreateView):
permission_required = "core.add_unit"
model = Unit
form_class = UnitForm
template_name = 'core/basic-info/unit_form.html'
success_url = reverse_lazy('core:units')
success_message = _("%(code)s was added successfully")
def get_context_data(self, **kwargs):
data = super(UnitCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['subunits'] = SubUnitFormSet(self.request.POST, )
else:
data['subunits'] = SubUnitFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
subunits = context['subunits']
with transaction.atomic():
if subunits.is_valid():
self.object = form.save()
subunits.instance = self.object
subunits.save()
else:
return self.render_to_response(self.get_context_data(form=form))
return super(UnitCreateView, self).form_valid(form)
Thank you kezabella ( django irc ).
Seems I found a solution by subclassing BaseInlineFormset:
class RequiredFormSet(BaseInlineFormSet):
def clean(self):
for form in self.initial_forms:
if not form.is_valid() or not (self.can_delete and form.cleaned_data.get('DELETE')):
return
for form in self.extra_forms:
if form.has_changed():
return
raise ValidationError("No initial or changed extra forms")
Btw, these validation errors do not show up in {{ formset.error }} but in:
{{ formset.non_form_errors }}