Can I change Django's auth_user.username field to be 100 chars long without breaking anything? - django

Before somebody marks this question as a duplicate of this question Can django's auth_user.username be varchar(75)? How could that be done? or other such questions on SO, please read this question. The question I linked to asks this question precisely but unfortunately the answers don't address the question that was asked.
Can I change the auth_user.username field to be 100 characters long by doing the following:
Run ALTER table in DB for the username field
Change the max_length here: username = models.CharField(_('username'), max_length=30, unique=True, help_text=_("Required. 30 characters or fewer. Letters, numbers and #/./+/-/_ characters"))
Would it break anything in Django if I were to do this?
That this will break when I update Django to a higher version is not a problem. I'm also not looking at writing other authentication methods.I just want to know if I would break anything if I were to do this.

You need to monkey-patch max-length in several places: model-field's description, form-field's description and max-length validators. Max-length validators are attached to form-fields as well as model-fields.
Here is a code snippet, which will patch everything:
https://gist.github.com/1143957 (tested with django 1.2 and 1.3)
Update:
Good news! Since django 1.5 you can override user model: Customizing the User model

There is no harm in doing that.
Just change the length in the model and in the database :)

Create a user profile model, add your very-long-username field there, and use it. of course this renders the genuine username field useless, but it is much better than hacking Django code, which will get you into trouble when you need to upgrade it.

For me, the code below works and is simple well.
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
....
# your custom fields
MyUser._meta.get_field('username').max_length = 255 # or 100
after you can run your migration

If you change the database manually as well as the model accordingly then there should be no problem.
You can also change back otherwise, and I would say make a backup just in case but I'm not sure its even necessary

for future needs this is the best and easiest way i found out:
https://github.com/GoodCloud/django-longer-username

Another solution is to change your authentication code. When a new user signs up, they enter an email, you save this in the email field so you have it, and if their email is >30 characters, you shorten it before putting it into the user field. Then, change your login authentication for new logins.

Related

Default regex django uses to validate email

recently, I started playing with Django and created a custom form for user registration. In that form to create the field for email I use something like
email = forms.EmailField()
I observed that address such as a#a.a is considered invalid by the form. Of course this is a nonsense email address. Nonetheless, I wonder how does Django checks for validity.
I found some topics on the net discussing how to check for validity of an email address but all of them were providing some custom ways. Couldn't find something talking about the django default validator.
In their docs on the email filed they specify
Uses EmailValidator to validate that the given value is a valid email address, using a moderately complex regular expression.
However that's not very specific so I decided to ask here.
For anyone also interested in this, I would suggest looking up the implementation (django.core.validators) as was kindly suggested by iklinac in the comments.
In it, there is not just the source but also mentions about standards that were used to derive regexes that check if domain and literal have valid format.
us should check docs here https://www.geeksforgeeks.org/emailfield-django-forms/#:~:text=EmailField%20in%20Django%20Forms%20is,max_length%20and%20min_length%20are%20provided.
if u wanna check validation use clean function like this :
from django.forms.fields import EmailField
email = EmailField()
my_email = "a#a.a"
print(email.clean(my_email))
if your email is valid then this func return value else return validation error

Django: Order of validation in Models

Recently I found out that its possible to define Django form validation directly in the models.py file. This can be done the following way:
fev1_liter = models.DecimalField(validators=[MaxValueValidator(8.2),
MinValueValidator(0.3)],
max_digits=3, decimal_places=2)
This is an awesome alternative to validation in forms.py, but I do have a very annoying problem:
How can I control in which order the validation is executed?
In this example Django will first validate if the inputs digits is in the format x.xx and thereafter min and max value. This results in some very confusing error messages.
Thanks in advance!
For each model field, field.clean() first performs field validation via field.validate(), then via field.run_validators(), validators are called in order they are returned from the field.validators iterator.
This makes sense, because in the general case you can expect your validators to fail if the field validation failed, so it makes for easier debugging. Remember that field validators are non-obligatory, so field.validate() takes precedence. If you want to change the behavior, you'll have to create your own Field classes and override the field.clean() behavior.
You can inspect the field sources for more details.

In Django, how can I calculate or update certain model fields BEFORE any validation happens?

