Django model field is showing in django admin - python

In my django admin model(Profile), I am not able to see my StudentID field declared in django model.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
StudentID = models.AutoField(primary_key=True, verbose_name='SID')
Branch = models.CharField(max_length=255, choices=Departments, default="CSE")
YearOfStudy = models.IntegerField(default=1)
ContactNumber = PhoneField(help_text='Contact phone number')
image = models.ImageField(default='default.jpeg', upload_to='profile_pics', blank=True)
parentsContactNumber = PhoneField(help_text="Parent's phone number", blank=True)
def __str__(self):
return f'{self.user.username} Profile'

To reflect your StudentID in the admin page you must return it in the str function
def __str__(self):
return self.StudentID

Related

Check In System by input user data in Django

I trying to do a check In System where Students can do it themselves by inputting their ID's but I am really struggling.
Follow views, models, forms, and html
VIEW
class Attendance(CreateView):
template_name = 'homepage.html'
model = GetAttendance
fields = ['aluno']
success_msg = "Check In Succesfully"
def form_valid(self, form):
form.save()
success_msg = self.get_success_message(form.cleaned_data)
if success_msg:
messages.success(self.request, success_msg)
return super().form_valid(form)
def get_success_url(self):
return reverse('attendance:homepage')
def get_success_message(self, cleaned_data):
return self.success_msg % cleaned_data
MODELS
class Aluno(models.Model):
id = ShortUUIDField(primary_key=True, editable=False, alphabet="0123456789", length=5)
photo = models.ImageField(upload_to='photos/', default='static/images/defaultuser.jpeg', blank=True)
nome = models.CharField(max_length=255)
phone = models.CharField(max_length=255)
email = models.EmailField(max_length=255, unique=True)
location = models.ForeignKey(MasterUser, on_delete=models.CASCADE)
belt = models.CharField(max_length=255, choices=BELT)
stripe = models.CharField(max_length=255, choices=GRAU)
join_date = models.DateField(default=timezone.now)
last_graduation = models.DateField(default=timezone.now)
gender = models.CharField(max_length=255, choices=GENDER)
def __str__(self):
return self.nome
class GetAttendance(models.Model):
aluno = models.ForeignKey(Aluno, on_delete=models.CASCADE)
attendance = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.aluno) + ' - ' + str(self.attendance)
That's views.py
My models.py
forms
html
check in page
Basically what I need is instead of having the form of a choice be able to input the student ID and run the model GetAttendance.

ValueError: Field 'id' expected a number but got string in Django Rest Framework

In DRF I am facing an issue, whenever I do a POST request on the endpoint, on the field "name" which is a text field I get an exception "Field 'id' expected a number but got 'TITLE'", but when I change the value of "name" to an integer the request is successful I don't understand it becauses name is TextField in model and why its mixing Id and Name field with each other. I have deleted the migration files from the Project and DB and re-run the Migrations, but still facing this issue.
Following is my code:
models.py
class Project(models.Model):
admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='project_crated_by')
name = models.TextField(max_length=225, blank=False, null=False)
project_members = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='members', null=True, blank=True)
created_on = models.DateField(default=timezone.now)
tags = ArrayField(models.CharField(max_length=225, default=''), blank=True)
def __str__(self):
return self.name
objects = models.Manager()
views.py
class ProjectView(viewsets.ViewSet):
def create(self, request):
project_name_exist = Project.verify_project_name(request.data['admin'], request.data['name'])
if project_name_exist:
return Response({'message': 'You already have a project with this name',
'status': status.HTTP_200_OK})
serialized_project = ProjectSerializer(data=request.data)
if serialized_project.is_valid():
serialized_project.save()
return Response({'message': 'Project Created Successfully', 'status': status.HTTP_201_CREATED})
else:
return Response({'error': serialized_project.errors, 'status': status.HTTP_400_BAD_REQUEST})
serializer.py
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'
A more generic and non-DIY solution is to use UniqueTogetherValidator on your serializer and let Django sort it out.
from rest_framework.validators import UniqueTogetherValidator
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'
validators = [
UniqueTogetherValidator(
queryset=Project.objects.all(),
fields=['admin', 'name'],
message='You already have a project with this name'
)
]
And/or add it to the model for enforcing it on the database.
class Project(models.Model):
admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='project_crated_by')
name = models.TextField(max_length=225, blank=False, null=False)
project_members = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='members', null=True, blank=True)
created_on = models.DateField(default=timezone.now)
tags = ArrayField(models.CharField(max_length=225, default=''), blank=True)
def __str__(self):
return self.name
objects = models.Manager()
class Meta:
unique_together = ("admin", "name")

