need help to save different unique date in django - python

I am creating a app using django rest-framework to record mensuration date.I have to put a validation to date fields like if one date is already entered in database the app should avoid to enter same date which is already exist in database. Need help to do that

You can make use of a UniqueConstraint [Django-doc] where you include both the user and the date:
from django.conf import settings
class MyModel(models.Model):
date = models.DateField()
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
class Meta:
constraints = [
UniqueConstraint(fields=['user', 'date'], name='unique_date_per_user')
]
Prior to django-2.2, you can make use of unique_together [Django-doc]:
from django.conf import settings
class MyModel(models.Model):
date = models.DateField()
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
class Meta:
unique_together=(('user', 'date'),)

Related

HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'

Hello I had to rewrite my user model for add some filed, I used AbstractUser
My models:
It's on blog app:
class Article(models.Model):
author = models.ForeignKey(User , null=True, on_delete=models.SET_NULL , related_name='articles' , verbose_name='نویسنده')...
it's on account app:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_authour = models.BooleanField(default=False, verbose_name="وضعیت نویسندگی")
special_user = models.DateTimeField(default=timezone.now, verbose_name="کاربر ویژه تا")
def is_special_user(self):
if self.special_user > timezone.now():
return True
else:
return False
is_special_user.boolean = True
is_special_user.short_description = "وضغیت کاربر ویژه"
I imported my User view in this way:
from account.models import User
And I added this to my setting:
AUTH_USER_MODEL = 'account.User'
when I migrate I get this error:
blog.Article.author: (fields.E301) Field defines a relation with the
model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
I searched my error but I can't find my solution
The current User passed to the ForeignKey points to the auth.User right now, not your custom User.
As the HINT itself suggests, use settings.AUTH_USER_MODEL instead of User in your author field in Article model.
class Article(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name='articles', verbose_name='نویسنده')...
Link to django docs: Using a custom user model
Did you register the model in the app's admin.py?
Furthermore, changing the user model mid-project...this can be a hassle, look here: Changing to a custom user model mid-project
I think you are importing User model from django auth app.
Change the author field in the Article model as follows:
class Article(models.Model):
author = models.ForeignKey('account.User', null=True, on_delete=models.SET_NULL, related_name='articles', verbose_name='نویسنده')
...

How to generate a choices tuple for django models field to use in a form

Trying to create a choice field based on another model
I want my choices to be mapped like username: first_name + last_name
When I try username: last_name it does work
I tried doing something like this(Note, I am adding on user_choices and choices=user_choices. The model already existed before me making these changes.)
This works:
he_user_choices = tuple(User.objects.values_list('username', 'last_name'))
Here's what my models.py looks like:
from django.contrib.auth.models import User
owner_choices = tuple(User.objects.values_list('username', 'first_name' + 'last_name'))
class ErrorEvent(models.Model):
"""Error Event Submissions"""
event_id = models.BigAutoField(primary_key=True)
owner = models.IntegerField(verbose_name="Owner", blank=True, choices=owner_choices)
and here's my forms.py
from django import forms
from .models import ErrorEvent
class ErrorEventForm(forms.ModelForm):
class Meta:
model = ErrorEvent
# fields =
exclude = ['event_id']
widgets = {
'owner': forms.Select(),
}
Currently the owner_choices doesn't work, I get an error that says:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Any recommendations on what else I can try, or how would I go about fixing my problem?
Thank you in advance!
Please do not work with an IntegerField to refer to an object. A ForeignKey will check referential integrity, and furthermore it makes the Django ORM more expressive.
You thus can implement this with:
from django.conf import settings
class ErrorEvent(models.Model):
event_id = models.BigAutoField(primary_key=True)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name='Owner',
blank=True,
null=True
)
This will work with a ModelChoiceField [Django-doc] that automatically will query the database to render options. This also means that if you add a new User, creating a new ErrorEvent can be linked to that user, since it each time requests the Users from the database.
You can subclass the ModelChoiceField to specify how to display the options, for example:
from django.forms import ModelChoiceField
class MyUserModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return f'{obj.username} ({obj.firstname} {obj.lastname})'
Then we can use this in the form:
class ErrorEventForm(forms.ModelForm):
owner = MyUserModelChoiceField(queryset=User.objects.all())
class Meta:
model = ErrorEvent
# fields =
exclude = ['event_id']
widgets = {
'owner': forms.Select(),
}

Overriding init method of Django model

What I am trying to do is implement a 'follower system' for my app and I just want to make sure a user can't be followed multiple times by the same user. I can't seem to implement this as the admin continues to let me create duplicate relationships.
models.py
class FollowRelationshipManager(models.Manager):
def create_followrelationship(self, follower, followee, date):
if FollowRelationship.objects.filter(
follower=follower,
followee=followee
).exists():
raise ValueError('User is already followed')
else:
followrelationship = self.create(
follower=follower,
followee=followee,
date=date
)
return followrelationship
class FollowRelationship(models.Model):
follower = models.ForeignKey(User, related_name='follower', on_delete=models.CASCADE)
followee = models.ForeignKey(User, related_name='followee', on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
You can simply make use of a UniqueConstraint [Django-doc] which will prevent that the combination of the two (or more) fields:
class FollowRelationship(models.Model):
follower = models.ForeignKey(
User,
related_name='follower',
on_delete=models.CASCADE
)
followee = models.ForeignKey(
User,
related_name='followee',
on_delete=models.CASCADE
)
date = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=['follower', 'followee'],
name='follow_once'
)
]
This will also be enforced at the database level.
Prior to django-2.2, you can use unique_together [Django-doc]:
# prior to Django-2.2
class FollowRelationship(models.Model):
follower = models.ForeignKey(
User,
related_name='follower',
on_delete=models.CASCADE
)
followee = models.ForeignKey(
User,
related_name='followee',
on_delete=models.CASCADE
)
date = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = [['follower', 'followee']]
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

How to add list of users to django admin panel

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.

foreignkey (user) in models

I read the docs and this post... Django - Foreign Key to User model
I followed what it said and I still cannot get it to work. When I try to run the migrations I get this error in the traceback...
django.db.utils.ProgrammingError: column "author_id" cannot be cast automatically to type integer
HINT: You might need to specify "USING author_id::integer".
I just don't know how to go about fixing that error.
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BlogCategory(models.Model):
'''model for categories'''
title = models.CharField(max_length=30)
description = models.CharField(max_length=100)
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()
Don't use the User model directly.
From the documentation
Instead of referring to User directly, you should reference the user
model using django.contrib.auth.get_user_model()
When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting.
Example:
from django.conf import settings
from django.db import models
class Article(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
If you created a custom User model, you would use setting.AUTH_USER_MODEL, if not you can go ahead an use User model
Referencing Django User model
the column "author_id" doesn't exist, looks like is the same problem from here : Django suffix ForeignKey field with _id , so to avoid this traceback you may use :
author = models.ForeignKey(User, db_column="user")
I do not know the "settings.AUTH_USER_MODEL" approach but a well-known approach and commonly used is the "Auth.User" model. Something like this on your end.
from django.contrib.auth.models import User
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()

Categories

Resources