Recording user activity in django? - django

I have a project in which some user can perform CRUD activities. I want to record who did what and when. Currently, I am thinking of making a model
class UserAction(models.Model):
user_id = models.CharField(max_length=100)
action_flag = models.CharField(max_length=100)
class_id = models.CharField(max_length=100)
action_taken_at = models.DateTimeField(default=datetime.now())
and making a function that fills my UserAction table. Is there any better way to do this?

app/models.py:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
class Action(models.Model):
sender = models.ForeignKey(User,related_name='user',on_delete=models.CASCADE)
verb = models.CharField(max_length=255)
target_ct = models.ForeignKey(ContentType, blank=True, null=True,
related_name='target_obj', on_delete=models.CASCADE)
target_id = models.PositiveIntegerField(null=True, blank=True)
target = GenericForeignKey('target_ct', 'target_id')
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return self.pk
app/admin.py
from .models import Action
admin.site.register(Action)
How you can use it ?
you can now import this models(Action) inside any of yours views.py.
Example if you have a post and a user likes it.you can just write
Action.objects.create(sender=request.user,verb="likes this post",target=post)
and now when you look at your admin you will see that tartget_id=post.pk
Here I assume that a user is authenticated and you can change it for your own.Happy coding!!!

You can do it by creating a model in
Models.py
class Auditable(models.Model):
ip = models.GenericIPAddressField(null=True)
user_agent = models.CharField(max_length=255, blank=True)
remote_host = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="%(app_label)s_%(class)s_created_by", null=True, blank=True) # this is for web user
modified_at = models.DateTimeField(auto_now=True, blank=True, null=True)
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="%(app_label)s_%(class)s_modified_by", null=True, blank=True) # this is for web user
class Meta:
abstract = True
def get_fields(self):
list_fields = ['ip', 'user_agent',
'remote_host', 'created_by', 'modified_by']
return [(field.verbose_name, field._get_val_from_obj(self)) for field in self.__class__._meta.fields if field.name not in list_fields and not
(field.get_internal_type() == "DateTimeField" and
(field.auto_now is True or field.auto_now_add is True)) and
field.concrete and (not field.is_relation or field.one_to_one or
(field.many_to_one and field.related_model))]
You can give any class name (i have given auditable). So all you have to do is pass this class (auditable) in your every model instead of models.Model
For Eg:
class Student(Auditable):
By doing this it will add all the auditable fields records in every table you have created.
Hope you may get your answer by doing this.

Related

How to Display or accept names instead of ids in Django Superadmin while using GenericFroeignKey

I have a model for my project which is using GenricFroeignKeys for adding Stakeholders to Projects and Reposistories both.
The model is
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class StakeHolder(models.Model):
"""Model class for Stakeholders of Project and Repos"""
name = models.TextField()
email = models.EmailField()
def __str__(self):
return self.name
class Role(models.Model):
"""This is the model for Role that the stakeholders will have o projects and repos"""
name = models.TextField()
def __str__(self):
return self.name
class ProjectRepoStakeHolder(models.Model):
"""This is a generic models used to define stakeholders on project and repos"""
stake_holder = models.ForeignKey(StakeHolder, on_delete=models.CASCADE)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
limit = models.Q(app_label='pr_reviews', model='repository') | \
models.Q(app_label='pr_reviews', model='project')
# Fields that are mandatory for generic relations
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit,)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
def __str__(self):
return self.stake_holder.name + "/" + self.role.name + "/" + self.content_object.name
class Project(models.Model):
"""Model class for Project"""
name = models.TextField(unique=True, blank=False, null=False)
uuid = models.UUIDField(unique=True, blank=False, null=False)
is_active = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Repository(models.Model):
"""Model class for Repository"""
project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=False, null=False)
name = models.TextField(unique=True, blank=False, null=False)
uuid = models.UUIDField(blank=False, null=False)
is_active = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
Now if I have to add a Stakeholder to a Project or a Repository I have to do it by passing object_id (pk of Project or repo)
Like in this Image. I have to pass object id of a repo or project
Is there a way I can add Stakeholders to a Project or Repo by using their names instead, without having to change the pks of project and repo? (Just like how superadmin handles adding FroeigKey relations by a dropdown). Just like this (for ref)
Following is my admin.py file
from django.contrib import admin
from pr_reviews.models import Project, Repository, Role, ProjectRepoStakeHolder, StakeHolder
class ProjectAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'is_active')
class RepoAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'is_active', 'project')
class ProjectRepoStakeholderAdmin(admin.ModelAdmin):
list_display = ('stake_holder', 'role', 'content_object', 'content_type')
admin.site.register(Project, ProjectAdmin)
admin.site.register(Repository, RepoAdmin)
admin.site.register(ProjectRepoStakeHolder, ProjectRepoStakeholderAdmin)
admin.site.register(Role)
admin.site.register(StakeHolder)
Please be polite if you want me to improve my question. I don't wanna get bullied like last time when I posted a question here. (just a newbie developer)

