Im new in django , When im learning django from documentation .i tried to make api using serializers and Function Based views .the this shows type object 'Questions' has no attribute 'objects'
models.py
class Questions:
title = models.CharField(max_length=40)
description = models.TextField(max_length=50)
status = models.CharField(default='inactive', max_length=30)
created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
serializers.py
from rest_framework import serializers
from demoapp.models import Questions
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Questions
fields = (
'id',
'title',
'description',
'created_by',
)
urls.py
from django.urls import path
from demoapp.views import *
urlpatterns = [
path('poll', demoapp),
]
And Error is:
enter image description here
Related
Problem Description
I'm new to django-rest-framework and got a problem in my view. I have three models namely #User, #Profession and #StudentProfessions. I need to create an api-view that takes user_id as request-parameter and returns a list of all professions that belongs to a particular user_id.
Here's My Codes
profession_app >> models.py
from django.db import models
class Profession(models.Model):
profession_name = models.CharField(max_length=100)
def __str__(self):
return self.profession_name
User Model
I used the django default model.
student_profile_app >> models.py
from django.contrib.auth.models import User
from department_app.models import Department
from profession_app.models import Profession
from program_app.models import Program
from django.db import models
class StudentProfile(models.Model):
student_status = models.BooleanField()
phone_number = models.CharField(max_length=100)
year_of_study = models.CharField(max_length=100)
program_id = models.ForeignKey(Program, on_delete=models.CASCADE)
student_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name="student_id")
organization_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="organization_id")
profile_image = models.ImageField(upload_to='images/', blank=True)
field_supervisor_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="field_supervisor")
department_id = models.ForeignKey(Department, on_delete=models.CASCADE)
academic_supervisor_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="academic_supervisor")
def __str__(self):
return f'{self.student_id.username } Profile'
class StudentProfession(models.Model):
student_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="student_profession_id")
profession_id = models.ForeignKey(Profession, on_delete=models.CASCADE)
def __str__(self):
return f'{self.student_id.username } Profession'
student_profile_app >> views.py
from .models import StudentProfile, StudentProfession
def getStudentProfessions(request, studentId):
professions = StudentProfession.objects.filter(student_id=studentId)
return professions
And In My urls
from student_profile_app.views import getStudentProfessions
from rest_framework import routers
router.register('getStudentProfessions/<int:studentId>', getStudentProfessions, 'getStudentProfessions')
urlpatterns = router.urls
But when i run the server i got the following error
urlpatterns = router.urls
File "E:\Codes\FIP\fipEnv\lib\site-packages\rest_framework\routers.py", line 77, in urls
self._urls = self.get_urls()
File "E:\Codes\FIP\fipEnv\lib\site-packages\rest_framework\routers.py", line 338, in get_urls
urls = super().get_urls()
File "E:\Codes\FIP\fipEnv\lib\site-packages\rest_framework\routers.py", line 236, in get_urls
routes = self.get_routes(viewset)
File "E:\Codes\FIP\fipEnv\lib\site-packages\rest_framework\routers.py", line 152, in get_routes
extra_actions = viewset.get_extra_actions()
AttributeError: 'function' object has no attribute 'get_extra_actions'
First of all StudentProfession.student_id has bad model parameter set (its related to User model - it should be Student model).
Django rest framework uses viewset's for routers.
What you need is serializer which will represent your endpoint api structure and viewset.
I will write simple serializer and viewset for you but you really need to read docs.
After edits from comments:
Serializer class:
from rest_framework import serializers
#...other imports
class StudentProfessionSerializer(serializers.ModelSerializer):
class Meta:
model = StuedentProfession
fields = ('profession')
Viewset class (that's what you register in router !)
from rest_framework import viewsets, mixins
#...other imports
class StudentProfessionViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.RetrieveModelMixin):
serializer_class = StudentProfessionSerializer
queryset = StudentProfession.objects
def get_queryset(self):
student_id = self.kwargs.get('studentId')
return self.queryset.filter(student_id=student_id)
Some tips from me:
READ DOCS
you dont need to write "_id" suffix in ForeignKey fields (django make it automatically underhood - means that columns in your table will have _id suffix anyway) and then you can use params without this ugly _id... like this
StudentProfession.objects.filter(student=somestudentid)
your API should be constructed like
router.register(r'students/(?P<studentId>\d+)/professions', StudentProfessionViewSet, 'student-profession')
try not to use "real" ID's of objects in url - use UUID's instead - its safer
i am new here in django python, I am learning 2 table relations, primary key foreign key scenario, for that i am using existing django user model and create another model userprofile, I want to list data of user and profile, so for that i have created rest api, when i do run api http://127.0.0.1:8000/api/v1/users/, it gives me this error : 'User' object has no attribute 'user'. here i have added my whole code, can anyone please look my code and help me to resolve this issue ?
models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
class Songs(models.Model):
# song title
title = models.CharField(max_length=255, null=False)
# name of artist or group/band
artist = models.CharField(max_length=255, null=False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255, null=False)
dob = models.CharField(max_length=255, null=False)
address = models.CharField(max_length=255, null=False)
country = models.CharField(max_length=255, null=False)
city = models.CharField(max_length=255, null=False)
zip = models.CharField(max_length=255, null=False)
photo = models.CharField(max_length=255, null=False)
def __str__(self):
return "{} - {}".format(self.title, self.dob, self.address, self.country, self.city, self.zip, self.photo,
self.user)
serializers.py
from rest_framework import serializers
from .models import Songs
from .models import UserProfile
from django.contrib.auth.models import User
class SongsSerializer(serializers.ModelSerializer):
class Meta:
model = Songs
fields = ("title", "artist")
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('user', 'title', 'dob', 'address', 'country', 'city', 'zip', 'photo')
class UserSerializer(serializers.ModelSerializer):
user = UserProfileSerializer(required=True)
class Meta:
model = User
fields = ('url', 'email', 'first_name', 'last_name', 'password', 'user')
extra_kwargs = {'password': {'write_only': True}}
views.py
import rest_framework.generics
from rest_framework import generics
from .models import Songs
from .serializers import SongsSerializer
from .serializers import UserSerializer
from django.contrib.auth.models import User
from rest_framework import viewsets
class ListSongsView(generics.ListAPIView):
"""
Provides a get method handler.
"""
queryset = Songs.objects.all()
serializer_class = SongsSerializer
class UserViewSet(viewsets.ModelViewSet): #generics.ListAPIView, generics.RetrieveAPIView
# viewsets.ModelViewSet
queryset = User.objects.all()
#print(queryset.count());
#exit()
serializer_class = UserSerializer
First of all, I think you need to use a OneToOneField for the User - UserProfile relation. Otherwise, one user may have multiple profiles, which is not common practice.
Now regarding the problem, the User model doesn't have a user attribute. You need to use related_name to get access to the reverse related object.
To fix this problem, you can refactor your code to this:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
class UserSerializer(serializers.ModelSerializer):
user_profile = UserProfileSerializer(required=True) # rename this field
class Meta:
model = User
fields = ('url', 'email', 'first_name', 'last_name', 'password', 'user_profile')
extra_kwargs = {'password': {'write_only': True}}
I am building a backend for a web app using django rest framework. I have a profile model that has a user forieingkey referencing a django user. Everything is loading correctly except for one issue which is that the User field is not showing up in the django rest framework backend urls so that I can assign a user to the profile object i want to create... does anyone know why this is happening...
models.py:
class Profile(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE
)
synapse = models.CharField(max_length=25, null=True)
bio = models.TextField(null=True)
profile_pic = models.ImageField(
upload_to='./profile_pics/',
max_length=150
)
facebook = models.URLField(max_length=150)
twitter = models.URLField(max_length=150)
updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username + ' profile'
viewset:
from users.models import Profile
from users.api.serializers.ProfileSerializer import ProfileSerializer
from rest_framework import viewsets
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
lookup_field = 'user__username'
url:
from users.api.views.ProfileView import ProfileViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'', ProfileViewSet, base_name='profile')
urlpatterns = router.urls
serializer:
from rest_framework import serializers
from users.models import Profile
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = (
'id',
'user',
'synapse',
'bio',
'profile_pic',
'facebook',
'twitter'
)
depth=2
That happens when you set a depth bigger that 0, foreign key fields become not editable (if you send a POST with that field containing some value, DRF viewset would ignore it, and if the field is required, it will raise an exception).
One solution for that is to override to_representation() method of the serializer and set the depth and restore it to zero:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = (
'id',
'user',
'synapse',
'bio',
'profile_pic',
'facebook',
'twitter'
)
def to_representation(self, instance):
self.Meta.depth = 2
representation = super().to_representation(instance)
self.Meta.depth = 0
return representation
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'm building a django restful json API using rest_framework libraries, however it returns empty json [ ] when I submit a request to it, even though there's plenty of records in the DB table. Here' my Code
models.py
class Member(models.Model):
email = models.EmailField()
mobile = models.CharField(max_length=11, null=False)
username = models.CharField(max_length=20, null= False, help_text="Username")
password = models.CharField(max_length=15, null=False, help_text="Password")
mobile_id = models.CharField(max_length=100, null=True, blank=True)
joined_date = models.DateTimeField(auto_now_add=True)
serializers.py
class MemberSerializer(serializers.Serializer):
class Meta:
model = Member
fields = ('email', 'mobile', 'username', 'joined_date')
views.py
class MemberAPI(viewsets.ModelViewSet):
serializer_class = MemberSerializer
queryset = Member.objects.all()
urls.py
router = DefaultRouter()
router.register(r'member', MemberAPI, base_name='member')
urlpatterns = router.urls
I got it now. It appears, I was inheriting a base generic class of serialize in
serializers.py
I should have inherited from ModelSerializer like this
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = Member
fields = ('email', 'mobile', 'username', 'joined_date')