Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Migrate new field with value from old field
I have a model with a field pub_date. I want to add a new field created_date, which should take the value from pub_date. Is there a simple way to achieve this? -
Run Django view as http.server
If I run python -m http.server 8080 on my console in order to be able to open an isolated html file containing a d3.js interactive map which loads local data it works well. When I try to render the same html file as a template called by a Django view via an url, the console.log advertises my that the javascript variable where I assign the loaded local data is undefined. Anybody knows where is the problem? -
Using Unaccent in Django Model database function
I have the unaccent extension installed in Postgres and simple filters are working fine in my Django app, for example: q = 'hello' queryset.filter(name__unaccent__startswith=q) I'm now trying to annotate the queryset result with the search index: queryset.annotate(search_index=StrIndex(Lower('name'), Value(q))) That works fine by itself for unaccented text, but I'm trying to figure out a way to apply UNACCENT to the name variable. Essentially: SELECT -- This is what I want! STRPOS(LOWER(UNACCENT(core_ingredient.name)::text), 'hello') AS search_index_unaccented, STRPOS(LOWER(core_ingredient.name), 'hello') AS search_index_basic FROM -- ... I've tried: # This has no effect, gives same query / result as above queryset.annotate(search_index=StrIndex(Lower('name__unaccent'), Value(q))) I've seen this answer: How use `unaccent` with full text search in django 1.10? but feel like that shouldn't be needed. -
django forms exclude values from choicefield that are already into database
I want to exclude those options from the ChoiceField in the forms that has been already selected and are into the database. Below is the Code. models.py SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) class Publish(models.Model): dates = models.CharField(max_length=255, choices = SEMESTER_CHOICES) def __str__(self): return self.dates form.py SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) class PublishForm(forms.ModelForm): def __init__(self, **kwargs): super(PublishForm, self).__init__(self, **kwargs) selected_choices = [i.dates for i in Publish.objects.all()] self.fields['dates'].SEMESTER_CHOICES = ({(k, v) for k, v in SEMESTER_CHOICES if k not in selected_choices}) class Meta: model = Publish fields = ['dates'] view.py def add(request): if request.method == 'POST': form = PublishForm(request.POST) if form.is_valid(): form.save() return redirect('mainapp:add') else: form = PublishForm() context = { 'form' : form } return render(request, 'mainapp/add.html', context) What am I doing wrong? Ive followed these 2 links here. link1 and link2. Any suggestions please. Also I am getting the error : 'PublishForm' object has no attribute 'get' Thank you -
Django template don't see my first element of a list
I have {% if author_list|length %} <li> {{ author_list|length }}</li> 0 elements in: nothing 1 elements in: nothing too 2 elements in: 2 How does it work? In my view my list shows correctly, btw -
Django filter with 'day-month' together without consider year
I want to filter my datetime field with 1 month after from today without consider year. How can I do it with query class Contract(models.Model): title = models.CharField(max_length=200, null=True) date = models.DateField() Example filter between: From: Today Day and Month: 01-05 (%m-%d) To: One Month Later: 02-05 (%m-%d) -
Page not found 404 for media url, getting images name from database Django 3.0.1
This is my project folders I first decided to set my media url and my media root on my settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/portfoliopicture/' On my admin side, I decided to give it an url pattern in local, since I tho while I am in local it wouldnt be able to get my URL "I wasnt sure at all since on the documentation nothing was talking about url pattern" if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have define my model this way. image = models.ImageField(upload_to='portfoliopicture/') And using the url to get the image, src="{{ portfolio.image.url }}" Inside my template html, this is how i call it, This issue I am getting is so weird, It's like it isnt able to find the url path.. This is the message error I am getting. coming from the network tab I would like to understand. Why am I having this issue when the url seems to be defined. Is it an issue with the way I'm calling the folders? I am clearly missing something here. -
How to use a pre_delete signal to universally prevent delete?
I have a common field is_active = models.BooleanField() on all my models. I want to create a universal override to the delete function so that instead of removing records from the database, is_active = False. I understand the best way to do this is a pre_delete signal rather than overriding delete() itself as delete() is not called in bulk operations. I have tried the following implementation: @receiver(pre_delete) def delete_obj(sender, instance, **kwargs): """Override delete() to set object to inactive.""" return instance.is_active == False However this still results in objects being deleted from the database. How do I correct this? -
400 Bad request error using POST in django-rest-framework
i am new at django-rest-framework so i am trying to develop a project management app so i tried to POST a form data to the API ,and i keep getting 400 bad request error and ["this field is required"] for all fields main.js: function getProjectReq(){ ax.get("/employees/").then((response) => { for (let obj of response.data){ document.getElementById('project_employees').insertAdjacentHTML('afterbegin',` <option value ="${obj.url}">${obj.f_name} ${obj.l_name}</option>`) } }) function add_Project(){ let form = document.forms.addProject; let data = new FormData(form); let json = formDataToJSON(data); let json1 = JSON.stringify(json) console.log(json1); ax({ method:'post', url:'project/create', data:{json1}, headers:{ 'Content-Type': 'application/json' } }).then((response)=> { console.log(response.data); window.location = "project/"+response.data.id; }).catch((error)=> { console.log(error.response.data) }) } serializers.py : class ProjectSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) tasks = TaskSerializer(many=True) leader = EmployeeSerializer() p_employees = EmployeeSerializer(many =True) #tasks = TaskSerializer(many =True) materials = MaterialsSerializer(many =True) class Meta : model = Project fields = ['url','id','name','statuts','description','leader','p_employees', 'start_date','end_date','tasks','materials'] def get_url(self, obj): # request request = self.context.get("request") return obj.get_api_url(request=request) -
Django finds two objects in a filter() query but fails to loop through them
Never had this happen before. The following is a method I've added to a model. It just checks that none of the LineItems related to it have a reconciliation_date set. The method is always returning False so I added a few logger.warning() lines to see what is happening. As you can see in the image, the method executes, finds that the model object has two related line_items and then ignores the for loop. Very strange! @property def is_reconciled(self): """Checks if JournalEntry has reconciled lineitems""" logger.warning('Starting is_reconciled() model property..') line_items = LineItem.objects.filter(journal_entry=self.id) #logger.warning('Found ' + str(len(line_items)) + ' line items') for item in line_items: logger.warning('Doing loop 1. Line_item is '+ line_item) if item.reconciliation_date is not None: logger.warning('Reconciliation date is not none here') return True return False -
“This field is required” when all fields are filled in Django
I have removed some useless branch from my git and now one function on my website does not work. It is about add_recipe http://lui93.pythonanywhere.com/accounts/add_recipe/ does not work. When I am trying to add it and every field is filled, i push the button "add recipe" it shows that ingrediend field is required. View: def add_recipe(request): add_recipe = RecipeForm(request.POST) print(add_recipe['ingredients'].value()) if add_recipe.is_valid(): add_recipe.save() return redirect('success_added_recipe') return render(request, 'drinks/add_recipe.html', {'RecipeForm': add_recipe}) Form: class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['recipe_name', 'preparation', 'ingredients', 'recipe_image'] debug.log (0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() (0.001) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient" WHERE "drinks_ingredient"."id" IN (12); args=(12,) (0.000) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient"; args=() "POST /accounts/add_recipe/ HTTP/1.1" 200 1637 (0.002) model: class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) recipe_image = models.ImageField(upload_to='images/', default='') def __str__(self): return self.recipe_name template: <h1>Add recipe</h1> <form method="post" action="{% url 'add_recipe' %}"> {% csrf_token %} <table> {{RecipeForm}} </table> <input type="submit" value="Add recipe"/> </form> -
Fallback shouldn't apply all fields
i think i have a big problem I keep fields like title , rating ,popularity ,... on Production Model. my rating and popularity fields are integer and they will be null when they are created. And side of model translation , i am using Fallback to avoid null for title but i don't need fallback for rating , popularity , if they are null , fallback show other_language value which defined in tuple, but i want to show null value settings.py LANGUAGE_CODE = 'tr' gettext = lambda s: s LANGUAGES = ( ('tr', _('Turkish')), ('ru', _('Russian')), ('es', _('Spanish')), ('ar', _('Arabic')), ) MODELTRANSLATION_LANGUAGES = ('tr', 'ru', 'es', 'ar') MODELTRANSLATION_AUTO_POPULATE = True MODELTRANSLATION_ENABLE_FALLBACKS = True here is translation.py from modeltranslation.translator import translator, TranslationOptions from cosmeclub.products.models import Product class ProductTranslationOptions(TranslationOptions): fields = ('title', 'rating', 'popularity', 'weekly_popularity', 'subcategory_order', 'last_reviewed_at') required_languages = ('tr', 'ru', 'es', 'ar') translator.register(Product, ProductTranslationOptions) -
Add a notification system to my messaging system
Hey so I have made a private messaging system using django-channels. But, I wanted to add a notification system where when a message is unread, a 1 or how many unread notifications you have next to the messages button in the navbar. I have tried django-notifications-hq but I get this error when I add it to my installedd apps: ModuleNotFoundError: No module named 'django.utils.six'. I later found out that django tool six out of django 3.0. I was wondering if anyone would know a way to implement this. Help is appreciated! Thanks! -
How can GORM's FirstOrCreate() method (or Django's get_or_create) ensure that just one row is created?
I'm considering using GORM for an application and was looking into how FirstOrCreate works, and it seems that it uses two database operations. Consider this example script: package main import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/sirupsen/logrus" ) type User struct { gorm.Model Name string Age uint } func main() { db, err := gorm.Open("sqlite3", "examplegorm.db") if err != nil { logrus.Fatalf("open db: %v", err) } defer db.Close() db.LogMode(true) db.AutoMigrate(&User{}) var user User db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrCreate(&user) } Upon running this and inspecting the logs, I see that (aside from the auto-migration) it uses two queries, one SELECT and one INSERT: kurt@Kurts-MacBook-Pro-13 ~/D/Scratch> go run gorm_example.go (/Users/kurt/Documents/Scratch/gorm_example.go:23) [2020-01-05 09:09:10] [1.03ms] CREATE TABLE "users" ("id" integer primary key autoincrement,"created_at" datetime,"updated_at" datetime,"deleted_at" datetime,"name" varchar(255),"age" integer ) [0 rows affected or returned ] (/Users/kurt/Documents/Scratch/gorm_example.go:23) [2020-01-05 09:09:10] [0.86ms] CREATE INDEX idx_users_deleted_at ON "users"(deleted_at) [0 rows affected or returned ] (/Users/kurt/Documents/Scratch/gorm_example.go:26) [2020-01-05 09:09:10] [0.28ms] SELECT * FROM "users" WHERE "users"."deleted_at" IS NULL AND (("users"."name" = 'non_existing')) ORDER BY "users"."id" ASC LIMIT 1 [0 rows affected or returned ] (/Users/kurt/Documents/Scratch/gorm_example.go:26) [2020-01-05 09:09:10] [0.31ms] INSERT INTO "users" ("created_at","updated_at","deleted_at","name","age") VALUES ('2020-01-05 09:09:10','2020-01-05 09:09:10',NULL,'non_existing',20) [1 rows affected or returned ] As I understand from https://stackoverflow.com/a/16128088/995862, however, In a SQL DBMS, the select-test-insert … -
Template doesn't show first element in list and it's proper length - Django
In my template: {% if author_list.0.card == '0' %} <p>Игра не началась </p> <li> {{ author_list.0.card }}</li> {% else %} {% if voted_list %} <ul> {% for i in user_list %} {% if i not in voted_list %} <li> {{ author_list.0.card }}</li> {% endif %} {% endfor %} </ul> {% else %} <ul> {% for i in user_list %} <li> {{ i }}</li> {% endfor %} </ul> {% endif %} {% endif %} First condition doesn't work, even if it should work. I need to check if my list empty, so when I use author_list|length == 0 with 0 elements it works correctly. After i create 1 element, but it thinks that it is zero. On my second element it shows 2. -
TypeError: __init__() got an unexpected keyword argument 'show_preview'
I am getting this error in Django 1.9 in PostForm content = forms.CharField(widget=PagedownWidget(show_preview=False)) TypeError: __init__() got an unexpected keyword argument 'show_preview' forms.py class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget(show_preview=False)) publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Post fields = [ "title", "content", "image", "draft", "publish", ] The dependencies installed in the virtual environment $ pip freeze certifi==2019.11.28 Django==1.9 django-crispy-forms==1.8.1 django-filter==2.2.0 django-markdown-deux==1.0.5 django-pagedown==2.0.3 djangorestframework==3.11.0 Markdown==3.1.1 markdown2==2.3.1 olefile==0.46 Pillow==6.2.1 -
How to pass multi-parameter to django url and how to reverse it
i am trying to make quiz app, i want make user to select subjects and topic and number of questions(genrate quiz). after input next view should be test/quiz .i am unable to pass the multiple parameter/values to django url. (e.g subject/topic/no_of_question) def generate_quiz(request): if request.method == 'GET': subjects = Subject.objects.all() topics = Topic.objects.all() return render(request, 'mcq/quizetting.html', {'subjects':subjects,'topics':topics}) if request.method == 'POST': subject_id = request.POST.get("subject", "") topic_id = request.POST.get("topic", "") mcq_no = request.POST.get("mcq_no", "") subjects = Subject.objects.all if subject_id != '': if topic_id != '': if mcq_no >= 10 and mcq_no <150: return HttpResponseRedirect(reverse('test', kwargs=['subject':subject_id, ])) else: return render(request, 'mcq/quizetting.html', {'subjects':subjects,'topics':topics}) else : topics = Subject.objects.get(id=subject_id).topic_set.all() else: topics = Topic.objects.all() subject_id = str(subject_id) return render(request, 'mcq/quizetting.html', {'subjects':subjects,'topics':topics, 'current_subject_id':subject_id}) def test(request, subject, topic, mcq_no): s = Subject.objects.get(id=subject) t = Topic.objects.get(id=topic) selected_questions = Question.objects.filter(subject=s, topic=t)[:mcq_no] return render(request, 'mcq/test.html', {'questions':selected_questions}) my view is working upto subject selection,topic filter and question filtration. when i submit form next url is not working. i have tired both {srt and int) variable to pass in url path('generate_quiz',views.generate_quiz, name='generate_quiz'), path('test/<subjects_id>/<topics_id>/<int:mcq_no>',views.test, name='test'), -
Masonry does not work properly for "load more" using Ajax
On my website I have a list of products in a masonry layout. Everything works fine. But when trying to add an infinite list using Ajax my masonry layout is not working properly. The error looks something like the picture below: The first items load correctly. When I get to the end of the page, the new elements overlap the old and the masonry system stops working and all the trenches look like without a masonry. My code in the template looks like this (other files): <div class="row masonry infinite-container"> {% for object in numbers %} <div class="masonry-item col-3 infinite-item"> <!--Content--> </div> {% endfor %} </div> <!-- Load more --> {% if numbers.has_next %} <a href="?page={{ numbers.next_page_number }}" class="btn">Loading...</a> {% endif %} <!-- end pagination --> <!-- Infinite Scroll --> <script src="{% static 'assets/js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'assets/js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'assets/js/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0] }); </script> How can I fix this error? I don't know much about ajax, but it looks like a new request is being loaded without considering my masonry code. Any help will be appreciated. -
How do I tell django to use the PostgreSQL DATE function in Django's .annotate()?
Suppose I have the model EventDateTime, which has a foreign key to a page as well as a date field. i.e. pages can have multiple EventDateTime of different dates and times. The way the site will work, is that it will show users a certain number of events (say 10) within a certain time, with multiple occurences of events on the same day ignored (but not across multiple days). Basically this SQL query: SELECT page_id, DATE(MIN(date)) FROM eventdatetime WHERE (date >= '2020-01-05 17:45:48.545123') GROUP BY page_id, DATE(date) ORDER BY date LIMIT 10; Which could return for example: page_id | date ---------+------------ 296 | 2020-01-07 301 | 2020-01-07 298 | 2020-01-09 289 | 2020-01-10 266 | 2020-01-11 267 | 2020-01-11 268 | 2020-01-11 269 | 2020-01-11 54 | 2020-01-13 290 | 2020-01-13 However, I'm having trouble figuring out how to translate this exact intent into Django's ORM: EventDateTime.objects\ .filter(page__live=True,date__gte=datetime.now())\ .values('page_id')\ .annotate(Min('date__date')).order_by('date') This is the returned SQL: SELECT "web_eventdatetime"."page_id", MIN("web_eventdatetime"."date") AS "date__date__min" FROM "web_eventdatetime" INNER JOIN "web_event" ON ("web_eventdatetime"."page_id" = "web_event"."page_ptr_id") INNER JOIN "wagtailcore_page" ON ("web_event"."page_ptr_id" = "wagtailcore_page"."id") WHERE ("web_eventdatetime"."date" >= 2020-01-05 18:07:57.516323 AND "wagtailcore_page"."live" = True) GROUP BY "web_eventdatetime"."page_id", "web_eventdatetime"."date" <-- does not extract date portion ORDER BY "web_eventdatetime"."date" ASC Notice … -
Registration forms based on attribute - Django
I have extended the user model with AbstractBaseUser with specific attributes to differentiate account types - Job Seeker and Employer. I would like to have 2 separate registration & login forms for users - 1 for job seekers to login/register and 1 for employers to login/register. I am struggling to figure out the best approach to doing this. What's the best approach to setting up two forms and set the is_jobseeker to True when registering for a jobseeker account and is_employer to true when registering for an employer account? I've included my models.py for reference if need. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) # account types is_jobseeker = models.BooleanField(_('Job Seeker'), default=True) is_employer = models.BooleanField(_('Employer'), default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(_('Site Admin'), default=False) # account activity is_active = models.BooleanField(_('Active'), default=True) # personal fields first_name = models.CharField(max_length=30, blank=True, default='') last_name = models.CharField(max_length=30, blank=True, default='') # contact fields phone = models.CharField(max_length=11, blank=True, default='') # location fields address = models.CharField(max_length=100, blank=True, default='') city = models.CharField(max_length=100, blank=True, default='') state = models.CharField(max_length=2, blank=True, default='') # other fields date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email Thanks in advance for any help! -
m2m_changed does not fire when changing one side of a m2m relationship
Sorry i am new to django , pardon me if this is a silly mistake. I am currently trying to build a notifications system using django signals , however i have encountered the issue of needing to query a m2m relationship. To further illustrate the issue ,here is my code. This is my Notifications Model. class Notifications(models.Model): notifications_id = models.AutoField(primary_key=True) user = models.ForeignKey(User,on_delete=models.CASCADE,default=1) time = models.DateTimeField(auto_now=True) message = models.TextField(max_length=100 ,default ='test') object_url = models.CharField(max_length=500, default ='test') is_read = models.BooleanField(default=False) This is my task model: class SalesTask(models.Model): sales_status= ( ('p1','Phase 1'), ('p2','Phase 2'), ('p3','Phase 3'), ('p4','Phase 4'), ) sales_priority= ( ('Urgent','Urgent'), ('Medium','Medium'), ('Low','Low'), ) task_id = models.AutoField(primary_key=True) salesExtra= models.ManyToManyField('SalesExtra') sales_project= models.ForeignKey('SalesProject',on_delete=models.CASCADE) title = models.TextField(max_length=50 , default='Your Title' ) description = models.TextField(max_length=200 , default='Your Description' ) priority = models.TextField(max_length=10 , choices= sales_priority ,default='Low' ) date_time = models.DateTimeField(auto_now=True) status = models.TextField(max_length=10, choices= sales_status ,default='p1') due_date = models.DateTimeField(default=timezone.now) This is my signal handler: def CreateTaskNotification(sender,**kwargs): print(kwargs['instance'].all()) for i in range(len(kwargs['instance'].all())): notification = Notifications.objects.create(user = kwargs['instance'].salesExtra.username[i], message = 'You have been assigned a new task', object_url = kwargs['instance'].get_absolute_url(self) ) m2m_changed.connect(CreateTaskNotification,sender=SalesTask) I have checked and my signal indeed does not fire when i create a new SalesExtra model instance. -
Passing button name to name to function - Django
I'm newbie in Django, pyhon. I'm want to pass name of clicked button to function in views and then use it as a filter. This is html: <tr> <td><a class="btn btn-primary" href="{% url 'display_ph' %}" role="button" method="post">{{ item.nazwa }}</a></td> <td>{{ item.ulica }}</td> <td>{{ item.miejscowosc }}</td> <td>{{ item.kod_pocztowy }}</td> </tbody> And I want to take "nazwa" and pass it to function: def display_ph(request, nazwa): filter = request.GET.get('nazwa', False) items = Phandlowy.objects.filter(firma=filter) context = { 'items': items, } return render(request, 'ph.html', context) I don't now it this is possible with this button. -
Django Form does not see arguments
I have removed some useless branch from my git and now one function on my website does not work. It is about add_recipe http://lui93.pythonanywhere.com/accounts/add_recipe/ does not work. When I am trying to add it and every field is filled, i push the button "add recipe" it shows that ingrediend field is required. View: def add_recipe(request): add_recipe = RecipeForm(request.POST) print(add_recipe['ingredients'].value()) if add_recipe.is_valid(): add_recipe.save() return redirect('success_added_recipe') return render(request, 'drinks/add_recipe.html', {'RecipeForm': add_recipe}) Form: class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['recipe_name', 'preparation', 'ingredients', 'recipe_image'] debug.log (0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() (0.001) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient" WHERE "drinks_ingredient"."id" IN (12); args=(12,) (0.000) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient"; args=() "POST /accounts/add_recipe/ HTTP/1.1" 200 1637 (0.002) -
Django does not recognize specific change in model
class Category(models.Model): name = models.CharField(max_length=128 , unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) # we override save so as to convert name to a slug ### essentially -> name.lower().replace(" " , "-") def save(self,*args,**kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def __str__(self): return self.name class Meta: verbose_name_plural = "Categories" The save override is not registering. I get a "No changes detected in app" message when trying to run makemigrations. I have tried making changes in the other methods, and the changes are recognized. What could be causing this? -
django rest_frameworks not getting data
I am trying to get dates from my model database. When I request for getting all objects, it only shows {}. I want to get and post a date using django-restapi Here is my code: My serializer: from rest_framework import serializers from .models import prediction_model class predserializer(serializers.Serializer): class Meta: model = prediction_model field = '__all__' my model: from django.db import models # Create your models here. class prediction_model(models.Model): date = models.DateField() def meta(self): return self.date my views.py : from django.shortcuts import render from rest_framework import status from rest_framework.response import Response from .models import prediction_model from .serializers import predserializer # Create your views here. from rest_framework.decorators import api_view def index(request): return render(request, 'homesite/index.html') @api_view(['GET', 'POST']) def get_date(request): if request.method == 'GET': prediction = prediction_model.objects.all() serializer = predserializer(prediction) return Response(serializer.data) def post_date(request): if request.method == 'POST': serializer = predserializer(data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED)