Basically I want to change value of company id and company name if your company field is changed.
Here I have used django-autocomplete-light for your company field. Code for this form:
class PartnerAddForm(forms.ModelForm):
company_id = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'disabled': ''}), required=False)
company_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'disabled': ''}), required=False)
class Meta:
model = CompanyCompanyMap
fields = ('your_company',)
widgets = {
'your_company': autocomplete.ModelSelect2(url='url_company_autocomplete',
attrs={'class': 'form-control',
'data-placeholder': 'Type for getting available companies'})
}
Code for autocomplete view of your company field:
class CompanyAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = CompanyAccess(self.request).get_non_partners()
if self.q:
qs = qs.filter(company_name__istartswith=self.q)
return qs
And code for template of this form
<form class="form-horizontal" role="form" action="." method="POST">
{% csrf_token %}
{% for f in form %}
<div class="form-group">
<label for="id_{{ f.name }}" class="col-sm-2 control-label">{{ f.label|capfirst }}</label>
<div class="col-sm-7">
{{ f }}
</div>
</div>
{% endfor %}
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-7">
<button type="submit" class="btn btn-default btn-primary">
Add Company as Friend
</button>
</div>
</div>
<!-- /.table-responsive -->
</form>
Is there any way to change it using js or other mechanism?
Related
I have a form (edit_city.html) where I want to edit my record, there is also one dropdown
field in which data is retrieving from another model name Country. How can I get the exact
value in dropdown field, when I click on edit.
Here is my Code
class Country(models.Model):
CountryID = models.AutoField(primary_key=True)
CountryName = models.CharField(max_length=125, verbose_name="Country Name")
def __str__(self):
return self.CountryName
class City(models.Model):
CityID = models.AutoField(primary_key=True)
CityName = models.CharField(max_length=125, verbose_name='City Name')
Country = models.ForeignKey(Country, verbose_name='Country Name',
on_delete=models.CASCADE)
def __str__(self):
return self.CityName
views.py
def Edit_City(request, id):
city = City.objects.get(CityID=id)
country = Country.objects.all()
context = {
'city':city,
'country':country,
}
return render(request, 'City/edit_city.html', context)
edit_city.html
<form method="post" action="{% url 'update_city' %}">
{% csrf_token %}
<div class="row">
<div class="col-12">
<h5 class="form-title"><span>Edit City</span></h5>
</div>
{% include 'includes/messages.html' %}
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">Country</label>
<select class="form-control" name="country_id" required>
<option>Select Country</option>
{% for con in country %}
<option value="{{con.CountryID}}">{{con.CountryName}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label>City Name</label>
<input type="text" class="form-control" name="city_name" value="{{city.CityName}}" required>
<input type="text" class="form-control" name="city_id" value="{{city.CityID}}" required hidden>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update City</button>
</div>
</div>
</form>
I have the following form:
class UpdateForm(forms.Form):
name = forms.CharField(max_length = 15,
widget=forms.TextInput(
attrs={
"class": "form-control",
'required': True,
'placeholder': 'Device name'
}
))
turn_server = forms.ChoiceField(
choices = TURN_CHOICES,
widget=forms.Select(
attrs={
"class": "form-control form-control-sm",
}
))
fps = forms.IntegerField(
widget=forms.NumberInput(
attrs={
'id':'ex1',
'data-slider-id':'ex1Slider',
'type':"text",
'data-slider-min':"10",
'data-slider-max':"60",
'data-slider-step':"1",
}
))
bitrate = forms.IntegerField(
widget=forms.NumberInput(
attrs={
'id':'ex2',
'data-slider-id':'ex2Slider',
'type':"text",
'data-slider-min':"200",
'data-slider-max':"2000",
'data-slider-step':"1",
}
))
class Meta:
model = Device
fields = ['name','fps','bitrate','turn_server']
to be used in the HTML template:
<form action="." method="POST">
{% csrf_token %}
{% for field in form %}
<div class="form-group row{% if field.errors %} invalid{% endif %}">
<label class="col-sm-3 col-form-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
<div class="col-sm-6">
{{ field }}
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-sm btn-light">Save</button>
</form>
and the view.py:
def control(request):
template = 'template.html'
context = {}
context['form'] = UpdateForm(initial={
'name': 'TestName',
'fps': '45',
'turn_server':'TestServer',
'bitrate':'500'
})
return render(request, template, context)
For some reason I can't figure it out, the form rendered in the template does not render with the initial values I have defined with initial. For example the fps resulted input html element is the following:
<input type="text" name="fps" value="10" id="ex1" data-slider-id="ex1Slider" data-slider-min="10" data-slider-max="60" data-slider-step="1" required="" data-value="10" style="display: none;">
Oddly, If I print in the views.py the form that is passed to the context I get the correct form data (ex value=45):
<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="TestName" class="form-control" required placeholder="Device name" maxlength="15" id="id_name"></td></tr>
<tr><th><label for="id_turn_server">Turn server:</label></th><td><select name="turn_server" class="form-control form-control-sm" id="id_turn_server">
<option value="1">frankfurt</option>
<option value="2">amsterdam</option>
<option value="3">new_york</option>
</select></td></tr>
<tr><th><label for="ex1">Fps:</label></th><td><input type="text" name="fps" value="45" id="ex1" data-slider-id="ex1Slider" data-slider-min="10" data-slider-max="60" data-slider-step="1" required></td></tr>
<tr><th><label for="ex2">Bitrate:</label></th><td><input type="text" name="bitrate" value="500" id="ex2" data-slider-id="ex2Slider" data-slider-min="200" data-slider-max="2000" data-slider-step="1" required></td></tr>
You can try to define the initial data from the form:
name = forms.CharField(initial='Your name')
Take a look at the documentation here
With this code i want to store multiple courses to the student table.But this code is not working.Neither it throws any error neither saves any data.The main problem is while clicking submit button the submit button does not perform any action at all.It does not load the submit button.How can i solve this??
I think the problem is in add_student.html template.When i return form.error it throws course.Is there anything i have to change??but i want to keep my design like this
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
def __str__(self):
return self.title
class Student(models.Model):
name = models.CharField(max_length=100)
course = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
def __str__(self):
return self.name
views.py
def addstudent(request):
courses = Course.objects.all()
if request.method == 'POST':
form = AddStudentForm(request.POST,request.FILES)
if form.is_valid():
student = form.save()
student.save()
# student.course.set(courses)
messages.success(request, 'student saved.')
return redirect('students:add_student')
else:
return HttpResponse(form.errors) # it returns course.i think the problem is while saving the course
else:
form = AddStudentForm()
return render(request,'students/add_student.html',{'form':form,'courses':courses})
forms.py
class AddStudentForm(forms.ModelForm):
course = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple)
class Meta:
model = Student
fields = ['name','course','email','address','phone','image','joined_date']
add_student.html
<form action="{% url 'students:add_student' %}"
method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Courses <span class="text-danger">*</span></h5>
<div class="controls">
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.id}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
</div>
</div>
<div class="form-group">
<h5>Address<span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Phone Number <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="phone" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Email <span class="text-danger">*</span></h5>
<div class="controls">
<input type="email" name="email" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Joined Date <span class="text-danger">*</span></h5>
<div class="controls">
<input type="date" name="joined_date" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Image <span class="text-danger">*</span></h5>
<div class="controls">
<input type="file" name="image" class="form-control" > </div>
</div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
I'd recommend this solution:
courses = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset= Course.objects.all())
in views.py
if form.is_valid():
student = form.save(commit=False)
courses = form.cleaned_data['courses']
student.course = courses
student.save()
ps. it's a good practice to name m2m fields in plural:
courses = models.ManyToManyField(Course)
here's what I meant with templates:
in add_student.html
Comment out whole <form> block and replace it with Django's {{ form }} and see how it'd render
You have a queryset of courses passed in context to template. Try to change it from:
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.title}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
to just:
{{ form.cource }}
Try a Class Based View
class CreateStudent(CreateView):
model = Student
form_class = AddStudentForm
template_name = "add_student.html"
I wish to know how to display 'auto_now_add' fields (and as disabled fields) in django frontend forms.
I attach some of relevant code:
# models.py
class ModelA(models.Model):
name = models.CharField('Name', max_length=100)
inserted = models.DateTimeField('Inserted ', auto_now_add=True)
# forms.py
class ProcessModelAForm(forms.ModelForm):
class Meta:
model = ModelA
fields = '__all__'
widgets = {
"name": forms.TextInput({
"class": "form-control",
"disabled": True,
}),
"inserted": forms.DateTimeInput({
"class": "form-control",
"disabled": True,
}),
}
# views.py
def process_model_a(request, pk):
instance_model_a = get_object_or_404(ModelA, id=pk)
process_form = ProcessModelAForm(instance=instance_model_a)
if request.method == 'POST':
# ...
return render(request, 'myapp/process_model_a.html', {'process_form ': process_form , 'instance':instance_model_a , } )
# process_model_a.html
<form method="post" class="form-horizontal">
{% csrf_token %}
{% for field in process_form %}
<div class="form-group form-group-lg">
<label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
{{ field }}
</div>
<div class="col-sm-4">
{{ field.errors }}
</div>
</div>
{% endfor %}
<div class="form-group">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary btn-lg center-block">Process</button>
</div>
</div>
</form>
The page "process_model_a.html" shows only "name" fields.
How can I display also "inserted" field?
Thanks.
So i have a button on my detailView page for my model 'patient', and that takes you to a createView for my other model 'appointment'. What i want is the foreign key field of the appointment to be pre-filled depending on what detailView i come from. Here is my code so far:
urls.py:
# /patients/appointment/add
url(r'appointment/add/$', views.appointmentCreate.as_view(), name='appointment-create'),
models.py:
class patient(models.Model):
TITLE_CHOICES = (
('Mr', 'Mr'),
('Mrs', 'Mrs'),
('Ms', 'Ms'),
('Miss', 'Miss'),
)
Title = models.CharField(max_length=100, blank=True, choices=TITLE_CHOICES)
First_Name = models.CharField(max_length=250, default='')
Surname = models.CharField(max_length=250, default='')
DOB = models.DateField()
class appointment(models.Model):
Patient = models.ForeignKey(patient, on_delete=models.CASCADE)
views.py:
class appointmentCreate(LoginRequiredMixin, CreateView):
model = appointment
fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType']
form-template.html:
<body>
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
</body>
appointment_form.html:
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<h3>Add new appointment</h3>
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'patients/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
The button from the detailView of patient to create appointment:
<ul class="nav nav-pills" style="margin-bottom: 10px;">
<li role="presentation" class="active">View All</li>
<li role="presentation">Add New Appointment</li>
</ul>
For example, the url might be /appname/appointment/add/?Patient=pk , where the end part determines what the value of Patient will be. I have looked into the get_initial function but do not understand how it can help me achieve this. Any help is appreciated. I am relatively new to django so please nothing too complex.
Edit: I have added this code to my model, thanks to Dimitris Kougioumtzis:
def get_context_data(self, **kwargs):
context = super(appointmentCreate, self).get_context_data(**kwargs)
context['patient_id'] = self.request.GET.get('patient')
return context
How do i implement this code?
first you create a modelForm:
from django import forms
from your_app.models import appointment
class AppointmentForm(forms.ModelForm):
class Meta:
model = appointment
fields = ['Patient', 'Date', 'Time', 'Duration', 'Location', 'Clinician', 'AppointmentType']
Then you pass the model form in your CreateView:
class appointmentCreate(LoginRequiredMixin, CreateView):
model = appointment
form_class = AppointmentForm
def get_initial(self):
patient = self.request.GET.get('patient')
return {
'patient': patient,
}
and Your patient choicefield will be populated based on the request get parameter