I have a model "Interview" and a model "Notes". Interview is a foreign key of Notes.
class Notes(models.Model):
notes = models.TextField(null=True)
interview = models.ForeignKey(Interview, null=True)
def __str__(self):
return self.interview
I am using http requests to GET and POST to the server.
How can I post notes to the server exactly since interview is a foreign key? Currently my post function looks like this:
saveNotes: function(interview, notes) {
$http({
method: 'POST',
url: apiroute + '/notes',
data: {
"notes": notes,
"interview": {
//attr of interview
}
}
}).success(callback);
}
And this looks to be correct but I am being met with:
POST http://127.0.0.1:8000/app/api/notes 500 (INTERNAL SERVER ERROR)
I used "notes/" as my url and I got:
POST http://127.0.0.1:8000/student/api/notes/ 400 (BAD REQUEST)
Can someone give a guess as to what my issue might be?
Thanks!
EDIT: Here are my serializer files. Interview is replaced by Lecture
class LectureSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Lecture
fields = ('id', 'lecture_no', 'title', 'youtubeLink', 'course', 'keywords')
class NotesSerializer(serializers.HyperlinkedModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Notes
fields = ('id', 'notes', 'lecture')
api views:
class LectureViewSet(viewsets.ModelViewSet):
serializer_class = LectureSerializer
def get_queryset(self):
course_id = self.request.query_params.get('course',False)
if course_id:
lectures = Lecture.objects.filter(course=course_id)
else:
lectures = Lecture.objects.all()
return lectures
class NotesViewSet(viewsets.ModelViewSet):
queryset = Notes.objects.all()
serializer_class = NotesSerializer
you need only to send the interview_id value:
data: {
"notes": notes,
"interview_id": interview_id
}
and in serializers.py define your serializers as follow:
class InterviewSerializer(serializers.ModelSerializer):
class Meta:
model = Interview
class NoteSerializer(serializers.ModelSerializer):
interview = InterviewSerializer(read_only=True, many=True)
class Meta:
model = Note
Related
I have two models User and Profile which is related by One to One relation. I have registered users who can login and if profile is not created for user, then user can create one profile (using POST) and if profile is created then user can update their profile (using PATCH).
Models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='profile')
locality = models.CharField(max_length=70, null=True, blank=True)
city = models.CharField(max_length=70, null=True, blank=True)
address = models.TextField(max_length=300, null=True, blank=True)
pin = models.IntegerField(null=True, blank=True)
state = models.CharField(max_length=70, null=True, blank=True)
profile_image = models.ImageField(upload_to='user_profile_image', blank=True, null=True)
Serializer.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model= Profile
fields = ['user', 'locality','city','address','pin','state','profile_image']
Views.py
class UserProfileDataView(APIView):
renderer_classes = [UserRenderer]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
serializer = ProfileSerializer(request.user.profile, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request, format=None):
serializer = ProfileSerializer(data= request.data, context={'user': request.user})
serializer.is_valid(raise_exception=True)
serializer.save()
return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED
)
def patch(self, request, format=None):
item = Profile.objects.get(user = request.user)
serializer = ProfileSerializer(item ,data = request.data, partial=True, context={'user': request.user.profile})
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({'msg':'Profile Updated Successfull'}, status = status.HTTP_200_OK)
API using Redux Toolkit
editProfile: builder.mutation({
query: (access_token, actualData ) => {
return {
url:'editprofile/',
method:'PATCH',
body:actualData,
headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'}
}
}
}),
createProfile: builder.mutation({
query: (access_token, actualData ) => {
return {
url:'createprofile/',
method:'POST',
body:actualData,
headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'}
}
}
}),
})
})
When I create profile from django admin for a user and tries to update its data, then I only get {"msg": "Profile Updated Successfull"} in network console but data is not reflected in database. and also when I try to create profile of user from Fronend using React, it gives error msg {"errors": {"user": ["This field is required."]}}
I think you missed setting the user_id field in the request payload. In the ProfileSerializer, you need to change the user field into user_id.
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model= Profile
fields = ['user_id', 'locality','city','address','pin','state','profile_image']
extra_kwargs = {
'user_id': {'source': 'user'}
}
And in the frontend, you need to set the user_id attribute in the actual_data object.
Or in the backend, you can add that field manually in the post method of the UserProfileDataView class.
class UserProfileDataView(APIView):
...
def post(self, request, format=None):
input_data = request.data
input_data['user_id'] = request.user.id
serializer = ProfileSerializer(data= input_data, context={'user': request.user})
serializer.is_valid(raise_exception=True)
serializer.save()
return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED
)
models file
class Posting(models.Model):
company = models.CharField(max_length=250)
recruiter = models.CharField(max_length=250)
image = models.ImageField(upload_to='postings/%Y/%m/%d/', null=True)
description = models.TextField()
position_title = models.CharField(max_length=150)
## Based on LinkedIn
# Auto adds creation date
creation_date = models.DateTimeField(auto_now_add=True)
# If 0, unpaid; if more than 0, paid (can be used to diffrentiate in postings frontend)
pay_range = models.CharField(max_length=250)
location = models.CharField(max_length=1000)
# Number of current applicants (can be used to encourage people)
num_applicants = models.IntegerField(default=0)
def __str__(self):
return self.position_title
class Question(models.Model):
qTypes=[('T','text'),('TA','textarea'),('C','choice')]
question=models.CharField(max_length=10000)
type=models.CharField(max_length=10,choices=qTypes)
post=models.ForeignKey(Posting,on_delete=models.CASCADE)
choices=models.TextField(null=True,blank=True)
serializer
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields = ('id','type','question','post')
class PostingSerializer(serializers.ModelSerializer):
question=QuestionSerializer(many=False)
class Meta:
model = Posting
fields = ('id', 'company', 'recruiter', 'image', 'description', 'creation_date', 'pay_range', 'location', 'num_applicants', 'position_title','question')
i want to retrieve the post with it's questions like this i could retrieve the data of the question with its post but i dont want that
What I want to do is post a ListLink object, which contains Link objects, to the database.
The Link objects are added by input field by the user and stored in the state until a request is sent for them to be saved in the database.
I am trying to make a post request to DRF, but I am getting the following response:
"Invalid data. Expected a dictionary, but got list."
I am using axios to make the request:
Home.jsx
handleSave = event => {
event.preventDefault();
return axios({
method: 'post',
url: 'http://localhost:8000/api/lists/',
headers: {
'Authorization': 'Token ' + localStorage.getItem('token')
},
data: {
links: this.state.links,
name: this.state.listName
}})
.then(res => {
console.log(res);
});
}
This is the state I am using to save the lists in:
this.state = {
listName: 'Link List',
listDescription: 'Add description here',
listURL: '',
currentLink: 'https://www.example.com',
links: []
};
Here are my models and serializers:
LinkList
class LinkList(models.Model):
owner = models.ForeignKey(
User,
related_name='lists',
on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.CharField(max_length=250)
public = models.BooleanField(default=False)
links = models.ManyToManyField(
Link,
related_name='linklists')
def __str__(self):
return "%s - %s" % (self.owner, self.name)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
Serializer:
class LinkListSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="lists-detail")
owner = serializers.ReadOnlyField(source='owner.username')
links = LinkSerializer()
class Meta:
model = LinkList
fields = ['url', 'owner', 'name', 'public', 'links']
Link
class Link(models.Model):
link = models.URLField(max_length=200)
def __str__(self):
return "%s" % (self.link)
Serializer:
class LinkSerializer(serializers.ModelSerializer):
class Meta:
model = Link
fields = ['url', 'link']
You can try to add many=True parameter to LinkSerializer but you will need to handle this list yourself (pop links attribute and manually create every link object).
class LinkListSerializer(serializers.ModelSerializer):
...
def create(self, validated_data):
with transaction.atomic(): # optional - ensure that changes will be rolled back on error
links = validated_data.pop('links', [])
instance = super().create(validated_data)
for l in links:
instance.links.create(link=l)
return instance
I am trying to make it so that I can POST and update database rows from my angularJS app but I seem to be having trouble adding new entries to my database.
Things are posted without error but when I go and check the database then all added data is "None".
I have written this method to save Notes with a corresponding Lecture ID, where Lecture is an attribute of Notes.
saveNotes: function(notes, lecture_id, callback) {
$http({
method: 'POST',
url: apiRoute + 'notes/',
data: {
"notes": notes,
"lecture_id": lecture_id
}
}).success(callback);
}
I have written these views:
class LectureViewSet(viewsets.ModelViewSet):
serializer_class = LectureSerializer
def get_queryset(self):
course_id = self.request.query_params.get('course',False)
if course_id:
lectures = Lecture.objects.filter(course=course_id)
else:
lectures = Lecture.objects.all()
return lectures
class NotesViewSet(viewsets.ModelViewSet):
queryset = Notes.objects.all()
serializer_class = NotesSerializer
And these serializers:
class LectureSerializer(serializers.ModelSerializer):
class Meta:
model = Lecture
fields = ('id', 'lecture_no', 'title', 'youtubeLink', 'course', 'keywords')
class NotesSerializer(serializers.ModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Notes
fields = ('id', 'notes', 'lecture')
Can anyone spot the error that is causing this addition of "None" values? Also, is there a way to make these fields update instead of post new ones?
Thanks!
Included models:
class Lecture(models.Model):
lecture_no = models.IntegerField(null=True)
title = models.CharField(max_length=128, unique=True, null=True)
youtubeLink = models.CharField(max_length=128, unique=True, null=True)
course = models.ForeignKey(Course, null=True)
keywords = models.TextField(max_length=300, null=True)
#Could add Next Rerun Date & Time
def __str__(self):
return self.title
class Notes(models.Model):
notes = models.TextField(null=True)
lecture = models.ForeignKey(Lecture, null=True)
def __str__(self):
return str(self.notes)
I have two models:
class Lecture(models.Model):
lecture_no = models.IntegerField(null=True)
title = models.CharField(max_length=128, unique=True, null=True)
youtubeLink = models.CharField(max_length=128, unique=True, null=True)
course = models.ForeignKey(Course, null=True)
keywords = models.TextField(max_length=300, null=True)
#Could add Next Rerun Date & Time
def __str__(self):
return self.title
class Notes(models.Model):
notes = models.TextField(null=True)
lecture = models.ForeignKey(Lecture, null=True, related_name='lecture')
def __str__(self):
return self.notes
These serializers:
class NotesSerializer(serializers.ModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Notes
fields = ('id', 'notes', 'lecture')
class KeywordSerializer(serializers.ModelSerializer):
lecture = LectureSerializer(read_only=True, many=True)
class Meta:
model = Keyword
fields = ('id', 'notes', 'lecture')
and these views:
class LectureViewSet(viewsets.ModelViewSet):
serializer_class = LectureSerializer
def get_queryset(self):
course_id = self.request.query_params.get('course',False)
if course_id:
lectures = Lecture.objects.filter(course=course_id)
else:
lectures = Lecture.objects.all()
return lectures
class NotesViewSet(viewsets.ModelViewSet):
queryset = Notes.objects.all()
serializer_class = NotesSerializer
and I'm trying to make it so that I can update the "notes" field for a specific lecture. Currently I'm using a POST http request:
saveNotes: function(notes, lecture_id, callback) {
$http({
method: 'POST',
url: apiRoute + 'notes/',
data: {
"notes": notes,
"lecture_id": lecture_id
}
}).success(callback);
}
But this just adds a new row to the database every time. How do you update fields instead?
Thanks