I try to use a RegexValidator with a CharField, but I can't make it work...
class Configuration(models.Model):
name = models.CharField(verbose_name=u'Name', validators =
[RegexValidator(regex="[a-z]", message="Not cool", code="nomatch")])
I then just register it with
admin.site.register(Configuration)
But then in the admin forms, it accepts any possible name... Is the validation system suppose to work like that, or am I missing something ?
Your current regex checks that your value contains a single character from a-z. So it allows a, but it also allows a1.
Try changing the regex to:
regex=r"^[a-z]+$"
By including ^ and $ to mark the beginning and end of string, you make sure that your string contains only characters from a-z. The + allows multiple characters.
Related
I have a Flutter TextFormField for email with input formatter as below.
var emailAddressFormatter = FilteringTextInputFormatter.allow(RegExp(
r"[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+"));
The problem is, when trying to input any character in the field it does not allow. The regex looks fine to me. When the formatter is removed the field accepts any character with any format. What am I going wrong?
The issue is that the FilteringTextInputFormatter that you're using rejects anything that does not match your regex. When you enter just a single character, it does not match your regex, so the character is rejected.
I know little about regex so I'm not sure if it's possible, but you would need a regex that would be able to match every string as you type e.g. a, am, amani#, amani#gmail.com.
I would personally not try to do filtering such as this. Instead, I would just allow all valid characters that are valid in email addresses to be present in the email and not enforce the specific format with the # and .. Then I would use a validator to check that the email is valid upon form submission.
If you don't like the alternate solution I proposed above and you can't use regex, you can make your own input formatter quite easily with TextInputFormatter.withFunction.
I am new to Python, Django 1.9 and overall regular expressions. So I am trying to write something like this within urls.py
search/doc_name/language/?id
where doc_name, allow for any name/case/length etc. like so: 'My Fave Doc 12'
where language, allow two letters like so: 'en'
where id, allows only numbers.
This is what I have, can someone point out where I went wrong?
url(r'^search/[\w-]+/[a-z]{2}+/(?P<id>[0-9]+)$', '....
The doc_name doesn't allow spaces. Add a space in the character set if you want one. Make sure you put it before the dash ([\w -]+). If other whitespaces are allowed, used \s instead ([\w\s-]+).
Also the language would currently match any even amount of letters. Remove the + and leave only [a-z]{2}. + means repeat one or more times, anything is matched only once by default.
You should really avoid to have spaces in you URL, I suggest the following:
url format: /search/<doc_name>/<id>/?lang=<language>
in urls.py:
url(r'^search/(?P<doc_name>[\w]+)/(?P<id>[0-9]+)/$'), your_view)
in views.py:
lang = request.GET.get('lang', 'en')
doc_name = request.POST.get('doc_name')
id = request.POST.get('id')
I am using TinyMCE in my Django Admin site. I need to validate that no disallowed HTML Tags get submitted. This is what I tried:
1) Validation Method
def check_for_invalid_html_tags(value) :
compiled_regex = re.compile('<(?!/?(p|div|ul|li)(>|\s))[^<]+?>')
if compiled_regex.match(value):
raise ValidationError('Invalid Tags')
2) Validation Rule
content = tinymce_models.HTMLField(validators=[check_for_invalid_html_tags])
This does not seem to work, as any submission is let through as valid. When I change the tinymce_models.HTMLField to models.TextField, the rule works perfectly. Thus I believe that the issue is as a result of TinyMCE.
Can anybody help?
I read the doc and there is a slight difference between match and search
match:
If zero or more characters at the beginning of string ...
search:
Scan through string looking for the first location ...
search() vs. match()
since what your are looking for might be everywhere in your string you need to use search instead of match. An other point, you might neeed to set the fag re.S or re.DOTALL since you might have newline in your input.
Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.
So here is the check_for_invalid_html_tags in a functor and a working solution.
import re
class CheckForInvalidHtmlTags(object):
compiled_regex = re.compile('<(?!/?(p|div|ul|li)(>|\s))[^<]+?>')
def __call__(self, value):
if self.compiled_regex.search(value):
print 'error'
else:
print 'ok'
c = CheckForInvalidHtmlTags()
c('test test <a>test<a> test') # print error
c('test <p> test</p>') # print ok
c('test<a> test</a><p>test</p>test') # print error
Your validation method must actually be a validator, which has special methods like __call__. Use one of django's core validators, like the regex validator.
from django.core.validators import RegexValidator
check_for_invalid_html_tags = RegexValidator(
regex=''<(?!/?(p|div|ul|li)(>|\s))[^<]+?>'',
message='Invalid Tags',
code='invalid_content'
)
Then in your model:
content = tinymce_models.HTMLField(validators=[check_for_invalid_html_tags])
When I post a value from my page an extra string is create and I would like to remove the 'pattern = "' is there a tag i could use or replace function i can use to remove pattern =" and the ending ". Please find below scenario:
pattern = "apple"
Desired output
apple
I tried using but to no success.Is there another method i could use newbie at django python.
{{ pattern|split }}
Write a custom templatetag and use a regular expression (a capture group would do the trick) to replace the desired part.
If the quotation marks are added to your string when you are submitting the form, you could use the .strip() method when accessing the POST data. You can also specify what characters you want to remove. Check it out here: http://docs.python.org/2/library/stdtypes.html
I'm trying to pass a 'string' argument to a view with a url.
The urls.py goes
('^add/(?P<string>\w+)', add ),
I'm having problems with strings including punctuation, newlines, spaces and so on.
I think I have to change the \w+ into something else.
Basically the string will be something copied by the user from a text of his choice, and I don't want to change it. I want to accept any character and special character so that the view acts exactly on what the user has copied.
How can I change it?
Thanks!
Notice that you can use only strings that can be understood as a proper URLs, it is not good idea to pass any string as url.
I use this regex to allow strings values in my urls:
(?P<string>[\w\-]+)
This allows to have 'slugs; in your url (like: 'this-is-my_slug')
Well, first off, there are a lot of characters that aren't allowed in URLs. Think ? and spaces for starters. Django will probably prevent these from being passed to your view no matter what you do.
Second, you want to read up on the re module. It is what sets the syntax for those URL matches. \w means any upper or lowercase letter, digit, or _ (basically, identifier characters, except it doesn't disallow a leading digit).
The right way to pass a string to a URL is as a form parameter (i.e. after a ?paramName= in the URL, and with special characters escaped, such as spaces changed to +).