1. add form validation :
if you want your tweet must be no longer than 400 characters than you can add function in models.py as
class TweetForm(forms.ModelForm):
class Meta:
model=Tweet
fields=['content']
labels={'content':'enter your content'}
help_text={'content':'enter your content'}
error_messages={'content':{'required':'name is compulsory'}} #you can give extra error messages giving comma
widgets={'name':forms.TextInput(attrs={'class':'content','placeholder':'enter content'})}
#widgets={'password':forms.PasswordInput} for not showing password if any error occurs
def clean_content(self):
content=self.cleaned_data.get('content')
if len(content)>20:
raise forms.ValidationError("this tweet is too long")
return content
def clean content is content to filter the length
2.there is ajax request in your form from homepage :
you need to take care of reditrecting that error to your page thus to redirect that error
in views.py where ajax request or the normal request is there
def tweet_form(request, *args, **kwargs):
if request.method=="POST":
fm=TweetForm(request.POST)# this will send your all the data to modelform and create new form there
print(fm)
url_redirect=request.POST.get("url_redirect") #get name of input from home.html(for future use to redirect to home page if clicked on submit :action purpose)
print("post data is",request.POST) #normally Post request of form will send you all content inside form: i.e name and value: in the form of "name":["value"]
print("your form will redirect to",url_redirect) #normal printing to know what is happening
print(request.is_ajax()) #checking if the req is ajaax or not
if fm.is_valid():
content=fm.cleaned_data['content']
print(len(content))
fm=TweetForm()
obj_of_model=Tweet(content=content)
obj_of_model.save()
if request.is_ajax():
return JsonResponse(obj_of_model.serializer(), status=200) #it will go and will print to console and same is the thing for serializer concept :look upppp
if url_redirect!=None and is_safe_url(url_redirect,ALLOWED_HOSTS):
return redirect(url_redirect) #redirect is used to redirect to any url while in the middle of working
if fm.errors:
if request.is_ajax():
return JsonResponse(fm.errors,status=400)
else:
fm=TweetForm()
return render(request, 'components/forms.html',{"form":fm})
if fm.errors function will handle the error and send error message as json format with status of 400
in display site i.e home.html
const tweet_control=(e)=>{
console.log("submitted")
const myform=e.target
console.log(myform)
e.preventDefault()
const myformdata= new FormData(myform)
for (const iterator of myformdata.entries()) {
console.log(iterator)
}
let method=myform.getAttribute("method")
let url=myform.getAttribute("action")
console.log(method,url)
const xhr=new XMLHttpRequest()
xhr.open(method,url,true);
xhr.setRequestHeader("HTTP_X_REQUESTED_WITH"," XMLHttpRequest") //normally no ajax is there so to pass ajax we use 2 of the
xhr.setRequestHeader("X-Requested-With"," XMLHttpRequest") //and it is done so that the response from django views->tweet_form wont return all the html page :
xhr.onload= function(){
if (xhr.status===200) {
let response=JSON.parse(xhr.responseText)
console.log(typeof response)
console.log(response)
let id=response.id
let content=response.content
let likes=response.likes
let tweet_to_append=tweet_render(id,content,likes)
let oghtml=div.innerHTML
div.innerHTML=tweet_to_append + oghtml
myform.reset() //to reset the innerhtml value of form after clicking submit
}
else if(xhr.status===400){
console.log(xhr.responseText)
}
else if(xhr.status===500){
alert("there was some internal server error. i.e error in dango")
}
}
xhr.onerror=()=>{
alert("some error occurred this error is occurred due to failing of server and from home.html xhr ")
}
xhr.send(myformdata)
}
it will take response back and back response is handled by if else condition
else if (status===400):
error page will handle error and show error as json format if length>(condition)
elseif(status===500)
is the internal server error like in django app
if print(abc) without declaration is done than it will show this error
2. display actually in homepage that tweet is too long(focus on yelow text)
const tweet_control=(e)=>{
console.log("submitted")
const myform=e.target
console.log(myform)
e.preventDefault()
const myformdata= new FormData(myform)
for (const iterator of myformdata.entries()) {
console.log(iterator)
}
let method=myform.getAttribute("method")
let url=myform.getAttribute("action")
console.log(method,url)
const xhr=new XMLHttpRequest()
xhr.open(method,url,true);
xhr.setRequestHeader("HTTP_X_REQUESTED_WITH"," XMLHttpRequest") //normally no ajax is there so to pass ajax we use 2 of the
xhr.setRequestHeader("X-Requested-With"," XMLHttpRequest") //and it is done so that the response from django views->tweet_form wont return all the html page :
xhr.onload= function(){
if (xhr.status===200) {
let response=JSON.parse(xhr.responseText)
console.log(typeof response)
console.log(response)
let id=response.id
let content=response.content
let likes=response.likes
let tweet_to_append=tweet_render(id,content,likes)
let oghtml=div.innerHTML
div.innerHTML=tweet_to_append + oghtml
myform.reset() //to reset the innerhtml value of form after clicking submit
handle_error('',false)
}
else if(xhr.status===400){
let response_error= JSON.parse(xhr.responseText)
let actual_error_content=response_error.content
if (actual_error_content) {
handle_error(actual_error_content,true)
} else {
alert("some error occurred")
}
}
else if(xhr.status===500){
alert("there was some internal server error. i.e error in django")
}
}
xhr.onerror=()=>{
alert("some error occurred this error is occurred due to failing of server and from home.html xhr ")
}
xhr.send(myformdata)
}
let handle_error=(actual_error_content,display)=>{
let error_div=document.getElementById("error_message")
if (display===true) {
error_div.setAttribute("class","d-block alert alert-danger")
error_div.innerHTML=actual_error_content
} else {
error_div.setAttribute("class","d-none ")
console.log(error_div)
}
}
there is a div added to home.html to display the error
<h1 class="text-center">welcome to tweetme.to</h1>
<div id="error_message" class="d-none"></div>
<div class="row">
<div class="col-md-4 mx-auto col-10" >
<form class="form" method="POST" action="form" id="form">{% csrf_token %}
<input type="hidden" name="url_redirect" value="/">
<textarea class="form-control" name="content" placeholder="your tweet" required id="value"></textarea>
<button class="btn btn-primary" type="submit">tweet</button>
</form>
</div>
</div>
\
Comments
Post a Comment