I have completed my models and I am trying to customise the admin model for a particular model.
Here is my admin.py
from project.base.models import *
from django.contrib import admin
from django import forms
class StaffModuleForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = StaffModule
class StaffModuleAdmin(admin.ModelAdmin):
form = StaffModuleForm
class Meta:
pass
Modules = [UserProfile, Student, Module, StaffModule, Exercise, Result]
admin.site.register(Modules)
and here is the model in question
class StaffModule(models.Model):
user = models.ForeignKey(User)
modules = models.ManyToManyField(Module) # Field name made lowercase.
department = models.CharField(max_length=6)
def __unicode__(self):
return str(self.user)
Here is the error I am currently unable to pass:
AttributeError at /admin/base/staffmodule/2/
type object 'StaffModuleAdmin' has no attribute '_meta'
Here is the trace: http://pastebin.com/tCJ9Q978
I would really appreciate some help, as I believe I am following the django admin docs and i am not quite sure what the issue is.
Thanks.
The problem is in this:
class StaffModuleAdmin(admin.ModelAdmin):
form = StaffModuleForm
class Meta:
pass
Inner Class Meta should not be defined for the admin.ModelAdmin class.
Related
I created a serializer and an API endpoint so I can retrieve some data from a Django DB in my React app but getting this error message:
AttributeError: 'ProgrammingChallengesView' object has no attribute 'get'
Here is my models.py:
#creating programming challenges
class ProgrammingChallenges(models.Model):
challenge_id = models.AutoField(primary_key=True)
challenge_name = models.CharField(max_length=200)
challenge_description = models.TextField()
challenge_expectations = models.TextField()
my serializer:
from accounts.models import ProgrammingChallenges
...
class ProgrammingChallengesView(serializers.ModelSerializer):
class Meta:
model = ProgrammingChallenges
fields = '__all__'
and my urls.py:
path('api/programming_challenges/', ProgrammingChallengesView, name='programming_challenges'),
Thanks to the comments; I clearly didn't understand that a serializer only transforms my data to make it available through an API. I still had to create a view for my API's endpoint.
I opted to create a ReadOnlyModelView because I only want to GET data from this endpoint.
Here is what I wrote in my views:
class ProgrammingChallengesView(ReadOnlyModelViewSet):
serializer_class = ProgrammingChallengesSerializer
queryset = ProgrammingChallenges.objects.all()
#action(detail=False)
def get_list(self, request):
pass
and in my urls.py:
path('api/programming_challenges/', ProgrammingChallengesView.as_view({'get':'list'}), name='programming_challenges'),
I think you shouldn't hurry read the docs again. You are trying to use serializers as views.
Models - are representation of db tables as class.
Serializer serializes the data to json.
View accepts the reqeust from client and returns a Response.
Code shoudld be:
models.py
class ProgrammingChallenge(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
expectations = models.TextField()
Your model name should be ProgrammingChallenge(singular) not ProgrammingChallenges(plural).
You should't add prefix challenge before all field names. Because we already know that the fields are in a Model called ProgrammingChallenge. And it is easy to access them like ProgrammingChallenge.name than ProgrammingChallenge.challenge_name
You don't have to add field id manually. Django model automatically adds id field as primary_key
serializer.py
from accounts.models import ProgrammingChallenge
...
class ProgrammingChallengeSerializer(serializers.ModelSerializer):
class Meta:
model = ProgrammingChallenge
fields = '__all__'
No problem in serialize.
Now, main problem is you don't have any view. You definetly read docs. You can use APIView, generic views or viewset. In this example i'm going to use ViewSet that handles CRUD operations built in.
viewsets.py
from rest_framework.viewsets import ModelViewSet
from .models import ProgrammingChallenge
from .serializers import ProgrammingChallengSerializer
class ProgrammingChallengViewSet(ModelViewSet):
queryset = ProgrammingChallenge.objects.all()
serializer_class = ProgrammingChallengeSerializer
urls.py
from rest_framework.routers import SimpleRouter
from .viewsets import ProgrammingChallenge
router = SimpleRouter()
router.register('challengr', ProgrammingChallengeViewSet)
urlpatterns = router.urls
Another advantage of using viewset, it also generate all endpoint for it's CRUD methods automatically via routes.
It should help you to start your first project.
AGAIN, READ THE DOCS!
In my django app I want to set focus to the first CharField (task) when the page loads.
my models.py is
from django.db import models
class ListModel(models.Model):
task = models.CharField(max_length=255)
status = models.BooleanField(default=False)
def __str__(self):
return f"{self.task} : {str(self.status)}"
and forms.py is
from django.forms import ModelForm
from .models import ListModel
class ListForm(ModelForm):
class Meta:
model = ListModel
fields = ["task", "status"]
I have tried adding the following widget in my CharField (in models.py):
task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True})
but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput'
I have also tried adding the following to the ListForm class (in forms.py):
def __init__(self):
self.fields['task'].widget.attrs.update(autofocus = 'autofocus')
though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField?
You are confusing model fields (which are used to store data in the database), and form fields, which are used to obtain, validate and clean data the user has entered.
You thus work with:
from django.forms import ModelForm
from django import forms
from .models import ListModel
class ListForm(ModelForm):
# forms ↓
task = forms.CharField(
max_length=255,
# forms ↓
widget=forms.TextInput(attrs={'autofocus': True})
)
class Meta:
model = ListModel
fields = ['task', 'status']
In djnago I have created Download model and it worked as expected but later when I tried to add new model 'Model' it just showing
AttributeError: 'Music' object has no attribute 'model'.
models.py looks like this:
from django.db import models
# Download/models.py.
class Download(models.Model):
name = models.CharField(max_length=50)
discription = models.CharField(max_length=50)
link = models.CharField(max_length=50)
imgages = models.ImageField(upload_to='media/')
def __str__(self):
return self.name
class Music(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.name
and here is an admin file
# Download/admin.py
from django.contrib import admin
from .models import Download,Music
# Register your models here.
admin.site.register(Download,Music)
If you pass two parameters to the register function, the first one is the model, and the second one is the ModelAdmin class for that model. Here you use it to register two models at once.
You can register a model without a ModelAdmin [Django-doc] by only specifying the model, but you thus can not specify multiple ones. You thus register the models with:
from django.contrib import admin
from .models import Download,Music
admin.site.register(Download)
admin.site.register(Music)
in Music you have self.name and I suppose you mean self.title
This is my forms.py file!!!
from django import forms
from . models import URLModel
class URLForm(forms.ModelForm):
class Meta:
model = 'URLModel'
fields = ['url']
This is my models.py file
from django.db import models
# Create your models here.
class URLModel(models.Model):
url=models.URLField(unique=True)
short=models.CharField(max_length=200,unique=True)
def __str__(self):
return self.url
Now i just wanted to ask that why this error is coming and i have revieved and i cant observe any error for real...please help
# Remove single quote from your model specification in forms.py
from django import forms
from .models import URLModel
class URLForm(forms.ModelForm):
class Meta:
model = URLModel
fields = ('url',)
This is my first time using Django and I am completely stuck at how to use ModelForms in my project. I have been able to follow the online tutorials this far but without ModelForms(to add data into a Postgresql database), I can't proceed onward. I am trying to simply make a form page that lets the users add a few inputs (2 datefields and 1 textfield) and by submitting that form, the data will be added to the database.
The error I have been getting is:
AttributeError: 'Hyuga_Requests' object has no attribute 'name' [where Hyuga_Request is a class set in the models.py]
models.py
from __future__ import unicode_literals
from django.db import models
from django.forms import ModelForm
class Hyuga_Requests(models.Model):
name = models.CharField(max_length=50)
s_date = models.DateField(auto_now=True)
e_date = models.DateField(auto_now=True)
reason = models.TextField(max_length=500)
def __unicode__(self):
return self.name
views.py
from django.shortcuts import render
from django import forms
from .forms import Hyuga_RequestForm
def create_req(request):
form = Hyuga_RequestForm()
context = {"form":form,}
return render(request,"request_form/requestform.html", context)
forms.py
from django import forms
from .models import Hyuga_Requests
from django.forms import ModelForm
class Hyuga_RequestForm(forms.ModelForm):
class Meta:
model = Hyuga_Requests()
fields = ['name','s_date','e_date','reason']
Please help this noobie...
Don't instantiate the model in the class Meta inside the Hyuga_RequestForm class.
model = Hyuga_Requests() should be model = Hyuga_Requests
model = Hyuga_Requests() -> model = Hyuga_Requests
The error come because you are calling the model on the form.
from django import forms
from .models import Hyuga_Requests
from django.forms import ModelForm
class Hyuga_RequestForm(forms.ModelForm):
class Meta:
model = Hyuga_Requests
fields = ['name','s_date','e_date','reason']
Note: i suggest to you use on the any class you define on python not use "_", you can check more about PEP8 and code styles here: https://www.python.org/dev/peps/pep-0008/