AttributeError at /admin/accounts/school/ 'School' object has no attribute 'username'

hello am just wondering why cant I return return f'{self.user.username} Profile'
form this model
class School(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
region = models.CharField(max_length=200)
district = models.CharField(max_length=200)
code = models.CharField(max_length=20)
logo = models.ImageField(default='default.jpg', upload_to='logos')
def __str__(self):
return f'{self.user.username} Profile'
what should be the syntax here help
You are referencing int instead of User object. Int doesn't have field username. If you want to create Many-to-one relation in Django you should use `ForeignKey. Ref: https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ForeignKey
Change your class to:
class School(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
region = models.CharField(max_length=200)
district = models.CharField(max_length=200)
code = models.CharField(max_length=20)
logo = models.ImageField(default='default.jpg', upload_to='logos')
def __str__(self):
return f'{self.user.username} Profile'

How to expand User(AbstractBaseUser) with OnetoOneField?

I want relate my Profile model with User model from class AbstractUserModel with OnetoOneFields. Is it possible? Or any solution with this problem. Here my models.py
from django.db import models
#from django.contrib.auth.models import User
from django.contrib.auth.models import (
AbstractBaseUser
)
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
class Profile(models.Model):
#HERE
user = models.OneToOneField(AbstractBaseUser, on_delete=models.CASCADE)
nama_lengkap = models.CharField(max_length=100, blank=True, null=True)
tgl_lahir = models.DateField(null=True, blank=True)
alamat = models.CharField(max_length=255)
foto_profil = models.ImageField(upload_to='foto_profil',blank=True)
jabatan = models.ForeignKey(Jabatan, on_delete=models.CASCADE)
def __str__(self):
return "{} - {}".format(self.user, self.nama_lengkap)
when I migrate this, just show some errors message like this:
SystemCheckError: System check identified some issues:
ERRORS:
users.Profile.user: (fields.E300) Field defines a relation with model 'AbstractBaseUser', which is either not installed, or is abstract.
users.Profile.user: (fields.E307) The field users.Profile.user was declared with a lazy reference to 'auth.abstractbaseuser', but app 'auth' doesn't provide model 'abstractbaseuser'.
thanks in advance
you need to replace this
user = models.OneToOneField(AbstractBaseUser, on_delete=models.CASCADE)
with
user = models.OneToOneField(User, on_delete=models.CASCADE)
However I recommend you doing it different way:
Instead of creating second User model, extend existing one:
#models.py
class ProfileUser(AbstractUser):
extra_field = models.CharField(max_length=100)
username = models.CharField(max_length=20) # modifing existing field
```
```
#settings.py
AUTH_USER_MODEL = "app_name.ProfileUser"

Django filter from another model

In models.py I have following models:
class Project(models.Model):
project_name = models.CharField(max_length=255, unique=True, blank=False)
def __str__(self):
return str(self.project_name)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent')
town = models.CharField(max_length=100)
project = models.ManyToManyField(Project)
def __str__(self):
return str('Advanced user informations')
class News(models.Model):
title = models.CharField(max_length=255, blank=False)
content = HTMLField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
In my views.py I have:
def news(request):
news_list = News.objects.all().order_by('-id')
paginator = Paginator(news_list, 5)
page = request.GET.get('page')
news = paginator.get_page(page)
return render(request, 'news.html', {'news': news})
Now I want to achieve that a User can only see news for a project he participates.
Something like:
News.objects.filter(News with a project that the User is linked to)
But I am not sure what could be a valid way to solve this. Maybe someone has a tip?
What about this,
News.objects.filter(project__in=request.user.profile.project.all())
This should do it:
News.objects.filter(project__profile_set__user=request.user)

Categories

Resources