Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding multiple bokeh html files to a django template
I created some plots with bokeh and exported them as html files. I now try to add these plots in a django template. The first plot works just fine, but if I want to add a second one it is not displayed. Here i have the python file that creates the bokeh html: from bokeh.plotting import figure, output_file, show output_file("test2.html",title="test2") p = figure(plot_width=400, plot_height=400) p.circle([1, 5, 7, 2, 5], [6, 7, 2, 5, 5], size=20, color="navy", alpha=0.5) show(p) This is the second plot, the first one is saved as test.html, the title is test and some of the point coordinates are different. And here is my django template: {% extends "MainPage/PageBase.html" %} {% block content %} <div class="container"> <div class="card"> <div class="card-header"> <font size="3">plot1</font> </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p><div class="basic"> {% include "GPanalysis\WorkingData\test.html" %} </div></p> </blockquote> </div> </div> <div class="card"> <div class="card-header"> <font size="3">plot2</font> </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p><div class="basic"> {% include "GPanalysis\WorkingData\test2.html" %} </div></p> </blockquote> </div> </div> </div> {% endblock %} In the first box appears a graph but the second one is empty. I switched the position of two plots, but only the one that comes first in the html script will be displayed. … -
Error: "there is no unique constraint matching given keys for referenced table" although primary key is included
I am trying to make a comments app for a Django project whereby each record can have a number of comments attached to it. However, when I try to migrate my model, I get the following error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "user_info" What am I doing wrong? Currently my models look like this: users/models.py class UserInfo(models.Model): id = models.CharField(max_length=25, blank=False, null=False, primary_key=True) dob = models.DateField(blank=True, null=True) age = models.IntegerField(blank=True, null=True) #Includes a number of other fields def __str__(self): return self.id class Meta: managed = False db_table = 'user_info' ordering = ['id'] comments/models.py from users.models import UserInfo class Comments(models.Model): patient_record = models.ForeignKey(UserInfo, on_delete=models.CASCADE, null=True, blank=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) -
Parsing JSON With Requests library In Django
I'm trying to fetch json data from a website and update my sqlite database in Django to show on the localhost. I am really stuck here. Please help me and could you please suggest me any website to take help? Thank you I am not able to parse the json correctly. I am using requests library to parse. I am getting the whole json on my local host but not able to parse individual items. this is my header of json on my local host. [{'id': 1, 'video_url':'https://storage.googleapis.com/makelocal/upload/nurs.......use',{'id': 2, 'video_url': 'https://storage.googleapis.com/......duction (short_version ver 2)'}] my views.py file from django.shortcuts import render def home(request): import requests import json api_request = requests.get('https://us-c..../content_all/json') try: api = json.loads(api_request.content) except Exception as e: api = "Error" return render(request, 'home.html', {'api':api}) this is my home.html file {% extends 'base.html' %} {% block content %} {{ api }} {% endblock %} when I am trying only api in home.html it is showing the whole json but when I am trying this<br/> {{ api.company_name }} #company_name is key in my json A blank page is coming. Could you please help me. -
Django data from database don't show in site
Problem with show data in site in django from model I try send the data from database, but nothing happend. Data don't show in site and console. views.py from django.shortcuts import render, render_to_response from .models import People def Peoples(request): data = People.objects.all() peo = { "peo_login": data } print(peo) return render_to_response("templates/login.html", peo) models.py class People(models.Model): peo_login = models.CharField(db_column='PEO_LOGIN', primary_key=True, max_length=50) peo_name = models.CharField(db_column='PEO_IMIE', max_length=255, blank=True, null=True) login.html {% for Peopl in peo %} <p>{{ Peoples.peo_login }}</p> {% endfor %} urls.py urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^login/$',auth_views.LoginView.as_view(template_name='login.html'), name='login'), I am newbie in Python, please help -
Can't add attribute to ModelForm field at __init__
I have the following model which returns the values in a ManyToMany field (approvers) as choices in an Integerfield (step): from django.utils.functional import lazy class Task(models.Model): step = models.IntegerField(null=True) approvers = models.ManyToManyField( get_user_model(), ) @property def get_step_choices(self): CHOICES = [] if self.approvers: CHOICES = [(a.id, a.email) for a in self.approvers.all()] return CHOICES def __init__(self, *args, **kwargs): super(Task, self).__init__(*args, **kwargs) self._meta.get_field('status')._choices = lazy( self.get_step_choices, list )() However, the syntax I have used under init does not appear to render the choices attr to step. Where am I going wrong? -
how can I serve my django app using http/2
I have a Django application that is deployed on AWS elastic beanstalk, when I ran the audits in my browser it recommends the use of http/2 over http/1 how to accomplish this. I know that usually you configure it using apache but here I am not using apache instead I have elastic beanstalk which has a load balancer and the Django app. how can I serve my app using http/2 ?? -
How to create a single field multiple image upload with two models?
I have a model called Product that needs multiple image upload capabilities. I have thus created a separate model called Images to link back to Product with a ForeignKey relationship. I need some help to write a function that can loop over each uploaded image and create the foreign key relationship back to Product. What follows is a simplified model: class Product(models.Model): title = models.Charfield() description = models.TextField() ... ...and the Images model: class Images(model.Model): image = models.ImageField() product = models.ForeignKey(Product) Simple forms for them both (Images omitted but it's the same idea: class ProductCreateForm(ModelForm): class Meta: model = Product fields = '__all__' Also, the template includes enctype="multipart/form-data" to allow multiple upload selection. I would like to know create a view function to loop over the uploads and create the ForeignKey relationship. Something like this: def CreateProduct(request): if request.method = 'POST' ... (now this is where I just have no idea how to write this. I'm very new to Django and programming/scripting in general.) -
How to track steps in a linear workflow
I have a model for a Task in a workflow. The task has a ManyToMany field that allows users to add approvers who can approve each step in the task. class Task(models.Model): approvers = models.ManyToManyField( get_user_model(), through='TaskStep' ) I am using an OrderedModel as an intermediary model to keep track of the order of each approval, with the intention to pass the Task linearly from one approver to the next as they sign off the Task: class TaskStep(OrderedModel): approver = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL ) task = models.ForeignKey(FlowTask, null=True, on_delete=models.SET_NULL) order_with_respect_to = 'task' status = models.BooleanField() What's the simplest way to keep track of which TaskStep the Task approval is on? -
Got AttributeError when attempting to get a value for field when using values_list
I have encountered the error which I cannot solve after I read the django doc and django-rest-framework doc,even I read all the related question on stackoverflow,I still cannot solve it. the full error message is as following: AttributeError at /api/v1/task/target/subdomain/get_by_target/ Got AttributeError when attempting to get a value for field `target_id` on serializer `TargetSubdomainSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `tuple` instance. Original exception text was: 'tuple' object has no attribute 'target_id'. I want to get the distinct result on my table, so I use django filter and distinct, when I just use the filter, the code runs correctly, but when I use filter and values_list at the same time, it runs into error. the TargetSubdomain model is as following: class TargetSubdomain(models.Model): target_id = models.IntegerField(help_text='目标ID') domain = models.CharField(max_length=200, help_text='域名') source = models.CharField(max_length=20, help_text='子域名来源') created_at = models.BigIntegerField(default=0, help_text='创建时间') updated_at = models.BigIntegerField(default=0, help_text='更新时间') def save(self, **kwargs): if not self.id: self.created_at = int(time.time()) self.updated_at = int(time.time()) super(TargetSubdomain, self).save() class Meta: db_table = 'nw_target_subdomain' the TargetSubdomainSerializer is as following: class TargetSubdomainSerializer(serializers.ModelSerializer): class Meta: model = TargetSubdomain fields = '__all__' the TargetSubdomainViewSet is as following: class TargetSubdomainViewSet(viewsets.ModelViewSet): queryset = TargetSubdomain.objects.all().order_by('-id') serializer_class = TargetSubdomainSerializer @action(methods=['GET'], detail=False, … -
Django annotate a queryset with objects
I have models named Product, Material, and Tag. Each product has many materials, each material has many tags. Each product has tags, the tags are all distinct tags of the product's materials. I would like to pass Product queryset with tags attribute to django rest serializer without N+1 problem. I used subquery, but it only return a row and a column. I tried to operate it at python level, but it produces N+1 problem, and even if I somehow manage to avoid N+1 problem it will be slower than using ORM because it's python. I tried to add tags column to Product, and update it everytime the material and/or material's tags changed, it works, but adding more complexities to my code for something that could be so simple class Product(models.Model): name = models.CharField(max_length=255) class Material(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, related_name='materials', on_delete=models.CASCADE) class Tag(models.Model): name = models.CharField(max_length=255) material = models.ForeignKey(Material, related_name='tags', on_delete=models.CASCADE) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class ProductSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: model = Product fields = '__all__' I expect to have queryset that can be passed to ProductSerializer without N+1 problem and without using signals. -
How to automatically update view once the database is updated in django?
I have a problem in which I have to show data entered into a database without having to press any button or doing anything. I am creating an app for a hospital, it has two views, one for a doctor and one for a patient. I want as soon as the patient enters his symptoms, it shows up on doctor immediately without having to press any button. I have no idea how to do this. Any help would be appreciated. Thanks in advance -
Django - Model property methods vs signals for field calculation
I have a model that does some basic aggregation of some values on a m2m field. I can achieve this by doing the calculation in a Model method, in which case the results would be stored in a model attribute. Or I can do the calculation in a pre_save signal function, and then the result would be stored in a model field. I want to know are there are any cons to using signals? or in which cases it would be better to use a model property method? I understand that the calculations will run at different times, with the signal function running when save() is called, and the model method running automatically. class CartItem(models.Model): name = models.CharField(max_length=100) total_price = models.DecimalField(max_digits=10, decimal_places=2) ##Model Method Approach @property def price(self): return self.extras.all().aggregate(Sum('price'))['price__sum'] ##Signal Approach def set_total_price(sender, instance, **kwargs): instance.total_price= instance.extras.all().aggregate(Sum('price'))['price__sum'] pre_save.connect(set_total_price, sender=CartItem) The signal approach has the benefit of resulting in a model field rather than a model attribute, which makes it easier use in Parent or related models for aggregation. So why would one ever use a Model method over a model signal? -
How to display data from mysql 8 in django 2.1.5?
I am trying to display some data from mysql 8 in Django 2.1. I created a database db1 and inserted some data into it and tested. All works perfectly. Then I add this piece of code into views.py: @login_required def population_list(request): names = Population.objects.all() return render_to_response('images/image/list.html', {'names': names}) inside models.py I have: class Population(models.Model): name = models.CharField(max_length=20) population = models.BigIntegerField() year = models.DateField() inside list.html I add this code: <div id="population-list"> <h3>Names here... </h3> <tbody> <tr> {% for name in names %} <td>{{ name.name }}</td> {% endfor %} </tr> </tbody> However I only see: "Names here..." text, nothing else. What is my mistake? Why I don't see the database content? How can I debug it? -
Slow server response times from Django app on Heroku
Ive grown quite stuck trying to figure out why my production Django application (E-commerce) has trouble with slow server response times on certain pages. The pages affected has quite some database requests on it because of complicated relationships between Cars and Products i.e some chargers only work with some cars and some chargers span multiple categories etc etc. The application is hosted on Heroku with a “Hobby Basic Postgres database” and "1 Professional Standard-1X dyno”. For some reason the server takes between 7-10 seconds to respond to a request on the live server. Locally everything works super smooth and fast with responses of maximum 0.5s on all pages. Has anyone had this trouble before and has any idea of how to fix it? Ive tried scaling the database and dynos without the response being any quicker.. I’ll attach som screenshots of logs and speed tests. And affected code Models, Views and Template. Heroku Metrics: https://screenshot.net/z7r4jid Heroku Logs: https://screenshot.net/ndv7ot8 Console Debugger: https://screenshot.net/m4310t3 Template: https://dpaste.de/tjEi View: https://dpaste.de/Bdut Models: https://dpaste.de/fNQY The page is: https://www.evify.se The pages with slow server response is all the car detail pages. Example: https://www.evify.se/laddboxar/jaguar-i-pace/ Would be extremely grateful if anyone has any idea, I’ve looked everywhere without finding any … -
How to convert duration into '%H:%M:%S.%f' time format, not in days
I need to convert days to hours, minutes, seconds def get_working_hours(self, obj): return datetime.strptime(str(obj.working_hours), '%H:%M:%S.%f').time() ValueError: time data '1 day, 7:06:38.340741' does not match format '%H:%M:%S.%f' -
How to set a dynamic choices tuple based on other model field values
I have a model with 2 fields: A ManyToMany field that contains a number of users who can approve a task (approvers); and An IntegerField that contains a choices tuple to return the current step of the task (step). class Task(models.Model): approvers = models.ManyToManyField( get_user_model(), through='TaskStep' ) step = IntegerField( choices=STEP_CHOICES ) I want to allow users to define the number of approvers, but also dynamically create a choice for each approver in step. How can I programmatically define the choices in my tuple to cover the number of users in the ManyToMany field? For example, if there are 3 approvers, the result would be: STATUS_CHOICES = ( (1, 'Step 1'), (2, 'Step 2'), (3, 'Step 3'), ) If there were 5 users, the result would be: STATUS_CHOICES = ( (1, 'Step 1'), (2, 'Step 2'), (3, 'Step 3'), (4, 'Step 4'), (5, 'Step 5'), ) -
Getting InvalidRequestError in stripe
I get following error: File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\stripe\api_requestor.py", line 151, in handle_error_response raise err stripe.error.InvalidRequestError: Request req_jQhnYD0I72zs8l: No such customer: cus_Fi7AiNV2Cpdkdi My code: def payment_method_create_view(request): print("Ajax payment") if request.method == "POST" and request.is_ajax(): billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) if not billing_profile: return HttpResponse({"message": "Cannot find this user "}, status=401) token = request.POST.get("token") print("token is:", token) if token is not None: new_card_obj = Card.objects.add_new(billing_profile, token) print(new_card_obj) return JsonResponse({"message": "Your card was added."}) return HttpResponse("error", status=401) class CardManager(models.Manager): def all(self, *args, **kwargs): return self.get_queryset().filter(active=True) def add_new(self, billing_profile, token): if token: customer = stripe.Customer.retrieve(billing_profile.customer_id) stripe_card_response = customer.sources.create(source=token) new_card = self.model( billing_profile = billing_profile, stripe_id = stripe_card_response.id, brand = stripe_card_response.brand, country = stripe_card_response.country, exp_month = stripe_card_response.exp_month, exp_year = stripe_card_response.exp_year, last4 = stripe_card_response.last4 ) new_card.save() return new_card return None class Card(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) stripe_id = models.CharField(max_length=120) brand = models.CharField(max_length=120, null=True, blank=True) country = models.CharField(max_length=20, null=True, blank=True) exp_month = models.IntegerField(null=True, blank=True) exp_year = models.IntegerField(null=True, blank=True) last4 = models.CharField(max_length=4, null=True, blank=True) default = models.BooleanField(default=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CardManager() -
Calculating two integers fields in django
I want to calculate these fields and want output for example (budget - Expense) (budget + Expense) (budget * Expense). how could i do that. Class calculate(models.Model): budget = models.IntegerField(default=0) Expense = models.IntegerField(default=0) -
Circular import error while importing urls file of another app in main app urls
I have created an app in djano with name user, and inside that user app , there is a file called urls.py, it contains various api_end points. Now I want to import this urls.py of app.py inside the urls.py file created by django project. I am getting circular import error. this is urls.py file created by django-admin urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/v1/', include('user.urls')), ] and this is urls.py file created inside user app urlpatterns = [ url(r'^login/?$', token_handling.CustomTokenObtainPairView.as_view(), name='login'), ] -
Setup docker volume for django logger
I have a Django 2.2 application and want to serve the application using Docker. I have the Django logger setup as FILE_LOCATIONS = { 'debug': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'debug.log'), 'error': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'error.log'), 'info': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'info.log') } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime}: ~{pathname} (line: {lineno}):: {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': FILE_LOCATIONS['debug'], 'formatter': 'verbose', 'when': 'midnight', 'interval': 1, 'backupCount': 0, }, 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'app': { # Common logger, log app 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'plan_change': { # Log plan change process 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, } } and docker-compose.yml file as version: '3' services: nginx: image: nginx:alpine container_name: "myapp-staging-nginx" ports: - "8000:80" volumes: - .:/app - ./configs/docker/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: "myapp-staging-dev" command: ["./scripts/docker/wait_for_it.sh", "db:5433", "--", "./scripts/docker/docker_start.sh"] volumes: - .:/app depends_on: - db # For database - redis # For celery broker db: image: mysql:8.0 container_name: "myapp-staging-mysql-db" env_file: - configs/docker/env/mysql_env.env ports: - "5433:5432" volumes: - myapp_staging_db_volume:/var/lib/mysql/data redis: image: "redis:alpine" celery: build: . command: celery -A qcg … -
Angular router guard with Django
I am using django authentication, I want to use angular router guards when not signed in. So that it reroutes to login page if not logged in. I have tried to setup as angular usually would with router guards, but this routes to the url without a trailing slash which doesn't work with Django. I have fixed it so it keeps the trailing slash, but this doesn't route to the Django page, it seems its looking for a Angular page. But if it type in the url for the Django login page that still works. Auth Guard: checkLogin(url: string): boolean { if (this.authService.isLoggedIn) { return true; } this.authService.redirectUrl = url; this.router.navigate(['/accounts/login/.']); return false; } app-routing module: { path:"", component: ProjectHomeComponent, canActivate : [AuthGuard], children: [ { path: '', children: [ { path: 'view', component: ProjectViewComponent }, { path: 'seeManage', component: ProjectManageComponent }, { path: '**', component: PagenotfoundComponent } ] } ] } Expect to be routed to django login page, not routed to django login page -
I want save data in sqlite Database, My Query not working in webpage But same code wroking fine in Django Shell
I am trying to add some data via Views.py but it not working but the same code working in django shell. My Code : username = request.POST['username'] bp = request.POST['bp'] bs = request.POST['bs'] height = request.POST['height'] weight = request.POST['weight'] temp = request.POST['temp'] datasaved = PatTest(Patient= Patient.objects.get(username=str(username)), BS=int(bs), BP=int(bp), PatHeight=float(height), PatientWeight=float(weight), BMI=BMICal(height, weight), TEMPA=int(temp)) print("Test") datasaved.save() -
Django - How to dynamically create signals
I'm working on a model Mixin which needs to dynamically set signals based on one attribute. It's more complicated but for simplicity, let's say the Mixin has this attribute: models = ['app.model1','app.model2'] This attribute is defined in model which extends this mixin. How do I can register signals dynamically? I tried to create a classmethod: @classmethod def set_signals(cls): def status_sig(sender, instance, created, *args, **kwargs): print('SIGNAL') ... do som things for m in cls.get_target_models(): post_save.connect(status_sig,m) My idea was to call this method somewhere in class automatically (for example __call__ method) but for now, I just tried to call it and then save the model to see if it works but it didn't. from django.db.models.signals import post_save print(post_save.receivers) Realestate.set_signals() print(post_save.receivers) r = Realestate.objects.first() r.status = 1 r.save() output [] [((139967044372680, 46800232), <weakref at 0x7f4c9d702408; dead>), ((139967044372680, 46793464), <weakref at 0x7f4c9d702408; dead>)] So you see that it registered those models but no signal has been triggered after saving the realestate. Do you know how to make it work? Even better without having to call method explicitely? EDIT: I can't just put the signals creation inside mixin file because models depends on the string in child model. -
Can't Add/Accept and Decline/Cancel Friend requests on Django
Able to Send Friend requests successfully but responding to the requests are an issue. When you press Accept to Add, the button is removed but the Friend isn't added or when you press Cancel to Decline, nothing happens. Tried adding a forms class Add_Friend(forms.ModelForm): model = UserProfile def add_friend(request, user_profile): request.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() request.friends.add(user_profile) user_profile.friends.add(self) request.friend_requests.remove(user_profile) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(blank=True, max_length=128) friends = models.ManyToManyField('self', blank=True, related_name='friends') friend_requests = models.ManyToManyField('self', blank=True, related_name='friend_requests') def send_friend_request(self, user_profile): self.friend_requests.add(user_profile) noti = Notification.objects.create(owner=self, type=Notification.FRIEND_REQUEST, sender=user_profile.user.username) self.notification_set.add(noti) return self.friend_requests.count() def add_friend(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() self.friends.add(user_profile) user_profile.friends.add(self) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() def cancel_friend_request(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() noti = Notification.objects.create(owner=user_profile, type=Notification.DECLINED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friend_requests.count() def __str__(self): return self.get_first_name() #Takes you to the userprofile page def get_absolute_url(self): return "/users/{}".format(self.id) @method_decorator(login_required, name='dispatch') class SendFriendRequestView(View): def get(self, request, *args, **kwargs): profile_id = request.GET.get('profile_id') requester_id = request.GET.get('requester_id') target = UserProfile.objects.get(id=profile_id) requester = UserProfile.objects.get(id=requester_id) target.send_friend_request(requester) message = 'Friend request to {} sent!'.format(target.visible_name) messages.info(request, message) return redirect('profile', username=target.user.username) @method_decorator(login_required, name='dispatch') class CancelFriendRequestView(View): def cancel_friend_request(request, id): if request.user.is_authenticated(): user = get_object_or_404(User, id=id) frequest, created = FriendRequest.objects.filter( from_user=request.user, to_user=user).first() frequest.delete() return HttpResponseRedirect('/users') @method_decorator(login_required, name='dispatch') class AddFriendView(View): def … -
Django Forms Not Rendering In HTML
I am finding it difficult to show django forms in html template. The django form fails to render in the template. I am using class base view and below are my codes for views.py,urls.py, models.py and the html template: views.py class Home(CreateView): models = Blog queryset = Blog.objects.filter(publish = True) template_name='index.html' fields = '__all__' urls.py ... urlpatterns=[ path('', Home.as_view(), name='index'), ] models.py ... Continent = ( ('select continent', 'Select Continent'), ('africa', 'Africa'), ('europe', 'Europe'), ('north america', 'North America'), ('south america', 'South America'), ('asia', 'Asia'), ('australia', 'Australia'), ('Antarctica', 'Antarctica'), ) class Blog(models.Model): name= models.CharField(max_length = 200) company= models.CharField(max_length = 200) post = models.CharField(max_length = 200) author= models.ForeignKey('auth.User', on_delete = models.PROTECT) mantra= models.CharField(max_length = 200, help_text='make it short and precise') continent = models.CharField(choices= Continent, default= 'select continent', help_text='help us to know you even more', max_length=50) publish = models.BooleanField(default =True) def __str__(self): return self.name def get_absolute_url(self): # new return reverse('post_detail') index.html {% extends "base.html" %} {% load static %} {% block content %} <body class="loading"> <div id="wrapper"> <div id="bg"></div> <div id="overlay"></div> <div id="main"> {{form.as_p}} {% include "partials/_footer.html" %} </div> </div> </body> {% endblock %} Any assistance will be greatly appreciated. Thanks.