Django Import Export, Filter ForeignKey objects connected to users

I'm building an import excel files system for every leads whit an import-export library. On the Website, each user must be able to import his leads and make sure that they are viewed only by him. In all other cases, I filtered the "organisation" field linked to a UserProfile model through the views.py. But now I don't know how to filter the field organisation for a specific user. At the moment I can import the excel files from the template but leave the organisation field blank. Help me please I'm desperate
Models.py
class Lead(models.Model):
nome = models.CharField(max_length=20)
cognome = models.CharField(max_length=20)
luogo=models.CharField(max_length=50, blank=True, null=True, choices=region_list)
città=models.CharField(max_length=20)
email = models.EmailField()
phone_number = models.CharField(max_length=20)
description = models.TextField()
agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL)
category = models.ForeignKey("Category", related_name="leads", null=True, blank=True, on_delete=models.SET_NULL)
chance=models.ForeignKey("Chance",related_name="chance", null=True, blank=True, on_delete=models.CASCADE)
profile_picture = models.ImageField(null=True, blank=True, upload_to="profile_pictures/")
converted_date = models.DateTimeField(null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE,null=True, blank=True)
objects = LeadManager()
age = models.IntegerField(default=0)
def __str__(self):
return f"{self.nome} {self.cognome}"
class User(AbstractUser):
is_organisor = models.BooleanField(default=True)
is_agent = models.BooleanField(default=False)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
Views.py
def simple_upload(request):
if request.method == 'POST':
Lead_resource = LeadResource()
dataset = Dataset()
newdoc = request.FILES['myfile']
imported_data = dataset.load(newdoc.read(),format='xlsx')
#print(imported_data)
for data in imported_data:
value = Lead(
data[0],
data[2],#nome
data[3],#cognome
data[5],#luogo
data[7],#città
data[8],#email
data[9],#numero telefono
data[11],#desc
)
value.save()
result = Lead_resource.import_data(dataset, dry_run=True) # Test the data import
if not result.has_errors():
Lead_resource.import_data(dataset,dry_run=False) # Actually import now
return render(request, 'input.html')
Resources.py
class LeadResource(resources.ModelResource):
nome = fields.Field(attribute='nome', column_name='nome')
luogo = fields.Field(attribute='luogo', column_name='regione')
class Meta:
model = Lead
report_skipped=True
admin.py
#admin.register(Lead)
class PersonAdmin(ImportExportModelAdmin):
readonly_fields = ('date_added',)

