I have a model form containing four fields, by default only one field is active waiting for the user input.
class SaleOrderInvoiceForm(forms.ModelForm):
class Meta:
model = SaleOrderInvoice
fields = (
'supplier',
'sale_order',
'invoice_number',
'invoice_date',
)
widgets={
'supplier':forms.Select(attrs={'class':'form-control'}),
'sale_order':forms.Select(attrs={'class':'form-control', 'disabled':'disabled'}),
'invoice_number':forms.TextInput(attrs={'class':'form-control', 'disabled':'disabled'}),
'invoice_date':forms.DateInput(attrs={'class':'form-control','type':'date','disabled':'disabled'}),
}
Based on the user selection of the first input, the rest of the form is loaded via AJAX. Now in the view, after necessary filtering, I want to swtich the disabled form fields to enabled and the enabled to disabled. I have tried the following but with no luck.
form = SaleOrderInvoiceForm()
form.fields['supplier'].disabled = True
form.fields['sale_order'].disabled = False
form.fields['invoice_number'].disabled = False
form.fields['invoice_date'].disabled = False
It neither raises any exceptions nor it works as desired.
can anyone suggest a way forward with this?
I found the solution, it appears the disabled attribute cannot be reset back to False, it can however pop out.
form.fields['supplier'].disabled = 'disabled'
form.fields['sale_order'].widget.attrs.pop('disabled')
form.fields['invoice_number'].widget.attrs.pop('disabled')
form.fields['invoice_date'].widget.attrs.pop('disabled')
Related
I am trying to restrict the dropdown options according to the user type within the same form
forms.py
class EForm(forms.ModelForm):
class Meta:
model = Model
fields = ('t','s','q')
I think you need to override the entire field.
https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#overriding-the-default-fields
So set one of your options (the most common one) as the default on the form - add this code to your list of fields (i.e. above Meta)
status = forms.Select(
widget=forms.Select(choices=CHOICES_OPTIONS_1),
)
Then override the widget if you need to by passing a new dict - you can replace your current if .. else with this bit.
if not self.user.is_usertypeA:
widgets = {
'status': Select(choices=CHOICES_OPTIONS_2),
}
I've not tested this, but it should work.
Note the options 1 and 2 are meant to represent the tuples you give in the question - so the first one is C and the second one would be A´ and B` in your example.
Not entirely convinced __init__ is the place to do this either, but if it works ...
So I have a user model with the following columns:
username = models.CharField(db_column='Username',max_length=32,unique=True)
email = models.CharField(db_column='Email',max_length=255)
password = models.CharField(db_column='Password',max_length=128)
prosthodontist = models.ForeignKey('Prosthodontist',on_delete=models.SET_NULL,null=True)
I'm trying to make a dropdown that allows the user to change their Prosthodontist value through django forms. It can't be a static list cause it has to always have every available Prosthodontist as they get added.
Just for show this is what I have so far along the lines of the form:
class ChangeProsthodontistForm(forms.ModelForm):
class Meta:
model = User
fields = ('prosthodontist',)
prosthodontist = forms.ChoiceField(
label = "Prosthodontist",
widget = forms.Select(
attrs={
'id':'prosthodontist',
},
),
choices=()
)
Please help me with this cause I'm really confused I feel like I could be able to iterate through the entries with a for loop but I feel like there has to be a better way through Django.
You answer is ModelChoiceField.
prosthodontist = forms.ModelChoiceField(
# ...
queryset = Prosthodontist.objects.all(),
# ...
)
I am trying to set a readonly attribute to this specific field in django. What I hope to accomplish is the field's data shows but it cant be changed. How do I go about this? Below is what I've tried and isn't working for me.
class editcartform(ModelForm):
class Meta:
model = signedup
exclude = ['sessionid', 'price', 'paid', 'orderid', 'dancer_1_level', 'dancer_2_level', 'dancer_2_sex', 'dancer_1_sex']
widgets = {
'comp_name':Textarea(attrs={'readonly'}),
}
'comp_name':Textarea(attrs={'readonly':'readonly'}),
or
'comp_name':Textarea(attrs={'disabled':'disabled'}),
It may change depends on what you want.
There are some constraints to this problem. We currently use a production database, with live Virtual Machine Statistics. We are trying to create a django interface, that interfaces with the tables we want our administrators to be able to edit. Thus, migrations are out of the question, for unless I have come to understand migrations wrong it will affect the current database structure and or data.
I matched the database structure exactly in my models.py file. However I have run into a few issues. One of the issues I have run into is when I try to add a new item under the admin control panel it will give me an integrity error as it is attempting to insert a null value for the field I have set as the primary key in the models.py file.
We are currently using an oracle database.
My Models.py not all of it but a sample of it.
class License(models.Model):
license_id = models.AutoField(primary_key = True, editable = False, db_column='license_id')
license_authority_id = models.ForeignKey(License_authoritie, on_delete = models.PROTECT, db_column='license_authority_id')
product = models.CharField(max_length = 20)
class Meta:
managed = False
db_table = 'licenses'
ordering = ['product']
def __unicode__(self): # Python 3: def __str__(self):
return self.product
class Vm_license(models.Model):
vm_license_id = models.AutoField(primary_key = True, db_column='vm_license_id')
vm_id = models.ForeignKey(Vm, on_delete = models.PROTECT, db_column='vm_id')
license = models.ManyToManyField(License)
class Meta:
managed = False
db_table = 'vm_licenses'
The error I get:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/portal/vm_license/add/
Django Version: 1.6.5
Exception Type: IntegrityError
Exception Value:
ORA-01400: cannot insert NULL into ("DEV"."VM_LICENSES"."VM_LICENSE_ID")
On top of that I have run into another problem.
For these two tables, under the vm_licenses section in the admin panel which is a table that holds all VM's and their assigned licenses. I need the ability to select multiple licenses at a time for each vm_id under the add section of the admin panel but i'm not quite sure how to do this.
admin.py code
class vm_license_admin(admin.ModelAdmin):
#list_display = ('vm_id', 'license_id')
list_display = ('vm_id',)
search_fields = ('vm_id__vm_name',)
ordering = ('vm_id',)
filter_horizontal = ('license',)
admin.site.register(Vm_license, vm_license_admin)
I also made an oracle trigger to auto increment a primary key if there is none, but im still getting the same error.
CREATE OR REPLACE TRIGGER license_trigger
BEFORE INSERT ON vm_licenses
FOR EACH ROW
BEGIN
SELECT vm_license_seq.nextval
INTO :new.vm_license_id
FROM dual;
END;
to be more percise I am using a manytomany field and it displays correctly when I goto add a new item before clicking save and getting the null error, however if I goto an existing item it will say table or view doesnt exist.
I was going to comment on your question, but I do not have the reputation yet...
but can I suggest you post your relevant admin.py code? Perhaps there is something within it relating to the Null PK error.
With regards to the second part, a ManyToManyField sounds more suitable.
I have a Model where one boolean ModelField is dependent upon another. The Model is configured like so:
class Situation(models.Model):
ctcs = models.BooleanField(verbose_name="Cross-Technology Critical Situation", blank=True)
has_been_ctcs = models.BooleanField(editable=False, default=False)
The ctcs field is rendered as a checkbox in the ModelForm for this model. What I want to do is, if the ctcs field has been checked, I also want to set has_been_ctcs to True. So what I am doing is setting cleaned_data['has_been_ctcs'] = True on the ModelForm. I've tried doing this both in my view that handles the POST request, as well as within the ModelForm clean function like so:
class SituationForm(forms.ModelForm):
def clean(self):
cleaned_data = super(SituationForm, self).clean()
ctcs = cleaned_data.get("ctcs")
if ctcs:
self.cleaned_data['has_been_ctcs'] = True
return cleaned_data
And here is the snippet from the view that handles creation of a new Situation model:
sit_form = SituationForm(request.POST)
if sit_form.is_valid():
print sit_form.cleaned_data['ctcs'] # Prints True
if sit_form.cleaned_data['ctcs']:
print "Checking form has_been_ctcs"
# Have also tried setting sit_form.cleaned_data['has_been_ctcs'] here, no difference from doing it in `def clean()`
print sit_form.cleaned_data['has_been_ctcs'] # Prints True
sit = sit_form.save()
print sit.has_been_ctcs # Prints False
I cannot seem to get the has_been_ctcs value of True to propagate to the Situation model. How can I go about doing this?
cleaned_data only works for fields that are included in the form. What you want to do is:
sit_form = SituationForm(request.POST)
if sit_form.is_valid():
if sit_form.cleand_data['ctcs']:
sit_form.instance.has_been_ctcs = True
sit = sit_form.save()