How to get data from jquery input field? - ajax

I use JQuery Datepicker and cannot get data from it.
In .html:
<p>Date: <input type="text" id="datepicker"/> </p>
In models.py:
class RecordModel(models.Model):
...
Date = models.DateField(blank = False)
...
In forms.py:
class RecordForm(forms.ModelForm):
...
#There is no Date field
...
In views.py:
def doc(request, DocName):
S = request.POST.get("Date") # error
Value of S in doc() function in views.py is "" (empty string), even if I choose date in a widget. How to get real data?

You need a name attribute to submit data.
You are looking for a POST data keyed by Date but I don't see a name=Date anywhere.
It should be:
<input type="text" id="datepicker" name="Date"/> </p>

Related

DRF: How to pass Foreign key Select options to show in the forms

I have the following
class Pet(models.Model):
name = models.CharField(max_length=200)
breed = models.ForeignKey(
"Breed",
on_delete=models.CASCADE,
)
Now i Have the serializer as:
class PetSerializer(serializers.ModelSerializer):
class Meta:
model = Pet
fields = "__all__
and viewset
class PetViewSet(viewsets.ModelViewSet):
queryset = Pet.objects.all()
serializer_class = PetSerializer
Now i am creating a simple form with name and select for breed
<form>
<label for="name">Name</label><br>
<input type="text" id="name" name="name"><br>
<label for="breeds">Choose a car:</label>
<select name="breeds" id="breeds">
<option value="1">Breed1</option>
<option value="2">Breed2</option>
<option value="3">Breed3</option>
<option value="4">Breed4</option>
...
</select>
</form>
Till now I was using Django forms. Which populate select fields automatically.
Since with DRF there is no such thing.
I have to write the form manually. So how to populate the select options
I am fine with ajax or reacts also.
It's not clear which technology you are using for the frontend. If you are using django template engine, you just need to override the get_context_data method in the view that's rendering this template (or add it to the context dictionary passed to the render() method if you are not using class-based views), to include breeds objects.
For example:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['breeds'] = Breeds.objects.all() # or customize the queryset
return context
Otherwise, if you are using a js framework like react or vue you have to do a request from your frontend to the breeds endpoint in order to retrieve a list of them (so you need a view exposing that resource). Than use a for loop inside the select tag iterating through the breeds object so you can use the property you need to populate the value attribute of the option tag.
Here an example using vue, assuming that you stored the response.json() a variable named breeds.
<form>
<label for="name">Name</label><br>
<input type="text" id="name" name="name"><br>
<label for="breeds">Choose a car:</label>
<select name="breeds" id="breeds">
<option
v-for="breed in breeds"
:key="breed.id"
:value="breed.id"
>{{ breed.name }}</option>
</select>
</form>
Note that I'm using breed.id as the value option tags, since ModelSerializer use pk by default to represent relationships.

fill form fields from relationship model in vform vue laravel

I have used vue vform for my form, here is the function to edit modal,
editModal(household){
this.form.reset();
$('#addNewHouseholdModal').modal('show');
this.form.fill(household); // this line fills the form with data to be edited
}
But I have form fields for which data is stored in another table. I have received the data but mnot able to figure out how to display them in the form. Please help me with it. Below is the household data i have passed in my form above.
id: 1
address_details_id: 14
ward: 2
house_no: "2"
family_no: "45"
geolocation: "{"latitude":"1.1","longitude":"1.1"}"
address_details: Object
id: 14
province: "23"
name: "Strret"
All details are filled in the form except Address details which is an object, how do I fill name from address details in the form? Thank you. Help will be appreciated.
I think you need to pass first the data before you open the modal.
editModal(data) {
isEditting = true
this.form.family_no = data.family_no
this.form.house_no = data.house_no
this.form.address = data.address
$('#addNewHouseholdModal').modal('show');
}
and then you form must be like this
<modal>
<input type="text" v-model="form.family_no" />
<input type="text" v-model="form.house_no" />
<input type="text" v-model="form.address" />
<modal>

Spring form with thymeleaf not binding right, throwing exception: Parameter is null

