I want to perform Update and Delete operation in Django rest framework, I did Get and Post operation. I'm new to django, Please help me to do Update and Delete operation.
views.py
class StudentViews(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
models.py
class Student(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
contact_number = models.CharField(max_length=12, blank=True, null=True)
email = models.EmailField(max_length=100, blank=True, null=True)
address = models.CharField(max_length=500, blank=True, null=True)
serializers.py
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
urls.py
router = routers.DefaultRouter()
router.register('api/student', views.StudentViews)
urlpatterns = [
path('', include(router.urls)),
]
You can do those operations(PUT,PATCH and DELETE) in the api/student/1234/ end-point, where the 1234 is the PK of the instance to be deleted or updated.
You can refer more related to the end-point which is created buy the router automatically here, DefaultRouter--[DRF-DOC]
Related
I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address...
So I modified admin.py:
from django.contrib import admin
from .models import Todo, Account
from django.contrib.auth.models import User
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Accounts'
class TodoAdmin(admin.ModelAdmin):
readonly_fields = ('created',)
inlines = (AccountInline, )
admin.site.unregister(User)
admin.site.register(Todo, TodoAdmin)
But got back:
<class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'.
So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE):
from django.db import models
from django.contrib.auth.models import User
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.CharField(max_length=100)
firstname = models.CharField(max_length=30)
lastname = models.CharField(max_length=50)
company = models.CharField(max_length=5)
def __str__(self):
return self.user.username
class Todo(models.Model):
title = models.CharField(max_length=100)
datetime = models.DateTimeField()
memo = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
datecompleted = models.DateTimeField(null=True, blank=True)
important = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
account = models.ForeignKey(Account, on_delete=models.CASCADE)
def __str__(self):
return self.title
But I still have the error, and I don't have any Users in the admin panel anymore
You accidentally wrote unregister for Users in your admin.py file. It should be admin.site.register(User)
You misinterpretted the error: the error states that you don't have a foreign key in your Account model to Todo.
This means your inline admin code isn't correct as it's expecting the other way around.
I want to assign a User to a Model in django, I created a custom User model and sign-up/sign-in Forms but now I want to Assign a User model to another model named Customer whenever a new user is Created Here he the Customer model
class Customer(models.Model):
id = models.AutoField(primary_key=True)
User = models.OneToOneField(
Account, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, default='0', null=True, blank=True)
address = models.CharField(
max_length=200, default=' ', null=True, blank=True)
city = models.CharField(max_length=200, default=' ', null=True, blank=True)
def __str__(self):
if self.name == None:
return "ERROR-CUSTOMER NAME IS NULL"
return self.name
Note: I can assign the User manually in the Database and It lists All the Users but I want it to do it itself when a new user is created
I think it would be better to extend the User model, and add more fields rather than creating a new model (which has a User onetoonefiled in it).
Something like this:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
This is the kind of approach I use in my projects.
Here you have the default User model fields:
User model default fields
You don't need to add these in your Profile class.
I based this on this article: How to extend User Django Model
don't forget to add to the admin.py:
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
to see the Profiles in the admin page
Got it fixed by setting the user in the Customer model when a user is created
Customer.objects.create(user=request.user, name=username, email=email, phone=phone)
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')
i just defined new class for my project. When I run server i dont recive errors just dont appears on the admin-django Panel.
Here is the new class from models.py
class Stock_Clinicas(models.Model):
organization = models.ForeignKey(Organization, null=True, blank=True, on_delete=models.SET_NULL)
products = models.ForeignKey(Products, null=True, blank=True, on_delete=models.SET_NULL)
provider = models.ForeignKey(Provider, null=True, blank=True, on_delete=models.SET_NULL)
stock_min = models.DecimalField('Stock minimo', max_digits=10, decimal_places=0)
stock_opt = models.DecimalField('Stock optimo', max_digits=10, decimal_places=0)
stock_act = models.DecimalField('Stock actual', max_digits=10, decimal_places=0, default=0)
and here my admin.py. i'll put all code.
from django.contrib import admin
from stock.models import *
from .models import Organization, OrganizationUser, OrganizationOwner
class OwnerInline(admin.StackedInline):
model = OrganizationOwner
raw_id_fields = ('organization_user',)
class OrganizationAdmin(admin.ModelAdmin):
inlines = [OwnerInline]
list_display = ['name', 'is_active']
prepopulated_fields = {"slug": ("name",)}
class OrganizationUserAdmin(admin.ModelAdmin):
list_display = ['user', 'organization', 'is_admin']
raw_id_fields = ('user', 'organization')
class OrganizationOwnerAdmin(admin.ModelAdmin):
raw_id_fields = ('organization_user', 'organization')
class Stock_ClinicasAdmin(admin.ModelAdmin):
list_display = ('stock_min', 'stock_opt', 'stock_act')
admin.site.register(Stock_Clinicas, Stock_ClinicasAdmin)
admin.site.register(Organization, OrganizationAdmin)
admin.site.register(OrganizationUser, OrganizationUserAdmin)
admin.site.register(OrganizationOwner, OrganizationOwnerAdmin)
Forget said, when I use syncdb the tables aren't created. I'm using Django 1.5.
dont resolved yet
You have a few issues:
class Stock_ClinicasAdmin(admin.ModelAdmin):
list_display = ('Stock Minimo', 'Stock Actual', 'Stock Optimo')
You don't have any fields called Stock Minimo, the field is stock_min, so you need to adjust this.
If you just created this app, make sure:
You add it to INSTALLED_APPS; it should have stock,
You might want to run manage.py makemigrations and manage.py migrate to create the tables.
In admin.py, rename your modelAdmin class to Stock_ClinicasAdmin (or anything else that your model name), and add this after the modelAdmin class declaration:
admin.register(Stoc_Clinicas, Stock_ClinicasAdmin)
I have models.py like this
class Faculty(TimeStampedModel):
_registry = []
faculty_code = models.CharField(max_length=30, unique=True)
name = models.CharField(max_length=255)
date_of_birth = models.DateField(default=datetime.date.today)
age = models.IntegerField()
current_subjects = models.CharField(max_length=255)
research_interest = models.CharField(max_length=255, blank=True)
joining_year = models.CharField(
max_length=5, )
projects = models.CharField(max_length=255, blank=True)
now the user can't add Faculty but can view those created from the admin. In order to do so the user must enter the faculty_code in a form after which I have to get the other fields and show it to the user.
I don't how to implement this. I mean anytime we create a django-form and use POST method it creates a new object I don't want that. User should send a 'GET' request to fetch data of other fields of the class.
I don't think a form is necessary for this, use a DetailView.
url
urlpatterns = patterns('',
url(r'^faculty/(?P<slug>\w+)/$', FacultyDetail.as_view()),
)
view
from django.views.generic.detail import DetailView
class FacultyDetail(DetailView):
model = Faculty
slug_field = 'faculty_code'
More info:
docs
ccbv