Get current user in Django modelformset_factory - django

I need to filter employees from same company as current user in forms.py.
But the solution I found, work only for single Formsets.
If I try to pass the request.user with modelformset_factory to generate a multiple formset, I get the following Error:
'MassnahmeForm' object has no attribute '__name__'
What can i Do?
Best regards
Bostjan
views.py:
frm = MassnahmeForm(user=request.user)
mformset = modelformset_factory(Massnahmen, form=frm, extra=mn.count())
forms.py:
class MassnahmeForm(forms.ModelForm):
id = forms.IntegerField(widget=forms.HiddenInput())
pdca = forms.IntegerField(widget=forms.HiddenInput())
status = forms.IntegerField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
print(self.user)
super(MassnahmeForm, self).__init__(*args, **kwargs)
class Meta:
model = Massnahmen
widgets = {
'massnahme': forms.Textarea(attrs={'onkeyup':'resizeTextarea()', 'rows': 3, 'style': 'margin: -5px;'
'width: 100%;'
'height: 100%;'}),
'umsetzer': forms.Select(choices=users, attrs={'style': 'width: 100%;'
'margin: 0px;'
'font-size: 100%;'
'padding: 0px'}),
'termin': forms.DateInput(attrs={'class': 'flatpickr flatpickr-input active',
'placeholder': 'Termin',
'readonly': 'readonly',
'style': 'width: 100%;'
'margin: 0px;'
'font-size: 100%;'
'padding: 0px'}),
}
fields = ('massnahme','umsetzer','termin','status')

You need use the Class of the form in the modelformset_factory, not one instance. Next, you can make use of the form_kwargs parameter in the Formset.
MassnahmeFormSet = modelformset_factory(
model = Massnahme,
form = MassnahmeForm,
extra = mn.count()
)
formset = MassnahmeFormSet(form_kwargs={'user': request.user})

Related

how to save custom ModelForm fields in django