django retrieving all objects from one to many model relationship in shell

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Board(models.Model):
title = models.CharField(max_length=50, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Task(models.Model):
title = models.CharField(max_length=200, null=True)
done = models.BooleanField(default=False, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
how can I get all tasks that are inside one board? (every user can create a board and inside that board the user can create tasks) I've tried Board.objects.get(pk=1).title.title but that doesn't seem to work.
You can retrieve the Board object, and then query with task_set:
board = Board.objects.get(pk=1)
board.task_set.all() # queryset of related Tasks
If you are not interested in the Board itself, you can omit querying the Board, and filter with:
Task.objects.filter(board_id=1) # queryset of related Tasks

Django models not allowing one to many relationship

Having a really tough time wrapping my head around creating this model set for Django. Currently I am creating a site where a user can click the article to decide that he or she likes the article. I have set up the models to include article, favorite articles, and user. However, currently the way I have it set up is for it to only allow the user to have one favorite article, not two. I am using the ForeignKey field and that is not working. Here they are
from django.db import models
# users/models.py
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
import uuid
class Article(models.Model):
title = models.CharField(max_length=120, primary_key=True)
content = models.TextField()
url=models.CharField(max_length=200, null=True)
category = models.CharField(max_length=250, null =True)
def __str__(self):
return self.title
class CustomUser(AbstractUser):
username = models.CharField(max_length=50, unique=True, primary_key=True)
git = models.CharField(max_length=200, null=True)
homepage = models.CharField(max_length=250, null=True)
def __str__(self):
return str(self.username)
class FavoriteArticles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user', null=True)
fav_title = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='fav_title', null=True)
reasons = models.CharField(max_length=120, null=True)
favcategory = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='favcategory', max_length=250, null =True)
# def __str__(self):
# return self.user

Not getting foreign key data in django api views

Currently I have a site, and I want the user to be able to view their liked articles. I want this to be included in the user api view that is already set up. I have tried the tracks = serializers.StringRelatedField(many=True)that is in the drf docs yet this didn't work. I have also tried the following:
from rest_framework import serializers
from articles.models import Article, CustomUser,FavoriteArticles
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('title', 'content')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = '__all__'
class FavoriteArticleSerializer(serializers.ModelSerializer):
class Meta:
model = FavoriteArticles
fields = '__all__'
class UserProfileSerializer(serializers.ModelSerializer):
fav_title = FavoriteArticleSerializer(read_only=False)
class Meta:
model = CustomUser
fields = 'username, git, email, fav_article, fav_title, homepage'
and my models:
from django.db import models
# users/models.py
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
import uuid
class ProgrammingLanguage(models.Model):
programming_language = models.CharField(max_length=120, null=False, primary_key=True, default="React")
def __str__(self):
return self.programming_language
class Article(models.Model):
title = models.CharField(max_length=25, primary_key=True)
content = models.TextField()
usedfor = models.TextField()
url=models.CharField(max_length=200, null=True)
article_programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE, related_name="article_programming_language", default="react")
score = models.IntegerField(max_length=5, null=0)
def __str__(self):
return self.title
class CustomUser(AbstractUser):
username = models.CharField(max_length=50, unique=True, primary_key=True)
git = models.CharField(max_length=200, null=True)
homepage = models.CharField(max_length=250, null=True)
user_programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE, related_name="most_used_programming_language", default="react")
def __str__(self):
return str(self.username)
class FavoriteArticles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
fav_title = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='fav_title')
reasons_liked = models.CharField(max_length=120, null=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="user", default="tom" )
def __unicode__(self):
return '%s: %s' % (self.fav_title, self.reasons_liked)
I think you misunderstood what related_name means. It specifies how you would access a model from its reverse relationship. So I'd recommend you remove it from fields in your FavoriteArticles model and use the default Django already provides (in this case favoritearticles_set):
class FavoriteArticles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
fav_title = models.ForeignKey(Article, on_delete=models.CASCADE)
reasons_liked = models.CharField(max_length=120, null=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default="tom")
def __unicode__(self):
return '%s: %s' % (self.fav_title, self.reasons_liked)
This way, you can access favorite articles of a user via my_user.favoritearticles_set.all(). Then, you can change your UserSerializer to include a liked_articles field which is populated from the favoritearticles_set reverse relationship to a user's FavoriteArticles using a source attribute:
class UserSerializer(serializers.ModelSerializer):
liked_articles = FavoriteArticleSerializer(source='favoritearticles_set', many=True, read_only=True)
class Meta:
model = CustomUser
# explicitly include other fields as required
fields = ('username', 'git', 'user_programming_language', 'liked_articles')
Note that we've made this a read_only field, so it will only get populated if you perform a GET request.