AttributeError at /admin/student/student_record/ - python

I updated my django model, for my student app, it now looks like this
from django.db import models
class Student_Record(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
address = models.CharField(max_length=500)
gpa = models.FloatField()
def __str__(self):
return str(self.student_id) + ", " + self.first_name
there used to be an IntegerField, student_id but I removed it. I made the migrations, and everything runs fine, but when I visit the django admin panel, to manually update the database records, I get the following error
does anyone know what's going on?
I registered the model, in admin.py
from django.contrib import admin
from .models import Student_Record
admin.site.register(Student_Record)

Look at your __str__ method it still references student_id.
You should search for the field name in your whole project, there might be other occurrences elsewhere.

Related

In my blogging website i want to delete a user and all its associated blogs and comments

I deleted a user, then all the associated blogs were also deleted but the associated comments are not deleted. Why comments model is indirectly related to User model using foreign key.
Can anyone give me the answer
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class blogpost(models.Model):
created_by=models.ForeignKey(User,on_delete=models.CASCADE)
topic=models.CharField(max_length=122,null=True,blank=False)
title=models.CharField(max_length=250,blank=False)
post=models.TextField()
likes=models.ManyToManyField(User, related_name='blog_posts')
date=models.DateTimeField(auto_now_add=True )
def __str__(self):
return ' (' +str(self.created_by)+') Title- '+self.title
class Meta:
ordering=['-date']
class CommentModel(models.Model):
post = models.ForeignKey(blogpost ,related_name='comments', on_delete=models.CASCADE)
name = models.CharField(max_length = 100)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' %(self.post.title, self.name)
class Meta:
ordering=['-date_added']
views.py
def comment_view(request, pk):
if request.method=='POST' and 'comment_button' in request.POST:
body=request.POST.get('comment_text')
post=blogpost.objects.get(pk=pk)
obj=CommentModel(body=body)
obj.name=request.user
obj.post=post
obj.save()
return HttpResponseRedirect(reverse('detaildata',args=[str(pk)]))
As I can see you have set on_delete=models.CASCADE in models, which is great.
You just have to delete the user, and belonging blogpost (and similarly so the comment) will get deleted on its own.
You can manually delete the user from Django Admin Panel or delete it from the shell. Here are the steps
$ python manage.py shell
...
$ User.objects.filter(id=1).delete()
Since you put on_delete on models.CASCADE, this will cause comments to be deleted if a user is removed.
You have two options:
Do this through the admin panel.
Enter into django shell using python manage.py shell and do so using User.objects.filter(id=1).delete ()

DJANGO get objects in sql like join

Context: I'm forcing my self to learn django, I already wrote a small php based website, so I'm basically porting over the pages and functions to learn how django works.
I have 2 models
from django.db import models
class Site(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Combo(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
dead = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
siteID = models.ForeignKey(Site, on_delete=models.PROTECT)
class Meta:
unique_together = ('username','siteID')
def __str__(self):
return f"{self.username}:{self.password}#{self.siteID.name}"
When creating a view, I want to get the Combo objects, but I want to sort them first by site name, then username.
I tried to create the view, but get errors about what fields I can order by Cannot resolve keyword 'Site' into field. Choices are: dead, id, password, siteID, siteID_id, timestamp, username
def current(request):
current = Combo.objects.filter(dead=False).order_by('Site__name','username')
return render(request, 'passwords/current.html',{'current':current})
Since I'm not necissarily entering the sites into the database in alphabetical order, ordering by siteID wouldn't be useful. Looking for some help to figure out how to return back the list of Combo objects ordered by the Site name object then the username.
You can order this by siteID__name:
def current(request):
current = Combo.objects.filter(dead=False).order_by('siteID__name','username')
return render(request, 'passwords/current.html',{'current':current})
since that is the name of the ForeignKey. But that being said, normally ForeignKeys are not given names that end with an ID, since Django already adds an _id suffix at the end for the database field.
Normally one uses:
class Combo(models.Model):
# …
site = models.ForeignKey(Site, on_delete=models.PROTECT)
if you want to give the database column a different name, you can specify that with the db_column=… parameter [Django-doc]:
class Combo(models.Model):
# …
site = models.ForeignKey(
Site,
on_delete=models.PROTECT,
db_column='siteID'
)

Unable to migrate Django models

So I'm trying to automatically assign the current logged in user to a variable in my model. I think this make sense but I'm not able to migrate the models and it is going me this error.
models.py:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank='True')
def __str__(self):
return self.user.username
class UserPosts(models.Model):
post_title = models.CharField(max_length=100,unique=True)
post_sub_title = models.CharField(max_length=250,unique=False)
post_author = models.ForeignKey('User',User.username)
post_date = models.DateField(default=date.today,blank=True)
post_body = models.TextField(max_length=1000,unique=False)
def __str__(self):
return str(self.post_title)
The Error:
ValueError: Cannot create form field for 'post_author' yet, because its related model 'User' has not been loaded yet
Remove the quotation from this line:
post_author = models.ForeignKey('User',User.username)
It should be like this:
post_author = models.ForeignKey(User,User.username)
I think the problem is this:
from django.contrib.auth.models import User
post_author = models.ForeignKey('User',User.username)
Your ForeignKey want's to use the attribute 'username' of the imported User. Not of your User object when related.
I think I just deleted the migrations and then migrated again from scratch...

How to authenticate user for a specific object rather than whole class in django?

I am working on making an app to add clubs in website. This is my model.py file
from django.db import models
from stdimage import StdImageField
# Create your models here.
class Club(models.Model):
ClubName = models.CharField(max_length=200)
ClubLogo = StdImageField(upload_to='club_logo', variations={'thumbnail':(150, 200, True)})
ClubDetails = models.TextField()
ClubStartDate = models.DateField()
def __str__(self):
return self.ClubName
class Notice(models.Model):
NOTICE = 'NOTICE'
UPDATES = 'UPDATES'
EVENTS = 'EVENTS'
NOTICE_IN_CHOICES = (
(NOTICE, 'Notice'),
(UPDATES, 'Updates'),
(EVENTS, 'Events'),)
NoticeType = models.CharField(
max_length=20, choices=NOTICE_IN_CHOICES, default=NOTICE)
NoticeTag = models.CharField(max_length=30)
NoticeStartDate = models.DateField(auto_now_add=True)
NoticeEndDate = models.DateField()
NoticeFile = models.FileField(default='#', upload_to='notice/%Y/%m/%d')
NoticeContent = models.TextField(default='NA')
NoticeClub = models.ForeignKey(Club)
def __str__(self):
return self.NoticeTag
class Members(models.Model):
MemeberName = models.CharField(max_length=200)
MemberImage = StdImageField(upload_to='member_photo', variations={'thumbnail':(150, 120, True)})
MemberEmail = models.EmailField()
MemberClub = models.ForeignKey(Club)
def __str__(self):
return self.MemeberName
Now when i am making users via django's inbuilt admin panel i have option to give permission to users to change member of any club but i want to give access to change members of only that particular club which he is member of.
As you can see in this picture that all club are in dropdown option when someone who has access to add notices adding otices. But instead of that i want only one option in the dropdown for the useradmin to which he is associated.
this is my admin.py file
from django.contrib import admin
# Register your models here.
from club.models import Club, Members, Notice
admin.site.register(Club),
admin.site.register(Members),
admin.site.register(Notice),
This is a problem with which many users have been struggling with.
I have been using couple of external packages, and couple of self made solutions. But the best one I have found so far is Django Guardian It's an implementation of per object permission .This means you can manage users and permissions to which they have access to.

Foreign key constraint error on Django app

I'm trying to have this third class noticeTime be constrained to the foreign key email. I am using the same syntax that worked for the 2nd class location, but when I use it on noticeTime it throws an error:
Exception Value: no such column: setupNotifications_noticetime.email_id
Here is the code:
from django.db import models
# Create your models here.
from django.db import models
class email(models.Model):
email = models.CharField(max_length=200)
def __unicode__(self):
return self.email`
class location(models.Model):
email = models.ForeignKey(email)
zip_code = models.CharField(max_length=5)
def __unicode__(self):
return self.zip_code
class noticeTime(models.Model):
email = models.ForeignKey(email)
time = models.CharField(max_length=200)
def __unicode__(self):
return self.time
here is admin.py:
from django.contrib import admin
# Register your models here.
from setupNotifications.models import email
from setupNotifications.models import location
from setupNotifications.models import noticeTime
admin.site.register(email)
admin.site.register(location)
admin.site.register(noticeTime)
I'm using the sqlite database
Perhaps your problem is that you ran syncdb, assuming that it would alter the table to match your model change. Unfortunately, it does not do that. There are some separate tools available, such as South, which can help with database migrations.

Categories