i have custom fields in ModelForm and there is no any values on save. im just confuse what to use in view.py to save with data
form.py
class AddCityForm(forms.ModelForm):
duration = forms.ChoiceField(widget=forms.RadioSelect(attrs={
'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=DURATION_CHOICES)
country = forms.ChoiceField(widget=forms.RadioSelect(attrs={
'style': 'background-color: #FAF9F9', 'class': 'mb-3, form-check-inline'}), choices=CITY_CHOICE)
something = forms.CharField(widget=forms.TextInput(attrs={
'style': 'background-color: #FAF9F9', 'class': 'mb-3'}))
class Meta:
model = Cities
exclude = ['city', 'duration', 'something']
view.py
def add_city(request):
data = dict()
if request.method == 'POST':
form = AddCityForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
form.city = request.POST.get('country')
form.duration = request.POST.get('dur')
form.something = request.POST.get('something')
form = form.save()
messages.success(request, f'Test for Added Successfully')
data['form_is_valid'] = True
else:
data['form_is_valid'] = False
else:
form = AddCityForm()
context = dict(form=form)
data['html_form'] = render_to_string('cites/modal_1.html', context, request=request)
return JsonResponse(data)
can any one help with this ?
Looks like the code is working, i have no idea why did not before i asked this question but i will keep this if any one look for similar question

fill formset with django raw sql query

I use Django formset factory and update view don't fill subform with
raw SQL query and return 'RawQuerySet' object has no attribute 'ordered'
error.
object query set fine but raw SQL query return this error.
'''python
formset = modelformset_factory(model=GiftVoucherSub,
form=GiftVoucherSubForm,
extra=0,
can_delete=True,
min_num=1,
validate_min=True,
)
formset = formset(request.POST or None,
queryset=queryset,
# initial=initial,
prefix='rlt_giftvoucher',
)'''
fixed by adding extra field to forms.py and views queryset with django object.
passanger name with autocomplete.
views
queryset = GiftVoucherSub.objects.filter(main_id=id, is_deleted=False).order_by('id')
forms
class GiftVoucherSubForm(forms.ModelForm):
passanger_id = forms.CharField(max_length=30,
required=False,
widget=forms.HiddenInput()
)
passanger_name = forms.CharField(widget=forms.TextInput(attrs={
# 'id': 'form_fatura_cari_isim',
'class': 'formset-field table-condensed clearable',
'required': 'True',
'autocomplete': 'off',
'type': 'search',
'onfocus': 'fn_search_passanger(this.id)',
}
)
)
class Meta:
model = GiftVoucherSub
fields = [
'id',
'main_request_type',
'sub_request_type',
'passanger_id',
'passanger_name',
'is_deleted',
]
def __init__(self, *args, **kwargs):
super(GiftVoucherSubForm, self).__init__(*args, **kwargs)
if self.instance.passanger_id:
extra_value = BoYolcuListesi.objects.get(usertableid=self.instance.passanger_id)
self.fields['passanger_name'].initial = extra_value.isim
self.helper = FormHelper()
self.helper.form_tag = True
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'formset-field table-condensed'})
self.fields[field].label = ''

Django CreateView - How to show a related field (FK) like integer instead of select?

Hi (sorry for my bad english), i'm trying to show a form using a number input instead a select in a FK Relation on django model, but i cant make it.
The thing is that i need to fill the ID of the product manually writing the id in a input box, but django automatically makes the select form with all the products!
this is what i have in forms.py
class PurchaseForm(forms.ModelForm):
class Meta:
model = Purchase
fields = [
'date',
'supplier',
'warehouse',
]
widgets = {
'date': forms.DateInput(attrs={
'type': 'date',
}),
}
class PurchaseItemForm(forms.ModelForm):
class Meta:
model = PurchaseItem
fields = [
'product',
'quantity',
'net_purchase_price',
'sell_price',
]
widgets = {
'product': forms.NumberInput(),
}
PurchaseFormSet = inlineformset_factory(
Purchase,
PurchaseItem,
fields='__all__',
extra = 10,
)
this is my view
class PruchaseCreateView(CreateView):
template_name = 'purchases/create_purchase.html'
form_class = PurchaseForm
def get_context_data(self, **kwargs):
context = super(PruchaseCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['formset'] = PurchaseFormSet(self.request.POST)
else:
context['formset'] = PurchaseFormSet()
return context
def form_valid(self, form):
context = self.get_context_data()
formset = context['formset']
if formset.is_valid():
self.object = form.save()
formset.instance = self.object
formset.save()
return redirect(self.object.get_absolute_url())
else:
return self.render_to_response(self.get_context_data(form=form))
i try with the widget NumberInput but nothing!!! any idea?
You need to include the custom form when you call inlineformset_factory:
PurchaseFormSet = inlineformset_factory(
Purchase,
PurchaseItem,
form=PurchaseItemForm
fields='__all__',
extra = 10,
)

How to save Foreign Key text input in Django model form

My view passes an id to my form. This id is a foreign key from another table. I am not able to save the id in the database table.
(id : voucher_id, table in which i am saving the form : TmpPlInvoicedet)
What i want to do
Send voucher_id from (View) to ---> TmpFormDetForm (Form) ---> TmpPlInvoicedet (DB)
Trying to get instance from the table 'TmpPlInvoice' (which has voucher_id as PK) and save it in the form gives me
DoesNotExist at /new/ TmpPlInvoice matching query does not exist
What am i doing wrong?
Views.py
def new_invoic(request):
# Create a voucher id according to my criteria
temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct()
if not temp_vid:
voucher_id = str(1).zfill(4)
else:
voucher_id = str(int(max(temp_vid)) + 1).zfill(4)
# POST METHOD TRying to show the voucher_id in the form in readonly format
if request.method == 'POST':
form_pk = TmpForm(request.POST or None, voucher_id=voucher_id,initial={'voucher_id': voucher_id})
if form.is_valid():
form_pk.save()
form = TmpFormDetForm(request.POST or None, voucher=voucher_id, initial={'voucher': voucher_id})
# My assumption is that since i have save the voucher_id in the TmpInvoice table so i can get the PK voucher_id value and save it in the TmpInvoiceDetForm
form.save()
return HttpResponseRedirect('/new/')
else:
return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request))
else:
form_pk = TmpForm(voucher_id=voucher_id,initial={'voucher_id': voucher_id})
form = TmpFormDetForm(voucher=voucher_id, initial={'voucher': voucher_id})
return render_to_response('test.html',{'form': form, 'form_pk': form_pk},context_instance=RequestContext(request))
Forms.py
# This form contains the FK. This one is giving errors while saving.
class TmpFormDetForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
voucher = kwargs.pop('voucher', None)
super(TmpFormDetForm, self).__init__(*args, **kwargs)
self.fields['voucher'].initial = TmpPlInvoice.objects.get(voucher_id=voucher)
voucher = forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
class Meta:
model = TmpPlInvoicedet
exclude = ['emp_id','particulars','qty', 'rate' , 'itemtot', 'stock_code' ]
widgets = {
'voucher': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required': 'False', 'name': 'voucher','readonly': 'readonly'}),
'lineitem': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Total', 'required': 'False', 'blank': 'True'})}
# This form takes the PK. I save the PK here first.
class TmpForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
voucher_id = kwargs.pop('voucher_id', None)
super(TmpFor, self).__init__(*args, **kwargs)
self.fields['voucher_id'].initial = voucher_id
pos_code = MyModelChoiceField(queryset=Positions.objects.all(), widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'}))
cust = MyModelChoiceField(queryset=Custodian.objects.all(), to_field_name='acct_id',widget=forms.Select(attrs={'class': 'select2_single form-control', 'blank': 'True'}))
acct = MyModelChoiceField(queryset=Item.objects.all(), to_field_name='stock_code',widget=forms.Select(attrs={'class':'select2_single form-control', 'blank': 'True'}))
voucher_date = forms.DateField(widget=forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'}))
class Meta:
model = TmpPlInvoice
exclude = ['net_amt', 'post_date', 'address', 'posted']
widgets = {
'voucher_id': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '', 'required':'False', 'name': 'voucher_id', 'readonly': 'readonly'}),
'voucher_date': forms.TextInput(attrs={'tabindex': '-1', 'class': 'form-control has-feedback-left', 'id': 'single_cal1','aria-describedby': 'inputSuccess2Status'}),
'particulars': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Add Particulars', 'required':'False'}),
}
Models.py
class TmpPlInvoicedet(models.Model):
stock_code = models.CharField(max_length=13, blank=True, null=True)
voucher = models.ForeignKey(TmpPlInvoice, db_column='voucher_id')
lineitem = models.CharField(max_length=6)
particulars = models.CharField(max_length=200, blank=True, null=True)
qty = models.FloatField(blank=True, null=True)
rate = models.FloatField(blank=True, null=True)
itemtot = models.FloatField(blank=True, null=True)
emp_id = models.CharField(max_length=8, blank=True, null=True)
class Meta:
managed = False
db_table = 'tmp_pl_invoicedet'
unique_together = (('voucher', 'lineitem'),)
Easy peesy.
def master_detail(request):
def get_new_voucher_id():
temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct()
logger.info('Voucher ID already present %s', temp_vid)
if not temp_vid:
voucher_id = str(1).zfill(4)
else:
voucher_id = str(int(max(temp_vid)) + 1).zfill(4)
return voucher_id
voucher_id = get_new_voucher_id()
author_form = TmpForm(initial={'voucher_id': voucher_id})
author = TmpPlInvoice()
BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet, exclude=('emp_id', 'itemtot', 'voucher', 'lineitem','id'),
form=TmpFormDetForm, extra=1)
formset = BookFormSet(instance=author)
if request.method == 'POST':
logger.info('*'*50)
author = TmpForm(request.POST, initial={'voucher_id': voucher_id})
if author.is_valid():
logger.info('Data for Author is %s', author.cleaned_data)
created_author = author.save()
formset = BookFormSet(request.POST, instance=created_author)
if formset.is_valid():
logger.info('Data for Book is %s', formset.cleaned_data)
formset.save()
else:
logger.info('Formset errors %s', formset.errors)
else:
logger.info('Master form errors %s', author.errors)
logger.info('*'*50)
return HttpResponseRedirect('/new/')
else:
logger.info('Formset from GET is %s', formset.errors)
return render_to_response('new_invoice.html',
{'form': author_form, 'formset': formset},context_instance=RequestContext(request))
You seem to be creating a new invoice ID and then, in your form, attempting to get the invoice matching that ID. But that invoice doesn't exist yet, of course, because you haven't created it.
You might want to use get_or_create to ensure that the invoice is created if it doesn't exist.

