Am new to DJANGO, How to get clean data? - django-forms

My models```
regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A- Z |a-z]{2,}\b'
class Enquiry(models. Model):
f name = models. Char Field (max_ length=100,null=True, blank=True)
l name = models .Char Field(max _length=100, null=True, blank=True)
email = models .Email Field(max _length=100, null=True, blank=True)
p number = models .Integer Field(null=True, blank=True)
b name = models .Char Field(max _length=13, null=True, blank=True)
description = models .Text Field(max_ length=150, null=True, blank=True)
time = models .Date Time Field(auto_ now_ add = True, blank = True)
def __ s t r __(self):
return s t r (self .f name)
def get _absolute _u r l(self):
return reverse('Enquiry', a r g s=[s t r(self.id)])
my views
def contact(request):
form _class = Enquiry form
form = form _class(request .POST or None)
if request .method=="POST":
if form.is _valid():
# form = form_ class(request. POST or None)
# f name = form. cleaned _data[f name]
# l name = form .cleaned _data['l name']
# email = form .cleaned_ data['email']
# p number = form. cleaned_ data['p number']
# b name = form .cleaned _data['b name']
# description = form .cleaned _data['description']
# return Http Response Redirect('/thanks/')
print(form)
form. Save()
messages .success(request, "Hi your information has been shared successfully")
return render(request, 'base/contact.html')
else:
form=Enquiry form()
context={'form':form}
return render(request, 'base/contact.html', context)
my Forms
from dataclasses import fields
from django import forms
from django.forms import ModelForm
from .models import Enquiry
from DJANGO . c o n t ri b .p o s t g r e s. forms import Simple Array Field
from DJANGO .core .exceptions import Validation Error
class Enquiry form(forms .Model Form):
f name = forms. Char Field(label="First Name", widget =forms .Text Input(a t t r s=
{
'class': 'form-control bg-light',
'size': 10,
'placeholder': 'First name',
'style': 'max-width: 300px;',
'style': 'border: none',
}
))
l name = forms .Char Field(label="Last Name", widget =forms .Text Input(a t t r s=
{
'class': 'form-control b g-light',
'size': 10,
'placeholder': 'Last name',
'style': 'max-width: 300px;',
'style': 'border: none',
}))
email = forms .Email Field(label="Email Id", widget =forms .Text Input(a t t r s=
{
'class': 'form-control bg-light',
'size': 10,
'placeholder': 'Valid Email Id',
'style': 'max-width: 300px;',
'style': 'border: none',
}))
p number = forms .Char Field(label="Phone Number", widget =forms .Number Input(a t t r s=
{
'class': 'form-control b g-light',
'size': 10,
'placeholder': 'Valid Phone No',
'style': 'max-width: 300px;',
'style': 'border: none',
}))
b name = forms. Char Field(label="Business Name", widget =forms .Text Input(a t t r s=
{
'class': 'form-control b g-light',
'size': 10,
'placeholder': 'Business Name',
'style': 'max-width: 300px;',
'style': 'border: none',
}))
description = forms. Char Field(widget=forms .Text area(a t t r s=
{
'class': 'form-control b g-light',
'placeholder': 'B r e if Shortly',
'style': 'border: none',
}))
class Meta:
model = Enquiry
fields = ['f name', 'l name', 'email' ,'p number', 'b name', 'description']
def clean(self):
#run the standard clean method first
cleaned _data=super(Enquiry form, self).clean()
f name = cleaned _data. get(f name)
l name = cleaned_ data .get(l name)
email = cleaned _data. get(email)
p number = cleaned _data. get(p number)
#check if passwords are entered and match
if f name == '' and l name =='' and email=='regex' and p number == 10:
return ('Please Fill The Form Carefully')
else:
raise forms .save("Your Details Shared!")
#always return the cleaned data
return cleaned data
how to get clean data … any suggestions will be help ful
Please suggest how to get clean data. in DJANGO form

Related

React Quill custom module value

I'm trying to create a custom module that attaches a class to the html element and uses the value that is inside the static create function to add it to the dataset.
so what I do is:
write some text
click the button
Expected Behaviour
:
The text gets wrapped in a bold tag with class "bold" and data-id=1
Result:
The text gets wrapped in a bold tag with
class "bold"
data-id=1.
Then the Placeholder create function is called once again with value = true, so the value changes to
class "bold"
data-id=true.
Does anybody know why this happens? Why is the Placeholder create function called twice? Also, I suspect this is something related to react, because I tried it on a simple js example and this doesn't happen
import ReactQuill,{Quill} from 'react-quill'
import Bold from "./Bold.ts"
Quill.register(Bold);
const Editor = () => {
const ref = useRef();
const [value, setValue] = useState("");
const modules = {
toolbar: [
[{ 'header': [1, 2, false] }],
['bold', 'italic', 'underline','strike', 'blockquote'],
[{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
[{ 'color': [] }, { 'background': [] }],
['clean']
],
}
const onChange = (content:any, delta:Delta) => {
setValue(content)
}
useEffect(()=>{
console.log("value is changing:", value)
},[value])
// #ts-ignore
const format = ()=>ref.current.editor.formatText(0,ref.current.editor.getText().length,"mybold", 1)
return (
<div>
<Button onClick={format} >style me</Button>
<ReactQuill ref={ref as LegacyRef<any>} modules={modules} theme="bubble" value={value} onChange={onChange}/>
</div>
);
}
Bold.ts
import Quill from "quill";
let Inline = Quill.import('blots/inline');
export default class Bold extends Inline {
static create(value:any){
const node = super.create()
console.log("value", value)
node.setAttribute("class","bold")
node.dataset["id"]= value
return node
}
}
Bold.blotName = 'mybold';
Bold.tagName = 'bold';

How to setState of array of Object value and toggle the count to either 1 or 2 on click

I want to update the state of value in an array of objects on click, the value will toggle between 1 and 2, once clicked if the existing value is 1 it will update it 2 on click, and if 2 it will update it 1. The value must change for the clicked object only and not all objects.
import React, {useRef, useState} from 'react'
import {BsThreeDots, BsBookmark, BsBookmarkFill} from 'react-icons/bs'
export const TextQuoteCard = () => {
const [textQuote, setTextQuote] = useState([
{
userId: '123',
userName: 'sample',
userImageUrl: 'https://qph.fs.quoracdn.net/main-thumb-ti-406-100-gtkoukgmmuzegaytlmtaybgrsoihzyii.jpeg',
quoteId: 'TQ119',
postDateTime: '28 June at 8:20',
quoteAuthorId: '123',
quoteAuthorName: 'john len',
quoteCategory: 'Motivational',
quoteType: 'textQuote',
quoteText: 'If there’s no market, then it may not be the best thing to do. Entrepreneurship is about finding market opportunities, or creating opportunities. If there’s no market, then you need to grow one',
quoteImageUrl: '',
// 1 = yes, 2 = no
bookmarkStatus: 1,
likesCount: 3300,
commentsCount: 123,
overallShareCount: 1203,
fbShareCount: 423,
twtShareCount: 1232,
waShareCount: 1023,
viewCount: 1923,
isSelected: null
}
])
const handleBookmark = i => {
let bookmarkStatus = [...textQuote]
let bookmark = bookmarkStatus[i].bookmarkStatus
console.log('before update' , bookmark)
if(bookmark === 1) {
bookmark = 2
} else if(bookmark === 2){
bookmark = 1
}
setTextQuote(bookmarkStatus)
console.log('after update', bookmark)
}
return(
<div>
{
textQuote.map((quote, index) => (
<div className="QuoteCardPrimaryContainer" key={quote.quoteId}>
className="QuoteCardAuthorFollowButtonActionContainer">
<span className="QuoteCardAuthorFollowButtonActionSpan"
onClick={() => handleBookmark(index)}>
<span className={quote.bookmarkStatus === 1 ?
'bookmarkButtonContainer activeBookmark':
'bookmarkButtonContainer'}>
{quote.bookmarkStatus === 1 ? <BsBookmarkFill/> :
<BsBookmark/>}
</span>
</span>
</div>
))
}
</div>
)
}
First get the object at that index where the bookmarkStatus has to be updated. Then using splice method you can replace with the updated object.
const handleBookmark = i => {
let quoteObj = {...textQuote[i]};
let bookmark = quoteObj.bookmarkStatus;
console.log('before update', bookmark);
if (bookmark === 1) {
quoteObj.bookmarkStatus = 2;
} else if (bookmark === 2) {
quoteObj.bookmarkStatus = 1;
}
textQuote.splice(i, 1, quoteObj)
console.log(textQuote);
setTextQuote([...textQuote]);
console.log('after update', textQuote[i].bookmarkStatus);
};
Hope this helps.

RxJS observe an object

I am new to RxJS so I apologize for the newbie question.
I have a local javascript object defined as:
model.user = {
firstName: 'John',
lastName: 'Smith'
}
I am binding each property to an input control where the user can change the values. I would like to be able to observe this object and capture the event when the value of any of the properties change.
Is this achievable with RxJS?
Thanks.
Instead of using an object, you can store your entire state as Observable.
Here is the example code (something similar to what people do in redux):
var fnameInput = document.getElementById('fname');
var lnameInput = document.getElementById('lname');
var jsonPre = document.getElementById('json');
var onFirstName$ = Rx.Observable.fromEvent(fnameInput, 'input');
var onLastName$ = Rx.Observable.fromEvent(lnameInput, 'input');
var initialState = {
firstName: '',
lastName: '',
};
var state$ = Rx.Observable
.merge(
onFirstName$
.map(e =>
state => Object.assign(
state,
{ firstName: e.target.value }
)
),
onLastName$
.map(e =>
state => Object.assign(
state,
{ lastName: e.target.value }
)
)
)
.scan(
(state, makeNew) => makeNew(state),
initialState
)
.startWith(initialState);
state$
.subscribe(state => {
jsonPre.innerHTML = JSON.stringify(state, null, 2);
});
<input id="fname" type="text">
<input id="lname" type="text">
<pre id="json"></pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>

Accessing Nokogiri element children

Upon parsing an html table, I am able to get the first row of the table as a Nokogiri element.
2.2.1 :041 > pp content[1]; nil
#(Element:0x3feee917d1e0 {
name = "tr",
children = [
#(Element:0x3feee917cfd8 {
name = "td",
attributes = [
#(Attr:0x3feee917cf74 { name = "valign", value = "top" })],
children = [
#(Element:0x3feee917ca60 {
name = "a",
attributes = [
#(Attr:0x3feee917c9fc {
name = "href",
value = "/cgi-bin/own-disp?action=getowner&CIK=0001513362"
})],
children = [ #(Text "Maestri Luca")]
})]
}),
#(Text "\n"),
#(Element:0x3feee917c150 {
name = "td",
children = [
#(Element:0x3feee917d794 {
name = "a",
attributes = [
#(Attr:0x3feee9179fb8 {
name = "href",
value = "/cgi-bin/browse-edgar?action=getcompany&CIK=0001513362"
})],
children = [ #(Text "0001513362")]
})]
}),
#(Text "\n"),
#(Element:0x3feee91796a8 {
name = "td",
children = [ #(Text "2016-09-04")]
}),
#(Text "\n"),
#(Element:0x3feee9179194 {
name = "td",
children = [ #(Text "officer: Senior Vice President, CFO")]
}),
#(Text "\n")]
})
=> nil
This is the content from the row:
Maestri Luca 0001513362 2016-09-04 officer: Senior Vice President, CFO
I need to access the Name, Number, Date and Title from the Nokogiri element.
One way of doing it is as below:
2.2.1 :042 > pp content[1].text; nil
"Maestri Luca\n0001513362\n2016-09-04\nofficer: Senior Vice President, CFO\n"
However, I am looking for a way of accessing the elements individually, not as one long sting with newline characters. How can I do it?
name, number, date, title = *content[1].css('td').map(&:text)
if content[1] is a tr, content[1].css('td') will find all td elements beneath it, .map(&:text) will call td.text for each of those td and put it into an array, which we than splat with * so we can do multiple assignment.
(Note: next time, please include the original HTML fragment, not the Nokogiri node inspect result.)

How to put an XML document into another with Nokogiri

I want to include an xml document with arbitrary user provided data in another one using nokogiri.
I have tried Node#add_child and encountered a problem: nokogiri looses namespace definition if there is a uri in child_doc that is also present in main doc but with a different prefix.
Example:
doc = Nokogiri::XML %(
<s:rack xmlns:s="urn://shelf">
<s:shelf></s:shelf>
</s:rack>
)
child_doc = Nokogiri::XML %(
<m:shelf xmlns:m="urn://shelf">
<m:book></m:book>
</m:shelf>
)
doc.root.add_child(child_doc.root)
doc.to_xml
# =>
# <s:rack xmlns:s="urn://shelf">
# <s:shelf/>
# <!-- namespace for prefix m is not declared! -->
# <m:shelf>
# <m:book/>
# </m:shelf>
# </s:rack>
Namespace for prefix m is lost.
Here is the resulting doc object, pretty printed:
#(Document:0x1b2ce28 {
name = "document",
children = [
#(Element:0x1b327c4 {
name = "rack",
namespace = #(Namespace:0x1b320a8 { prefix = "s", href = "urn://shelf" }),
children = [
#(Text "\n "),
#(Element:0x1b45f90 { name = "shelf", namespace = #(Namespace:0x1b320a8 { prefix = "s", href = "urn://shelf" }) }),
#(Text "\n "),
#(Element:0x1a9e5d8 {
name = "shelf",
namespace = #(Namespace:0x1a87450 { prefix = "m", href = "urn://shelf" }),
children = [
#(Text "\n "),
#(Element:0x1a41dec { name = "book", namespace = #(Namespace:0x1a87450 { prefix = "m", href = "urn://shelf" }) }),
#(Text "\n ")]
})]
})]
})
As you can see internally namespaces in added nodes are correct but they are serialized wrong. How do I get nokogiri to save them in the resulting xml?

Resources