In my database query which is executed with the sqlite3 module I insert a new row of data which includes a date field.
The problem is when getting todays date with datetime.date.today().strftime('%Y-%m-%d') which outputs '2023-02-06' (expected output), it changes inside the database to '2015'. Why does this happen?
This is a Django project so that is where i created the model for the database.
models.py
class User(models.Model):
...
date_joined = models.DateField('%Y-%m-%d')
...
database.py
def add_user(self, email, password):
date = datetime.date.today().strftime('%Y-%m-%d')
self.cursor.execute(f"""
INSERT INTO App_user ('username','email','password', 'email_preference', 'region', 'date_joined')
VALUES ('{username}', '{email}', '{password}', 'All', 'None', {date})
""")
self.con.commit()
You should not have the date field on the client side when you create the user. This field in Django is automatically saved in the database by defining DateField and registering every user.
You can also use the following code snippet to record the user's creation date as well as the date the user updated his profile.
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Related
I have this model in my Django application:
class ClubSession(models.Model):
location = models.CharField(max_length=200)
coach = models.ForeignKey('auth.User', on_delete=models.CASCADE)
date = models.DateTimeField(default=now)
details = models.TextField()
def __str__(self):
return self.location
This view implements it:
class SessionListView(ListView):
model = ClubSession
template_name = 'club_sessions.html'
context_object_name = 'all_club_sessions_list'
I'm trying to test the view. My test class has a setUp which creates a record:
def setUp(self):
ClubSession.objects.create(location='test location',
coach=User(id=1),
date='2020-06-01 18:30',
details='this is another test')
When I run my test I get this error:
IntegrityError: The row in table 'club_sessions_clubsession' with primary key '1' has an invalid foreign key: club_sessions_clubsession.coach_id contains a value '1' that does not have a corresponding value in auth_user.id.
A user with id 1 exists so how do I get this to work? I've tried adding the username but that didn't work either.
I would strongly advise not to use primary keys, especially since dispatching primary keys is the responsibility of the database, and thus that can differ between sessions.
Furthermore tests run on an independent database, so the data stored in the database you use in development or on production is not used.
Probably it is better to first create a user, for example:
from django.contrib.auth.models import User
# …
def setUp(self):
user = User.objects.create(username='foo')
ClubSession.objects.create(
location='test location',
coach=user,
date='2020-06-01 18:30',
details='this is another test'
)
I am trying to create a new Model to keep track of the current password and the most recent previous password used. I want it to look like this crude example:
ID --- CUR_PASS --- PREV_PASS
1 --- 123 --- 321
2 --- 456 --- 654
Is it possible to make the ID the username in my auth_user table?
Here is the class I have so far:
# class model to store previously used passwords
class oldPass(models.Model):
# username = models.ForeignKey('something') --> instead of ID?
current_pass = models.CharField(max_length=100)
prev_pass = models.CharField(max_length=100)
class Meta: # meta class to define the table name
db_table = "old_pass"
I am trying to make it so I can have the ID be the username and when changing the password in auth_user, check back to the old_pass table and compare the values making sure it is neither. If it is either of em, kick back an error.
My biggest issues are these:
I don't know how to import auth_user so I can assign the username to this new table
I don't know how to change the ID to be the username instead of numbers. (Would this be done using ForeignKey?)
I want to be able to compare the values to a passed in variable...
Example of #3:
- I want to execute User.set_password('pass') (so that the pass is hashed), I then want to compare this new password to 'current_pass' and 'prev_pass' before committing User.save(). If the password matches one of the passwords used, I want to abort.
I am using Django 1.9 and Python 2.7.13
UPDATE
So looking at the answers received and more info researched... This is my new class
from django.contrib.auth.models import User
# class model to store previously used passwords
class oldPass(models.Model):
# username = models.ForeignKey(User) --> instead of ID?
current_pass = models.CharField(max_length=100)
prev_pass = models.CharField(max_length=100)
class Meta: # meta class to define the table name
db_table = "old_pass"
from django.conf import settings, and settings.AUTH_USER_MODEL is your auth_user model.
Use a custom id like this id = models.CharField(primary_key=True). But mostly, ID should be a meaningless field.
You can check the password before execute User.set_password('pass').
models.py
class oldPass(models.Model):
user = models.ForeignKey(`settings.AUTH_USER_MODEL`)
current_pass = models.CharField(max_length=100)
prev_pass = models.CharField(max_length=100)
class Meta:
db_table = "old_pass"
views.py
if oldPass.objects.filter(user=user, pre_pass='pass').exists():
raise Error
user.set_password('pass')
user.save() #at the same time, update user's password in oldPass
In Django Project I am using two databases, first is MySQL second is PostgreSQL, in PostgreSQL I have only geometric values but I need users too, so In models I have:
from django.conf import settings
from django.contrib.gis.db import models
class geo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
location = models.PointField()
Everything is working fine but when I try to save, user field shows an error user instance with id 1L does not exist So what could be the answer? Is problem coming from the router.py file?
The error comes from this line :
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
Here you are defining default=1 so when you are not assigning any user instance to user field of geo model, default then user field is taking integer default value, but it is expecting a user instance.
There are two solutions :
At the time of creation of new instance/record of geo model, add a user instance to it.
Or
Use blank=True, null=True in your geo model,like this:
class geo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
location = models.PointField()
I would personally recommend the second method. Thanks.
I have a model with start_date and end_date. I would like to add a list of users at the bottom so that an admin can pick from a list of users that are associated with this model.
This is how the model looks in admin panel at the moment
My model looks like this in models.py
class MyPeriod(ValidateOnSaveMixin, models.Model):
start_date = models.DateField(unique=True)
end_date = models.DateField()
In admin.py I tried adding filter_horizontal like this but it gave me errors
class MyPeriodAdmin(admin.ModelAdmin):
list_display = ('start_date', 'end_date',)
filter_horizontal = ('user',)
The value of 'filter_horizontal[0]' refers to 'user', which is not an
attribute of 'MyPeriod'.
Your current model does not contain an association between period and users. You have to specify a ForeignKey relation with the User model, such as:
from django.conf import settings
...
class MyPeriod(ValidateOnSaveMixin, models.Model):
start_date = models.DateField(unique=True)
end_date = models.DateField()
user = models.ForeignKey(settings.AUTH_USER_MODEL)
After this addition (and applying migrations to reflect the changes to the actual database) you will be able to assign Users to your MyPeriod model.
I am stuck with an Error with models.DateField()
First, I did this.
models.py
from datetime import date, datetime
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
birthdate = models.DateField()
Then, I got,
$ python manage.py makemigrations
You are trying to add a non-nullable field 'birthdate' to user_profile without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
So, I did,
models.py
from datetime import date, datetime
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
birthdate = models.DateField(default=date.today)
Then,
$ python manage.py migrate
django.core.exceptions.ValidationError: ["'' は無効な日付形式です。YYYY-MM-DD形式にしなければなりません。"]
The error means, like "'' is invalid for formate of date. You should change to YYYY-MM-DD".
How should I change this code?
Thank you.
/// additional ///
If I can, I don't want to INSERT date INTO birthdate field. But it seems I have to. Can I let it blank?
birthdate = models.DateField(null=True, blank=False)
didn't work.
Python 3.5.1
Django 1.9.1
Sounds like your migration files are messed up. When you do a migration, django would create a migration file that records what you did. So in short, you changed your model code many times, but you never changed your migration file, or you are creating duplicate migration files.
The following should be what you want,
birthdate = models.DateField(null=True, blank=True)
But as you noticed, cleaning up all migration files that related to this change and create a new one should solve the problem.
What you have tried should work:
birthdate = models.DateField(null=True, blank=False)
This allows the database to accept null values (which it does during the migration) and blank means that django will not accept empty values from forms.
Make sure to delete migrations that have been made but not applied. Also try deleting all .pyc's in your project.
Try this,
birthdate = models.DateField(null=True, blank=False)