So I'm new to Django...
First some background on how we do things now. We have a custom php system but I am constructing an improved inventory management system in django using only the admin interface. We store part numbers, and it is essential that we do not store duplicates. Part numbers can sometimes be entered with hypens, periods, spaces, etc. We need to be sure that duplicate parts are not added no matter what kind of formatting is entered. With our existing non-django system, we use a regex to strip anything from the string that is not a-zA-Z0-9. The actual entered part number is persisted, and the cleaned number is persisted to the db as well. Then when someone is adding a new part or even searching for a part, this cleaned version of the part number helps to avoid this ambiguity. We do the same for the manufacturer name.
My way of emulating this in django was to add the part_number_clean field along with the part_number field to the model. Then I overrode the save method to calculate the clean part number like so (manufacturer as well):
def save(self, *args, **kwargs):
self.manufacturer_clean = re.sub(r'[^a-zA-Z0-9]', '', self.manufacturer).lower()
self.part_number_clean = re.sub(r'[^a-zA-Z0-9]', '', self.part_number).lower()
super(CatalogProduct, self).save(*args, **kwargs)
The problem is, I need to unique on a combination of part number and manufacturer:
class Meta:
unique_together = ('part_number_clean ', 'manufacturer_clean ')
When I try to save a duplicate record, I get a database integrity violation. So it seems like django is evaluating the unique fields before the save function is called (which makes sense). I just need to know how or which method I should override to calculate these fields BEFORE any validation.
Additionally, I am interested in adding a third field to the unique_together mix that may or may not be filled out. If it is not filled it will just have an empty default value. I hope this will not cause any issues.
It would also be great if when the user tabbed-out of the manufacturer and part number fields, and both were not empty, some js would see if that product exists already, and offer the user the option to click a button and be whisked away to that record, before they waste their time filling out the rest of the data only to find that it already exists. I'm guessing this lies way outside the realm of the admin interface without serious hacking. Is there any way to somehow integrate this with the admin interface? Its working great for me up till now...
I figured it out. I'm posting the answer for anyone else that is curious. This was actually very simple in the end to implement in the model. All one needs to do is implement (override?) the clean() method of the model. In the method, I calculate and set my special fields, then be sure to call self.validate_unique() after. Works like a charm! No need to raise any exceptions, the form will display the error on top perfectly. Doing this in the save method will not work, as the exception cannot be thrown by your code or django at that point. Here is the code:
class CatalogProduct(models.Model):
manufacturer = models.CharField(max_length=100)
manufacturer_clean = models.CharField('Manufacturer',max_length=100,blank=True,editable=False)
part_number = models.CharField(max_length=100)
part_number_clean = models.CharField('Part number',max_length=100,blank=True,editable=False)
def clean(self):
# Calculate manufacturer_clean and part_number_clean
self.manufacturer_clean = re.sub(r'[^a-zA-Z0-9]', '', self.manufacturer).lower()
self.part_number_clean = re.sub(r'[^a-zA-Z0-9]', '', self.part_number).lower()
self.validate_unique()
The model is only responsible for describing data and how that data should be represented between your Python and database environment. It's because of this atomic role that models don't care about validation and what you've just went in there and introduced it.
You need a model form. It can clean the manufacturer and part number and also ensure that uniqueness constraints are satisfied as part of the validation process.

Understanding User class in django

I create a user in my view.py using this simple code.
if not errors:
user = User.objects.create_user(username, email, password)
user.save()
Except for the validation, there is nothing that I do to the username and password values before creating the object.
But I find this in the User class in Django API. I don't know how to use the help text. If it is help text what does it print? How do I find the default values of algo, salt and hexdigest?
password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the change password form."))
"If it is help text what does it print?"
-> it prints exactly this: Use '[algo]$[salt]$[hexdigest]'
when you create a user, it will automatically call make_password(password[, salt, hashers])
which: Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text. Optionally, you can provide a salt and a hashing algorithm to use, if you don't want to use the defaults (first entry of PASSWORD_HASHERS setting). Currently supported algorithms are: 'pbkdf2_sha256', 'pbkdf2_sha1', 'bcrypt' (see Using bcrypt with Django), 'sha1', 'md5', 'unsalted_md5'
are you facing any problems with this?
create_user will automatically generate password hash and it will create user in the database (thus you don't need that user.save())
See docs on creating users.
The help text is basicly just code for the message that shows up in the django admin, when editing a User object. It's meant to explain to someone looking at the edit form, why the password field has something like sha1$12345$1234567890abcdef1234567890abcdef12345678 instead of the password that was set for that user. The reason is, of course that the password is hashed for security, and that representation holds all the information required to verify a user-typed password later.
The admin user edit form has a special page for editing passwords. If you want to edit the users password in your code use the set_password method of the User object, the check_password method is for verifying a supplied password.
The documentation for make_password has more information about the algorithms Django uses and can use. The default for Django <1.3 was sha1, Django 1.4 changed the default to PBKDF2. The default value for salt is a random string (it's there so that two identical passwords don't look the same in the database). Hexdigest is the value of the password string and the salt string hashed with the hashing algorithm. You can read the details in the code on github.

Extending django-registration fields

I am trying to extend the fields in django-reg (with First name, last name and contact number). To this end, I have written an app (name=regfields), with the following contents:
http://dpaste.com/596163/
When I run syncdb, I see all the extra fields I have set up on the database, but, when I try and create an account, the extra fields I have given are not stored in my database.
What could be wrong?
Sorry, I am a django 101 user!
The indentation of the save() function in newforms.py looks off. Assuming that is not an error introduced by copying it into dpaste, that method is not a part of RegistrationFormZ.