How to set default values in TabularInline formset in Django admin

How to set first default rows/values in django admin's inline?
class Employee(models.Model):
username = models.CharField(_('Username'), max_length=150, null=False, blank=False)
email = models.CharField(_('Email'), max_length=150, null=False, blank=False)
class Details(models.Model):
employee = models.ForeignKey(Employee, verbose_name=_('Employee'), blank=False, null=False)
label = models.CharField(_('Label'), max_length=150, null=False, blank=False)
value = models.CharField(_('Value'), max_length=150, null=False, blank=False)
class DetailsFormset(forms.models.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
self.initial = [
{ 'label': 'first name'},
{'label': 'last name'},
{'label': 'job',}]
super(DetailsFormset, self).__init__(*args, **kwargs)
class DetailsInline(admin.TabularInline):
model = Details
formset = DetailsFormset
fieldsets = [
['', {'fields': ['employee', 'label', 'value']}]
]
class EmployeeAdmin(admin.ModelAdmin):
inlines = [DetailsInline]
but this row doesn't work
self.initial = [
{ 'label': 'first name'},
{'label': 'last name'},
{'label': 'job',}]
How do I set default values using django admin?
from django.utils.functional import curry
class DetailsInline(admin.TabularInline):
model = Details
formset = DetailsFormset
extra = 3
def get_formset(self, request, obj=None, **kwargs):
initial = []
if request.method == "GET":
initial.append({
'label': 'first name',
})
formset = super(DetailsInline, self).get_formset(request, obj, **kwargs)
formset.__init__ = curry(formset.__init__, initial=initial)
return formset
From here: Pre-populate an inline FormSet?
If what you need is to define default values for the new forms that are created you can redefine the empty_form property of a InlineFormSet:
class MyDefaultFormSet(django.forms.models.BaseInlineFormSet):
#property
def empty_form(self):
form = super(MyDefaultFormSet, self).empty_form
# you can access self.instance to get the model parent object
form.fields['label'].initial = 'first name'
# ...
return form
class DetailsInline(admin.TabularInline):
formset = MyDefaultFormSet
Now, every time you add a new form it contains the initial data you provided it with. I've tested this on django 1.5.
I tried many suggestions from Stackoverflow (Django=4.x), not working for me.
Here is what I did.
class MilestoneFormSet(forms.models.BaseInlineFormSet):
model = Milestone
def __init__(self, *args, **kwargs):
super(MilestoneFormSet, self).__init__(*args, **kwargs)
if not self.instance.pk:
self.initial = [
{'stage': '1.Plan', 'description': 'Requirements gathering', },
{'stage': '2.Define', 'description': 'Validate requirement', },
]
class MilestoneInline(admin.TabularInline):
model = Milestone
formset = MilestoneFormSet
def get_extra(self, request, obj=None, **kwargs):
extra = 0 #default 0
if not obj: #new create only
extra = 2 #2 records defined in __init__
return extra
I hope this works for everyone.
To provide a static default for all instances in the inline, I found a simpler solution that just sets it in a form:
class DetailsForm(django_forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['label'] = 'first_name'
class DetailsInline(admin.TabularInline):
form = DetailsForm
# ...
I think this doesn't work for the OP's particular case because each form has a different value for the 'label' field, but I hope it can be useful for anyone coming to this page in the future.