I am getting an error while running the following form. please help me to fix the error.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class student(models.Model):
name = models.CharField(max_length=50)
emailid = models.EmailField(max_length=60)
marks = models.CharField(max_length=11)
date = models.DateTimeField()
def __str__(self):
return self.name
forms.py
from django import forms
from .models import *
class student_form(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(), required=True, max_length=100)
emailid = forms.EmailField(widget=forms.EmailField(), required=True)
class Meta():
model = student
fields = ['name','emailiid']
I have tried many things but no solution. please look at in this code and help to sort this out. so confusing for me as i am new to Django.
In forms.py, you must indent the Meta class so it is part of the student_form class.
This gives:
from django import forms
from .models import *
class student_form(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(), required=True, max_length=100)
emailid = forms.EmailField(widget=forms.EmailField(), required=True)
class Meta:
model = student
fields = ['name','emailiid']
Related
from django.contrib import admin
from . import models
class TodoListAdmin(admin.ModelAdmin):
list_display = ("title", "created", "due_date")
class CategoryAdmin(admin.ModelAdmin):
list_display = ("name",)
admin.site.register(models.TodoList, TodoListAdmin)
admin.site.register(models.Category, CategoryAdmin)
I am trying to register two models in my Django admin.py file inside the app directory
The model file is as follows :
from django.db import models
from django.utils import timezone
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=200)
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
def __str__(self):
return self.name
class ToDoList(models.Model):
title = models.CharField(max_length=250)
contents = models.TextField(blank=True)
created = models.DateField(default=timezone.now().strftime("%d-%m-%Y"))
due_date = models.DateField(default=timezone.now().strftime("%d-%m-%Y"))
category = models.ForeignKey(Category,on_delete=models.DO_NOTHING)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.title
For some reason , there is no problem with Category class but I am encountering an error with ToDoList class . Django is showing the following error
admin.site.register(models.TodoList, TodoListAdmin)
AttributeError: module 'todolist.models' has no attribute 'TodoList'
Its all in the spelling bro,
Your class instance is
ToDoList
and in your
admin.site.register()
You are making reference to
Todolist
Change the "d" in your admin.site.register() to uppercase
That is
admin.site.register(models.ToDoList, TodoListAdmin)
You just typo, change TodoList with ToDoList.
I have two models, which are User and Record. Each has several fields.
from django.db import models
class User(models.Model):
openid = models.CharField(max_length=20)
nickname = models.CharField(max_length=20,null=True)
def __str__(self):
return self.nickname
class Record(models.Model):
expression = models.CharField(max_length=100)
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.expression
I register them in admin.py
from django.contrib import admin
from .models import User,Record
class RecordAdmin(admin.ModelAdmin):
list_display = ('expression','user','time')
class UserAdmin(admin.ModelAdmin):
empty_value_display = "çİş"
list_display = ('openid','nickname')
admin.site.register(User,UserAdmin)
admin.site.register(Record,RecordAdmin)
it works well in django admin initially. but one day, the fields of the Record model disppeared. It looks like
.
No field displays. It makes me unable to modify or add the values of the Record model. The other model User works well and all data exists in database. So why?
I think you just have to add on_delete=models.CASCADE in your ForeignKey Field. When you are using this kind of field, you have to specify the comportment when you make an update, a delete or anything else on this field.
So your script should be like this :
class Record(models.Model):
expression = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.expression
This is the result :
Edit :
You can also modify null=True by default=null
class User(models.Model):
openid = models.CharField(max_length=20)
nickname = models.CharField(max_length=20,default=null)
def __str__(self):
return self.nickname
I'm trying to hide and delete two fields from showing in a form I created in the Django administration page using ModelForm.
I looked at answers that said I should use the "exclude" meta field, but I don't know why it's not working in my case.
Here is my code:
models.py:
class Activity(models.Model):
type = models.CharField(max_length=50, default="")
title = models.CharField(max_length=200, default="")
description = models.CharField(max_length=500)
owner = models.ForeignKey(User, related_name="owner")
college = models.CharField(max_length=200)
location = models.CharField(max_length=200)
room = models.CharField(max_length=200)
startDate = models.DateTimeField(null=True, blank=True)
endDate = models.DateTimeField(null=True, blank=True)
attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)
volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True)
I'm trying to exclude the "attendee & volunteer" fields from displaying in the Django administration form.
In admin.py I have:
from django.contrib import admin
from django import forms
from KSUvity.models import Activity
class ActivityForm(forms.ModelForm):
class Meta:
model = Activity
exclude = ['attendee', 'volunteer',]
class ActivityAdmin(admin.ModelAdmin):
exclude = ['attendee', 'volunteer',]
form = ActivityForm
admin.site.register(Activity, ActivityAdmin)
You have to create an admin.py file in your app and register your models
Follow the instuctions
See the example below
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
admin.site.register(Person, PersonAdmin)
You can use either fields or exclude in one class.
In your app admin field add this code.
app_name/admin.py
from django.contrib import admin
class ActivityAdmin(admin.ModelAdmin):
exclude = ('attendee', 'volunteer',)
You have to use ModelAdmin option to exclude fields from form in Django administration, either ModelAdmin.exclude or ModelAdmin.fields. Below is an example:
class ActivityAdmin(admin.ModelAdmin):
exclude = ('attendee', 'volunteer', )
To make it work, you register model like this:
admin.site.register(Activity, ActivityAdmin)
You add this code to admin.py file.
I am a newbee to django and I have created a simple model with two fields to create profiles and registered them in admin.
here is my model
from django.db import models
# Create your models here.
class profile(models.Model):
name = models.CharField(max_length = 1200)
description = models.TextField(default= 'description default')
def __unicode__(self):
return self.name
and below is the admin.py
from django.contrib import admin
# Register your models here.
from .models import profile
class profileAdmin(admin.ModelAdmin):
class Meta:
model= profile
admin.site.register(profile,profileAdmin)
but when I add profiles it is not showing the name of the profile
If you are using Python 3, you should define __str__ instead of __unicode__.
class profile(models.Model):
name = models.CharField(max_length = 1200)
description = models.TextField(default= 'description default')
def __str__(self):
return self.name
Say I have this app named Pantry that is to connect to any other app I may come along. To keep the app decoupled, generic relations are used through the model LinkedItem which connects the Ingredients model to apps outside Pantry.
I can make a filter_horizontal show up for the LinkedItem's admin in Django. Now I would like the content on the other end of the generic relation, say an app named Bakery, to be able to do a filter_horizontal with ingredients.
Pantry
models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import fields
class Ingredient(models.Model):
'''
Model containing all the ingredients, their slugs, and their descriptions
'''
name = models.CharField(unique=True, max_length=100)
slug = models.SlugField(unique=True, max_length=100)
description = models.CharField(max_length=300)
# method to return the name of the db entry
def __str__(self):
return self.name
class LinkedItem(models.Model):
'''
Model that links ingredients to various other content models
'''
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = fields.GenericForeignKey('content_type', 'object_id')
ingredient = models.ManyToManyField(Ingredient)
# method to return the name of the db entry
def __str__(self):
return self.ingredient.name
# defines options for the model itself
class Meta:
unique_together = (('content_type','object_id')) # prevents duplicates
Bakery
admin.py
from django.contrib import admin
from bakery.models import Cake
class CakeAdmin(admin.ModelAdmin):
filter_horizontal = ('') # what to put here so ingredients show up?
Any ideas?
A solution is to create a GenericTabularInline for LinkedItem and putting some restrictions on the display to avoid duplicates like below:
from django.contrib.contenttypes.admin import GenericTabularInline
class LinkedItemAdmin(GenericTabularInline):
model = LinkedItem
# choosing the field and display
field = ['ingredient']
filter_horizontal = ['ingredient']
# These help with removing some potential issues in the admin
extra = 0
min_num = 1
max_num = 1
can_delete = False
Then in the CakeAdmin I can do this to make the ingredients show up.
class CakeAdmin(admin.ModelAdmin):
inlines = [LinkedItemAdmin]