How to make a user profile view? - python

Since I am new to django, this is my first time trying to create a user profile. And I don't know how to make a profile view with a link to it. Could you please give me an example
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
username = models.CharField(max_length = 40, unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
slug = AutoSlugField(populate_from = 'username', null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = CustomUserManager()
class Meta:
verbose_name = 'Пользователь'
verbose_name_plural = 'Пользователи'
def __str__(self):
return self.email
def get_absolute_url(self):
return reverse('profile', args=[str(self.slug)])
class UserProfile(models.Model):
user = models.OneToOneField(CustomUser, on_delete = models.CASCADE, null = True, db_constraint=False)
avatar = ProcessedImageField(
upload_to = 'avatar',
format = "JPEG",
default = "avatar/empty_avatar.jpg",
processors = [ResizeToFit(250, 200)],
options = {'quality': 90},
blank = True,
null = True,
)
description = models.TextField(default = '', blank = True, null = True)
slug = AutoSlugField(populate_from = 'user', null=True)
class Meta:
verbose_name = 'Профиль'
verbose_name_plural = 'Профили'
#receiver(post_save, sender=CustomUser)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
#receiver(post_save, sender=CustomUser)
def save_user_profile(sender, instance, **kwargs):
try:
instance.userprofile.save()
except ObjectDoesNotExist:
UserProfile.objects.create(user=instance)
forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('email', 'username',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('email', 'username',)
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('avatar', 'description',)
views.py
I want to create a link to an object using a slug or username so that it looks like "accounts/profile/username"
class UserProfileUpdate(generic.UpdateView, generic.FormView):
model = UserProfile
template_name = 'users/profile.html'
form_class = UserProfileForm
def form_valid(self, form):
response = form.save(commit = False)
response.save()
return super(UserProfileUpdate, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(UserProfileUpdate, self).get_context_data(**kwargs)
context['user'] = CustomUser.objects.get(slug = slug)
context['profile'] = UserProfile.objects.get(user = context['user'])
return context
I also want users to be able to view other users' profiles, not just thier own

Related

Cannot assign "<SimpleLazyObject: <User: student1#mail.ru>>": "Answer.id_student" must be a "Student" instance

I am trying to use email for authentication in Django. Previously, I worked directly with the user, but I need it through the "Student" class.
VIEWS
class AnswerToCase(FormMixin, DetailView):
STATUS = [
('Участник', 'Участник'), ('Победитель', 'Победитель')]
model = Case
template_name = 'addanswer.html'
form_class = AddAnswer
success_url = '/'
context_object_name = 'get_case'
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.id_case = self.get_object()
What is the correct way to specify saving an object to yourself?
self.object.id_student = self.request.user
self.object.is_won = self.get_object()
self.object.save()
return super().form_valid(form)
If I write the command like this self.object.id_student = Student.objects.get(user_id=self.request.user)
Error
['The value of “Fun” must be True or False.']
Fan is title of the "case" model
Models
Class User
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(db_index=True, unique=True, max_length=254)
phone = models.CharField(max_length=20, help_text='Номер телефона')
is_staff = models.BooleanField(default=True) # must needed, otherwise you won't be at
is_active = models.BooleanField(default=True) # must needed, otherwise you won't be «
is_superuser = models.BooleanField(default=False) # this field we inherit from Permis
is_student = models.BooleanField(default=False)
is_partner = models.BooleanField(default=False)
objects = CustomUserManager()
REQUIRED_FIELDS = ["phone"]
USERNAME_FIELD = 'email'
Class Student
class Student(models.Model):
user = models.OneToOneField(User, verbose_name='id', on_delete=models.CASCADE, primary_key=True)
Fio = models.CharField(max_length=100, blank=True, verbose_name='ФИО')
Educational_institution = models.CharField(max_length=50, verbose_name='Место учебы')
age = models.CharField(max_length=2,verbose_name='возраст')
region = models.CharField(max_length=50, choices=REGIONS, default=REGIONS[0])
Direction_of_study = models.CharField(max_length=50, verbose_name='Специальность')
Education = models.CharField(max_length=50, verbose_name='Образование', choices=EDUCATION, default=EDUCATION[0])
Course = models.CharField(max_length=50, verbose_name='Курс', choices=COURSE, default=COURSE[0])
Class Answer
class Answer(models.Model):
Url = models.URLField(verbose_name='Ссылка на ответ', blank=True)
File = models.FileField(verbose_name='Файл', upload_to = "file",blank=True)
id_case = models.ForeignKey(Case, verbose_name="Кейс", on_delete=models.CASCADE,blank=True,related_name='cases')
If you change the class to User, then saving works id_student = models.ForeignKey(Student, verbose_name="Студент", on_delete=models.CASCADE,blank=True)
id_student = models.ForeignKey(Student, verbose_name="Студент", on_delete=models.CASCADE,blank=True)
is_won = models.BooleanField(default=False)
Class Case
class Case(models.Model):
title = models.CharField(max_length=200, verbose_name='Название')
description = models.TextField(verbose_name='Описание кейса')
date_of_create = models.DateTimeField(auto_now=True, verbose_name='Дата создания')
date_of_edit = models.DateTimeField(auto_now_add=True, verbose_name='Дата последней редакции')
date_of_close = models.DateTimeField(verbose_name='Дата закрытия')
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категории')
user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='partners')
is_published = models.BooleanField(default=True, verbose_name='Опубликован')

How to use checkbox in form, i have in my model 1 field manytomanyfield

I need to show the category field in my template as a checkbox field.
forms.py
class PostUpdateForms(forms.ModelForm):
class Meta:
model = CreatePost
fields = ['title', 'img', 'category', 'content' ]
widgets = {
'title':forms.TextInput(attrs={'class':'form-control'}),
}
models.py
class Categories(models.Model):
category = models.CharField(verbose_name="Categoria", max_length=20)
class Meta:
verbose_name = 'Categoria'
verbose_name_plural = 'Categorias'
ordering = ['category']
def __str__(self):
return self.category
def custom_upload_to(instance, filename):
#old_intance = CreatePost.objects.get(pk=instance.pk)
#old_intance.img.delete()
return 'post/'+filename
class CreatePost(models.Model):
#user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Usuario")
title = models.CharField(verbose_name="Titulo", max_length=100)
slug = models.CharField(max_length=200, blank=True)
content = models.TextField(verbose_name="Contenido", null=True, blank=True)
img = models.ImageField(upload_to=custom_upload_to, null=True, blank=False)
category = models.ManyToManyField(Categories)
created = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(CreatePost, self).save(*args, **kwargs)
class Meta:
verbose_name = 'Anime'
verbose_name_plural = 'Animes'
ordering = ['-created']

How can I get user from serializer?

I am trying to override perform_update in my views, get user from serializer and assign it to updated_by in my Category model.
class Category(models.Model):
name = models.CharField(max_length=80)
created_at = models.DateTimeField(auto_now_add = True, null = True)
created_by = CurrentUserField()
updated_at = models.DateTimeField(auto_now = True, null = True)
updated_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name="updated_by")
deleted_at = models.DateTimeField(null = True)
deleted_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name='deleted_by')
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.name
def soft_delete(self, deleter):
self.deleted_by = deleter
self.deleted_at = timezone.now()
self.save()
serializer
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = "__all__"
views:
class CategoryView(viewsets.ModelViewSet):
serializer_class = CategorySerializer
queryset = Category.objects.all()
def get_permissions(self):
if self.request.method == "GET":
self.permission_classes = (AllowAny, )
else:
self.permission_classes = (IsAdminUser, )
return super(CategoryView, self).get_permissions()
def perform_update(self, serializer):
instance = self.get_object()
instance.updated_by = username
serializer.save()
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
deleter = self.request.user
self.perform_destroy(instance, deleter)
return Response(status=status.HTTP_204_NO_CONTENT)
def perform_destroy(self, instance, deleter):
instance.soft_delete(deleter)
User is available from request, not serializer. You are already using self.request.user in destroy() and you can do the same thing in perform_update()
def perform_update(self, serializer):
serializer.save(updated_by=self.request.user)

How do i create a new proxy model based on another model in django?

I have a model named tranasaction.
class transactions(models.Model):
id = models.AutoField(primary_key=True)
date = models.DateTimeField(default=datetime.now, blank=True)
saleduser = models.ForeignKey('UserData',on_delete=models.CASCADE, related_name='vclouduser_data', blank=True, null=True)
brand = models.CharField(max_length=50,blank=True)
type = models.CharField(max_length=50,blank=True)
quantity = models.DecimalField(blank=True,null=True,max_digits=20,decimal_places=2)
amount = models.DecimalField(blank=True,null=True,max_digits=20,decimal_places=2)
And I need to create a summary report,
so I create a new Model.
class SaleSummary(transactions):
class Meta:
proxy = True
verbose_name = 'Sale Summary'
verbose_name_plural = 'Sales Summary'
what i need that i need to get the total amount of each type as a new model.
please help me to solve this.
Thanks in advance.
Here is an example of a proxy model for a normal model, with a filtering example. I hope it will be helpful for you that how can you create the proxy model and how can you filter specific data from any model for the admin site. You also can apply this for your custom API response, Then you should write this code in serializers. Best of luck.
models.py
class UserModel(AbstractBaseUser):
"""
Purpose: create a custom auth user table
"""
name = models.CharField('name of user',max_length=256)
email = models.EmailField('email address', unique=True)
date_joined = models.DateTimeField('user creation date', auto_now_add=True)
is_admin = models.BooleanField('is a admin', default=False)
is_staff = models.BooleanField('is a staff', default=False)
is_superuser = models.BooleanField('if a superuser', default=False)
status = models.ForeignKey(SesameUserStatus, on_delete = models.CASCADE, related_name='sesame_user_status_type', default=2)
organization = models.ForeignKey(Organization, on_delete = models.CASCADE, related_name='sesame_user_organization_info', default=1)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def has_perm(self,prm,obj=None):
return self.is_active and self.is_admin
def has_module_perms(self,app_level):
return self.is_active and self.is_admin
def __str__(self):
return f'{self.name} // {self.email} // {self.organization.name}'
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
indexes = [
models.Index(fields=['email']),
]
class UserProxyModel(UserModel):
"""
Purpose: create proxy model to visualize only pending user
"""
class Meta:
proxy = True
verbose_name = "Pending User"
verbose_name_plural = "Pending Users"
###########################################################################
admin.py
class UserAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'email', 'date_joined', 'is_admin', 'is_staff']
class Meta:
model = UserModel
class UserProxyModelAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'email', 'date_joined', 'is_admin', 'is_staff', 'organization', 'status']
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs.filter(status=SESAME_USERS["status"]["PENDING"]).order_by('id')
return None
class Meta:
model = UserProxyModel
admin.site.register(UserModel, UserAdmin)
admin.site.register(UserProxyModel, UserProxyModelAdmin)