I have two views, one to book appointments and one to show them in a calendar view. After the booking was successful, there's a confirmation shown. The confirmation then forwards to the calendar view. I want to pass the booking infos as parameters to the calendar view so it can display the new booking accordingly in the calendar, but a null exception is thrown in that step.
I copied the template of a working form. I inspected the web request, all the necessary data is there, I think it's just not binding right.
data class EventAppointmentSearchRequest (val startDateTime: LocalDateTime, val endDateTime: LocalDateTime, val rooms: List<Room>)
/**
* Gets called when confirming a booking to add it to the DB.
*/
#PostMapping("/roomBookingConfirmation")
fun roomBookingConfirmation(model: Model, #ModelAttribute roomBookingRequest: RoomBookingRequest): String {
makeBooking(roomBookingRequest)
val date = roomBookingRequest.datetimeFrom
val start = roomBookingRequest.datetimeFrom.minusDays(date.dayOfWeek.value.toLong())
val end = roomBookingRequest.datetimeFrom.plusDays(7 - date.dayOfWeek.value.toLong())
model.addAttribute("eventAppointmentSearchRequest", EventAppointmentSearchRequest(
startDateTime = start,
endDateTime = end,
rooms = listOf(roomRepository.findByRoomName(roomBookingRequest.roomNr))
))
return "roomBookingConfirmation"
}
/**
* Displays the appointments in the calendar view according to the request
*/
#PostMapping("/calendarView")
fun calendarView(model: Model, #ModelAttribute eventAppointmentSearchRequest: EventAppointmentSearchRequest): String {
// THIS THROWS THE EXCEPTION: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method ...requests.EventAppointmentSearchRequest.<init>, parameter startDateTime
...
}
<!-- /*#thymesVar id="eventAppointmentSearchRequest" type="de.tudarmstadt.pvw.tulpe.soonToBeArtifactory.requests.EventAppointmentSearchRequest"*/ -->
<form th:action="#{/calendarView}" method="post" th:object="${eventAppointmentSearchRequest}" id="forwardToCalendar" style="grid-column: span 4">
<H1 th:text="#{roomBooking.bookingConfirmed}">
Booking confirmed.
</H1>
<div class="links">
<a href="#" th:text="#{roomBooking.nowRedirecting}" onclick="forwardToCalendar()">Redirecting to
calendarView in </a> <b id="secondsLeft">7</b>
<input type="hidden" th:field="${eventAppointmentSearchRequest.startDateTime}" th:name="startDateTime" th:value="${eventAppointmentSearchRequest.startDateTime}">
<input type="hidden" th:field="${eventAppointmentSearchRequest.endDateTime}" th:name="endDateTime" th:value="${eventAppointmentSearchRequest.endDateTime}">
<input type="hidden" th:field="${eventAppointmentSearchRequest.rooms}" name="rooms[]" th:each="room: ${eventAppointmentSearchRequest.rooms}" th:value="${room.RoomId}">
</div>
...
</form>
I expect the form to just be bound correctly, I can see all the necessary data to use the constructor of EventAppointmentSearchRequest in the web inspector of my browser. Actual output is this error message:
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method ...requests.EventAppointmentSearchRequest., parameter startDateTime
Something like this should suffice for the two date hidden inputs:
<input type="hidden" th:field="*{endDateTime}">
As for the third, th:field takes precedence over name and value attributes, if you look closely into the generated HTML, you'll see that the value is identical for each room hidden input, and it's the toString() on the list of Rooms. This is clearly wrong, and you need to specify each attribute of Room that you want to submit, have a look at the following article: https://www.baeldung.com/thymeleaf-list
I don't see the point in transmitting the details of the booking 2 more times between the client and server, I'd just pass a booking ID to the calendar page and have it load all the details...

How to get checked checkbox value from html page to spring mvc controller

