Django Unable to set widget in form class - django-models

I want to create a form that hides a field. This works:
form_class = modelform_factory( Model, widgets = { 'field1' : forms.HiddenInput() }, exclude = () )
form = form_class() # field1 is hidden
Why doesn't it work when I create the form_class and then set the widgets through its meta class?
form_class = modelform_factory( Model, exclude=() )
form_class._meta.widgets = { 'field1' : forms.HiddenInput() }
form = form_class() # field1 is not hidden in form

Related

Using Django formset displaying related names in template

I am trying to display the state values for each country name in Django app. To save the user response, I am using Django generic CreateView. My models look something like this:
class Question(model.Models):
ques_id = models.AutoField(primary_key=True)
country = models.ForeignKey(Country)
state = models.CharField(max_length=...)
class Test(model.Models):
test = models.AutoField(primary_key=True, )
test_num = models.CharField(max_length=6, )
class Response(model.Models):
response = models.AutoField(primary_key=True)
test_id = models.ForeignKey(Test, related_name='test', )
ques_offered = models.ForeignKey(Question, related_name='choice',
ans_submitted = models.CharField(max_length=240,
To display the available choices for field state for each country value (in the db), I am looping through Django management form for the formset in my template. However, I am unable to get to the values of field state instead I am getting the country values.
Additional info:
The views that I am using to achieve this:
class ResponseCreateView(CreateView):
template_name = ...
model = Test
form_class = # Form_name
def get_context_data(self, **kwargs):
data = super(ResponseCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['get_response'] = responseFormset(self.request.POST, self.request.FILES)
else:
data['get_response'] = responseFormset()
def form_valid(self, form):
context = self.get_context_data()
get_response = context['get_response']
with transaction.atomic():
if get_response.is_valid():
self.object = form.save()
get_response.instance = self.object
get_response.save()
return redirect('...')
else:
context.update({'get_response': get_response,
})
return self.render_to_response(context)
return super(ResponseCreateView, self).form_valid(form)

How can I create multiple related objects inside a view with cleaned data from two Django forms on the same page

I have 4 related Django Models ModifiedUser and Profile defined as follows . I am trying to create the person responsible for the activity,through a person model form. Through a person profile model form I am trying to add their profile details which includes the related person,country etc. Using these details I want to create a second person, called related user. Then I want to assign the two people to the activities via their Roles.
Models
'''
Class ModifiedUser:
email = models.EmailField(
max_length=255,blank=True,null=True,unique=True)
...
Class Profile:
modified_user = models.ForeignKey(ModifiedUser)
related_user = models.EmailField(
max_length=255,blank=True,null=True)
...
class Activity:
person = models.ManyToManyField(Profile,related_query_name='actor',related_name=' person', through='RoleAssignment')
class RoleAssignment:
person = models.ForeignKey(Profiles,on_delete=CASCADE,related_name="role")
feedback = models.ForeignKey(Activity,on_delete=CASCADE)
...
'''
Forms:
'''
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = '__all__'
class ModifiedUserForm(forms.ModelForm):
class Meta:
model = ModifiedUser
fields = '__all__'
'''
View
'''
from profiles.models import Profile, ModifiedUser,Activity
from .forms import ResponsibleForm, ModifiedUser
def add_activity_owner(request):
activity = Activity.objects.create(initiatedby=currentuser,updatedby=currentuser)
if request.method == 'POST':
responsibleform = ResponsibleForm(request.POST, request.FILES)
profileform = ProfileForm(request.POST, request.FILES)
if all([receiverform.is_valid(), detailform.is_valid()]):
owner_firstname =responsibleform .cleaned_data['Phone']
owner_lastname = responsibleform .cleaned_data['Address']
owner_email = responsibleform .cleaned_data['email']
relatedperson_email= profileform.cleaned_data['related_user'],
country = profileform.cleaned_data['country'],
gender = profileform.cleaned_data['gender'],
relatedperson,person_created = ModifiedUser.objects.get_or_create(email=relatedperson_email,FirstName=NULL,LastName=NULL)
owner,owner_created=Profiles.objects.get_or_create(email=owner_email,FirstName=owner_firstname,Lastame=owner_lastname)
owner_profile ,owner_created= Profiles.objects.get_or_create(user=owner,
related_user= relatedperson_email,
country = country,
gender = gender,
owner_role = RoleAssignment.objects.create(activity=activity,person=owner,role=role['owner'])
related_person_role = RoleAssignment.objects.create(activity=activity,person=relatedperson,role=role['actor'])
context['relateduser']=relateduser
context['owner']=owner
context['owner_role']=owner_role
return redirect(selectroles,activity)
else:
responsibleform = GiverForm()
profileform = UserProfileUpdateForm()
profileform':profileform})
return render(request,'addowner.html',context)
'''

How check UniqueConstraint in Django with CreateView and custom forms if field set in view?

I do:
I define UniqueConstraint (also try with 'unique_together') in model:
class Project(models.Model):
class Meta:
constraints = [
models.UniqueConstraint(
fields=['company', 'name'], name="unique_project_name_in_company"
)
]
name = models.CharField(blank=False, max_length=256)
company = models.ForeignKey(
Company,
on_delete=models.CASCADE
)
I set company in form_valid in view (I think it's reason of my problem):
class ProjectCreateView(LoginRequiredMixin, generic.CreateView):
model = Project
form_class = ProjectForm
def form_valid(self, form):
form.instance.company = self.request.user.company
return super().form_valid(form)
I try define message for 'unique_project_name_in_company' in form:
class ProjectForm(forms.ModelForm):
model = Project
class Meta:
model = Project
fields = ['name']
error_messages = {
NON_FIELD_ERRORS: {
'unique_project_name_in_company': "Name isn't unique!",
}
}
Unexpected behavior
If I submit form with non-unique pair (inputed non-unique name) I want get my custom error_message but I get:
500 IntegrityError UNIQUE constraint failed: company_id, name

Update a particular field in django forms and not be able to edit the others

I am trying to create a expense claim app, i have created a form where a user can claim a expense ,when the admin Logs in the following webpage in the picture appears and the webpages iterates all the claims that have claim_status == Null, i want the admin to be able to accept or reject the claim from the dropdown and it to update the value for that object in the database and webpage to refresh and that claim showing no more
I have given a initial value of Null for the ExpenseClaim model and when user fills the expense claim form he cannot see the claim_status field
please see my models
class ExpenseClaim(models.Model):
reference_number = models.AutoField(primary_key=True)
employee_name = models.CharField(max_length=150)
employee_ID = models.CharField(max_length=150)
claim_initiating_date = models.DateTimeField(auto_now=True)
invoice_date = models.DateField()
invoice_location = models.CharField(max_length=150)
biller_name = models.CharField(max_length=150)
invoice_category = models.CharField(max_length=150)
price = models.DecimalField(decimal_places=2, max_digits=10, null=False , default=0.00)
GST = models.DecimalField(decimal_places=2 ,max_digits=10, null=False , default=0.00)
CGST = models.DecimalField(decimal_places=2 ,max_digits=10, null=False , default=0.00)
IGST = models.DecimalField(decimal_places=2, max_digits=10, null=False , default=0.00)
Total_amount = models.DecimalField(decimal_places=2 ,max_digits=10, null=False , default=0.00)
mode_of_payement = models.CharField(max_length=20)
Payment_reference = models.BooleanField()
invoice = models.FileField()
claim_status = models.CharField(default=None , max_length=10)
payment_status = models.CharField(default= None , max_length=10)
Following is my models field i tried to create a new form but that just creates a new object in the database i want to update the existing one
invoice_category_choices =[
('food',"food"),
('travel',"travel"),
('accodmodation',"accomodation"),
('fuel',"fuel"),
# ('others',"others"),
]
claim_status_choices = [
('accepted' , 'accepted'),
('rejected' , 'rejected')
]
payment_status_choices =[
('paid' , 'paid'),
('notpaid' , 'notpaid')
]
class ExpenseClaimForm(forms.ModelForm):
class Meta:
model = ExpenseClaim
exclude = [
"employee_name",
"employee_ID",
"claim_status",
"payment_status"
]
widgets = {
'invoice_date': forms.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'placeholder':'Select a date', 'type':'date'}),
'invoice_category':forms.Select(choices= invoice_category_choices),
'claim_status':forms.Select(choices= claim_status_choices)
}
class ClaimStatusForm(forms.ModelForm):
class Meta:
model = ExpenseClaim
fields = [
"claim_status",
]
widgets = {
'claim_status':forms.Select(choices= claim_status_choices)
}
forms.py
class ClaimStatusForm(forms.ModelForm):
class Meta:
model = ExpenseClaim
fields = [
"claim_status",
]
widgets = {
'claim_status':forms.Select(choices= claim_status_choices)
}
views .py
def admin_update_view(request , reference_number):
post = get_object_or_404(ExpenseClaim , reference_number=reference_number)
form = ClaimStatusForm(instance=post)
if request.method == 'POST':
post = get_object_or_404(ExpenseClaim , reference_number=reference_number)
form = ClaimStatusForm(request.POST)
if form.is_valid():
claim_status = form.cleaned_data.get('claim_status')
post.claim_status = claim_status
post.save()
return redirect('/admin/')
context = { "form":form , "initialize_context" : initialize_context(request)}
return render(request , 'graphauth/adminupdate.html' , context)
urls.py
path('adminupdate/<int:reference_number>', views.admin_update_view , name='adminupdate'),
admin.html
update

Override registration module & Hide or show input text drupal 7

I created a module and a hook to override the registration module form :
function custommodule_form_alter(&$form, $form_state, $form_id) {
// retrieve name & surname
global $user;
$user_fields = user_load($user->uid);
$name = $user_fields->field_name['und']['0']['value'];
$surname = $user_fields->field_surname['und']['0']['value'];
// var_dump($name); die();
// check the form_id
if($form_id=='registration_form'){
if( $form['who_is_registering']['#options']['registration_registrant_type_me'] =='Myself') {
$form['field_name']['und'][0]['value']['#default_value'] = $name;
$form['field_surname']['und'][0]['value']['#default_value'] = $surname;
} else {
$form['field_name']['und'][0]['value']['#default_value'] = '';
$form['field_surname']['und'][0]['value']['#default_value'] = '';
}
}
}
In the original module we can hide or display a field depending on the select value. For example if the select is positionned on "Myself", the user mail field is not visible.
I'd like to set the fields to empty if the select is positionned on "Myself" and to show empty fields otherwise.
Actually the name and surname are defined in the fields.

Resources