Django-rest: How to implement authentication and permissions for custom User models?

views.py
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
model = User
serializer_class = UserSerializer
paginate_by = 10
def get_queryset(self):
queryset = User.objects.all()
search_query = self.request.query_params.get('user', None)
if search_query is not None:
queryset = queryset.filter(name__istartswith=search_query)
queryset = queryset.order_by('name')
return queryset
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
model = User
serializer_class = UserSerializer
models.py
class UserRole(models.Model):
class Meta:
ordering = ["name"]
db_table = 'userrole'
name = models.CharField(max_length=50)
status = models.CharField(max_length=100)
class User(models.Model):
class Meta:
ordering = ["name"]
db_table = 'user'
name = models.CharField(max_length=100)
email = models.EmailField(unique=True, max_length=100)
password = models.CharField(max_length=100)
status = models.CharField(max_length=100, default='active')
roleid = models.ForeignKey(UserRole, on_delete=models.CASCADE,
default=None, blank=True, db_column='roleid')
createdby = models.CharField(max_length=100, blank=True, default="")
createdon = models.DateTimeField(blank=True, auto_now_add=True)
updatedon = models.DateTimeField(blank=True, auto_now=True)
Serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
class UserRoleSerializer(serializers.ModelSerializer):
class Meta:
model = UserRole
I've gone through with Django-rest documentation but not able to find a reference for implementing authentication and permission for custom created Users.
Please advise.
Check Django Document for User authentication in Django and Permissions in Django Rest Framework.
Below is the sample models structure for custom BaseUser and BaseUserManager.
from django.conf import settings
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
from django.template.defaultfilters import slugify
User = settings.AUTH_USER_MODEL
class BaseUserManager(BaseUserManager):
def create_user(self, useremail, display_name, password=None):
if not useremail:
raise ValueError('Users must have an email address')
now = timezone.now()
user = self.model(useremail=BaseUserManager.normalize_email(useremail))
user.display_name = display_name
user.email = useremail
user.profile_slug = getUniqueValue(BaseUser,slugify(useremail.split("#")[0]),field_name="profile_slug")
user.set_password(password)
user.status='A'
user.last_login = user.date_joined = now
user.save(using=self._db)
return user
def create_superuser(self, useremail, display_name, password):
user = self.create_user(useremail=useremail,
display_name=display_name, password=password)
user.email = useremail
user.display_name = display_name
user.is_superuser = True
user.is_staff = True
user.status='A'
user.save(using=self._db)
return user
class BaseUser(AbstractBaseUser, PermissionsMixin):
display_name = models.CharField(max_length=25)
profile_slug = models.CharField(max_length=25,null=True)
gender = models.CharField(max_length=1, blank=True, choices=Gender)
useremail = models.EmailField(unique=True)
is_staff = models.BooleanField(default=False)
user_status = models.CharField(max_length=1, default='A')
USERNAME_FIELD = 'useremail'
REQUIRED_FIELDS = ['display_name']
objects = BaseUserManager()
def __unicode__(self):
return self.display_name
In your permission.py, you may define permissions as:
from rest_framework import permissions
class CheckPermission(permissions.BasePermission):
def has_permission(self, request, view):
try:
# some code
return True
except:
return False

Categories

Resources