im using spring mvc framework with thymeleaf template engine
the problem is , i have 1 page with multiple check box iterated sing thymeleaf th:each iterator.When i clicked multiple check boxes i want to pass check box values to the controller method..
html content
<table>
<tr th:each="q : ${questions}">
<h3 th:text="${q.questionPattern.questionPattern}"></h3>
<div>
<p >
<input type="checkbox" class="ads_Checkbox" th:text="${q.questionName}" th:value="${q.id}" name="id"/>
</p>
</div>
</tr>
</table>
*Controller*
#RequestMapping(value = Array("/saveAssessment"), params = Array({ "save" }))
def save(#RequestParam set: String, id:Long): String = {
var userAccount: UserAccount = secService.getLoggedUserAccount
println(userAccount)
var questionSetQuestion:QuestionSetQuestion=new QuestionSetQuestion
var questionSet: QuestionSet = new QuestionSet
questionSet.setUser(userAccount)
questionSet.setSetName(set)
questionSet.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetService.addQuestionSet(questionSet)
var list2: List[Question] = questionService.findAllQuestion
var limit=list2.size
var qustn:Question=null
var a = 1;
for( a <- 1 to limit ){
println( a );
qustn= questionService.findQuestionById(a)
questionSetQuestion.setQuestion(qustn)
questionSetQuestion.setQuestionSet(questionSet)
questionSetQuestion.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetQuestionService.addQuestionSetQuestion(questionSetQuestion) } "redirect:/teacher/Assessment.html" }
I think you pretty much have it. With a checkbox, you can only send one piece of information back with the form...that being the value. So if you are trying to determine which checkboxes are checked when the user clicks the submit button, then I would have the checkboxes all use one name...like "id" (exactly like you have). Value is the actual id of the question (again like you have). Once submitted, "id" will be a String array which includes all the values of the checkboxes that were checked.
So your controller method needs to take param called "ids" mapped to parameter "id" which is a string[]. Now for each id, you can call questionService.findQuestionById.
(I'm not a Groovy guru so no code example sry :)
I have used JSTL with JSP and thymeleaf was something new. I read the THYMELEAF documentation.
There is a section which explains multi valued check boxes.
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:value="${q.id}" name="id"/>
In the above code we are not binding the value to the field of the command object. Instead try doing this
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:field="*{selectedQuestions}"
th:value="${q.id}" />
here the selectedQuestions is an array object present in the spring command object.

How to add unobtrusive validation for html template fields whats not in the model

i got a template created for custom zip code field.
My template code is below:
#{
string model = Model ?? string.Empty;
string zipFirst = "";
string zipSecond = "";
if(!String.IsNullOrEmpty(model) && !String.IsNullOrWhiteSpace(model))
{
var values = model.Split('-');
if(values.Count() == 2)
{
zipFirst = values[0] ?? string.Empty;
zipSecond = values[1] ?? string.Empty;
}
}
var pName = ViewData.ModelMetadata.PropertyName;
var zipAreaId = "#" + pName + "zipcodearea";
}
<div id="#(pName)zipcodearea">
<input type="text" maxlength="5" id="zipcodefirst" name="#(pName)codefirst" value="#(zipFirst)" style="width:136px"/> -
<input type="text" maxlength="4" id="zipcodesecond" name="#(pName)codesecond" value="#(zipSecond)" style="width:120px"/>
#Html.HiddenFor(m => m, new { #class = "generatedZipField"})
</div>
<script type="text/javascript">
jQuery(function ($) {
$('#(zipAreaId) #zipcodefirst').autotab({ target: '#(pName)codesecond', format: 'numeric' });
$('#(zipAreaId) #zipcodesecond').autotab({ previous: '#(pName)codefirst', format: 'numeric' });
$('#(zipAreaId)').zipcode();
});
</script>
And i use it like this:
[UIHint("ZipCode")]
[Display(Name = "Zip Code")]
public string Zip { get; set; }
Like you see in my template i got two fields whats not included in the model.
It is #zipcodefirst and #zipcodesecond.
What i need to achieve is to have two separate fields for full us zip code.
When user fill both fields im using jquery widget for merging them into one string and inserting it into hidden field in template. after form submited value in hidden field getting sent into server.
Whats the problem?
I need to add mvc unobtrusive validation for them two fields whats not in the model #zipcodefirst and #zipcodesecond.
validation rules
zipcodefirst field must be filled in first
then zipcodefirst field is filled you can fill second field
second field must have 4 digits in it
first field must have five digits
cant fill second field while first one is empty or incorectly filled
Im strugling with validation part for quite a while now.... :(
How i could achieve that thru mvc3 unobtrusive validation tools?
any help will be highly apreciated guys.
Add unobrusive data data validation on the textbox by adding data-val="true" and use a regular expression for your zip code.
<input type="text" data-val="true" data-val-regex="Invalid zip code format" data-val-regex-pattern="YOUR REGEXP HERE" />
UPDATE
If you also want it to be required you can add the data-val-required attribute.
<input type="text" data-val="true" data-val-requred="Zip code is required" data-val-regex="Invalid zip code format" data-val-regex-pattern="YOUR REGEXP HERE" />
More information about validation in MVC 3:
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

Resources