How to Reset form field after submit in HTMX - django

I'm tried to reset form field after submit the data in HTMX.
Please guide me how to do.

You can do with with htmx beforeswap https://htmx.org/docs/#modifying_swapping_behavior_with_events
To make the example below work django view must return HttpResponse(status=204)
htmx.on("htmx:beforeSwap", (e) => {
if (!e.detail.xhr.response) {
var title = $('#id_title');
if (title) {
title.val('');
}
}
})
Tutorial how to work with django forms and htmx https://blog.benoitblanchon.fr/django-htmx-modal-form/

Related

serializer.save() not saving data to admin database

So, i was making a simple Web app in which i would get in data from user using React JS Front-end Interface and Forms. Django stays in the background where i have made CRUD functions.
My app lets user to create, edit, delete and view the data inputted.
Edit and View work perfectly fine but create has been making a problem for me. There is no error in the browser console or django terminal but the React JS front-end change does not reflect in the Django Admin.
Now, handleChange simply listens to the change made in the HTML form. Active Record is my current form in which new data is being added:
handleChange(e){
var value = e.target.value;
this.setState({
activeRecord:{
...this.state.activeRecord,
[e.target.name]:value
} }) }
handleSubmit() just connects my frontend submit button to Django's CRUD'S Create url. Finally, i set the current object state back to default.
handleSubmit(e){
e.preventDefault()
console.log('Item',this.state.activeRecord)
var csrftoken = this.getCookie('csrftoken')
var url = 'http://127.0.0.1:8080/DataCollection/create/'
fetch(url,{
method:'POST',
headers: {
'Content-type':'application/json',
'X-CSRFToken': csrftoken,
},
body:JSON.stringify(this.state.activeRecord)
}) .then((response)=>{
this.fetchTasks()
this.setState({
activeRecord:{
id: "",
full_name:"",
age:"",
gender:"",
weight:"",
height:"",
salary: "",
project_count: "",
job_domain: "",
experience: "",
no_of_jobs:"",
}
})
}).catch(function(error){
console.log('ERROR',error)
})
}
handleSubmit() just connects my frontend submit button to Django's CRUD'S Create url.
Please note that there is no error shown when i run it but 2nd line console.log in the handlSubmit() function shows the inputted values implying that my added data is reaching react js at least.
Thus, this makes me think there is some issue with the Django part and hence, i have posted this question in this subreddit.
Note: I am an aspiring data scientist who is to start his Master Studies in September 2020. Just wanted to add some Web App Development skills to my resume.
Any suggestion would be appreciated....
Create View:
#api_view(['POST'])
def createRecord(request):
serializer = InputValuesSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
b.) Serializer: serializers.ModelSerializer had to be this way. Got a gruesome error when i tried to use serializers.Serializer
class InputValuesSerializers(serializers.ModelSerializer):
class Meta:
model = InputValues
fields = 'all'
I've tried all the online resources and discussions but cannot find the solution. This is really frustrating as i can that the data is going where it's supposed to go, but only a single statement might me screwing things up.
I would really appreciate any help over this.

Django : View for submit?

It is a good way to create a view only for submit a form ?
For example :
Ajax send a form submitted to this specific view, this view validate the form and create a object in database and return a json response to Ajax.
It's ok to do like this ?
Because I'am afraid of users write directly the url to this specific view on browser...

How to remove/reset ember validation in form

I have a form inside a modal, that form allows user to update each model feild and I'm also using ember-validations to validate them, but then after successful saving or when a user closes/cancel the modal the form element still contain the class has-success, has-error, has-feedback classes, so how can I reset the form fields after every successful saving/cancel?
It's common practice create new Form instance instead of cleaning errors. For each opening form/modal you should create new form
form: computed(function() {
return Form.create({ });
}),
actions: {
onShow() {
this.notifyPropertyChange('form');
}
}

Django - How to stay on the same page without refreshing page?

I am using Boostrap modal fade window which renders Django form to update my database records. And what I fail to do is not to reload the page if the user has opened the Update window and did not change anything. It will be easier to get my idea if you look at the code below:
def updateTask(request, task_id):
#cur_usr_sale_point = PersonUnique.objects.filter(employees__employeeuser__auth_user = request.user.id).values_list('agreementemployees__agreement_unique__sale_point_id',flat=True)
selected_task = Tasks.objects.get(id=task_id)
task_form = TaskForm(instance=selected_task )
taskTable = Tasks.objects.all()
if request.method == 'POST':
task_form = TaskForm(request.POST,instance=selected_task)
if task_form.has_changed():
if task_form.is_valid():
# inside your model instance add each field with the wanted value for it
task_form.save();
return HttpResponseRedirect('/task_list/')
else: # The user did not change any data but I still tell Django to
#reload my page, thus wasting my time.
return HttpResponseRedirect('/task_list/')
return render_to_response('task_management/task_list.html',{'createTask_form':task_form, 'task_id': task_id, 'taskTable': taskTable},context_instance=RequestContext(request))
The question is, is there any way to tell Django to change the url (like it happens after redirecting) but not to load the same page with same data for the second time?
It's not trivial, but the basic steps you need are:
Write some javascript to usurp the form submit button click
Call your ajax function which sends data to "checking" view
Write a "checking" view that will check if form data has changed
If data have changed, submit the form
If not, just stay on page
This blog post is a nice walkthrough of the entire process (though targeted towards a different end result, you'll need to modify the view).
And here are some SO answers that will help with the steps above:
Basically:
$('#your-form-id').on('submit', function(event){
event.preventDefault();
your_ajax_function();
});
Call ajax function on form submit
Gotta do yourself!
Submit form after checking

how to update request.user in django?

I have an ajax call which sets
request.user.my_field = value
When the ajax succeeds, I reload the page with location.reload(True)
I expect the request.user.my_field in the view function is updated now but it has the old value.
How can I fix this?
EDIT
The ajax call:
$.ajax({
type: 'POST',
url: '{% url editor_select %}',
data: {'editor_type':$(this).val(),
success: function(response_data) {
location.reload(true);
}
}
});
The first view:
def editor_select(request):
"""
called when user changes editor type to post question/answer
"""
editor_type = CharField().clean(request.POST['editor_type'])
request.user.editor_type = editor_type
request.user.save()
The second view:
def second_view(request):
print 'ask, editor_type:', request.user.editor_type
I find AuthenticationMiddleware (which sets request.user to request), doesn't get called in between the ajax call and the location.reload()
so umm???
Save the model before exiting the view.
request.user.save()
Wow shoot me..
success: was inside data and it requested two pages in succession.