Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImproperlyConfigured Error for Django application
I keep getting an Improperly Configured Error when I try to run my server Error message: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I created a new django project, I have django installed in my virtual environment, I did not forget to activate the virtual environment, And I triple checked my python path, Here is the full traceback: (venv3) C:\Users\user\Desktop\trialproject>django-admin.py runserver Traceback (most recent call last): File "C:\Users\user\Desktop\trialproject\venv3\Scripts\django-admin.py", line 5, in <module> management.execute_from_command_line() File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "c:\users\user\desktop\trialproject\venv3\lib\site-packages\django\conf\__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Someone please help me figure out the problem. Thanks -
Is calling python script for many kinds of operations from rails, on heroku, a good idea?
What are the pros and cons of using Rails but using python scripts for all kinds of operations, including ML (hosting on heroku)? I like Rails, but if Django would be better long-term, I'm willing to switch to that. I'm hoping that by framing this question as "pros and cons," this fits more into stack overflow norm... if not, I'm sorry. I'd really appreciate help though. -
Python graphql to integrate with azure functions
Could anyone tell me how to integrate python graphql with azure functions? -
Am I required to use django data migrations?
I migrated a database that was manipulated via SQL to use Django's migration module: https://docs.djangoproject.com/en/3.0/topics/migrations/. Initially I thought of using migrations only for changes in the model such as changes in columns or new tables, performing deletes, inserts and updates through SQL, as they are constant and writing a migration for each case would be a little impractical. Could using the migration module without using data migrations cause me some kind of problem or inconsistency in the future? -
dynamiclly change pages with slug and include tag in template
I was trying to build a template preview in my website, which is when user click the specific template preview on the templates list page, it will direct to the template detail page,the urls.py code is like below: urls.py: urlpatterns = [path('choose_templates/<slug:slug>/', views.template_preview, name='template_preview'),] views.py: def template_preview(request,slug): context = { 'slug':slug } return render(request,'./html/htmlbase.html',context) htmlbase.html: <!DOCTYPE html> <html> <head></head> <body> {% include slug %} </body> </html> what I want to do is when user click on different template preview button, it will direct to the correspond template detail page. the code above result in " TemplateDoesNotExist". Could anyone helo me with this? Thank you! -
why is django returning form.is_valid == false?
Everytime I use this form I get form.is_valid() == False . When I do print(form.errors) I get : <ul class="errorlist"><li>reservation_code<ul class="errorlist"><li>Client with this Reservation code already exists.</li></ul></li></ul> But the whole point of the form is to get the details of the reservation, by entering an already existing reservation code. So how can I change this so the form returns valid? Here is the view: def reservationView(request): if request.method == "GET": return render(request,'aplikacija/reservations.html') else: form = ReservationForm(request.POST) if form.is_valid(): code = form.cleaned_data['reservation_code'] try: client = Client.objects.filter(reservation_code=code) tour = client.tour.destination client.delete() return render(request,'aplikacija/reservations.html',{'infoMsg':f'You have successfully cancelled your trip to {tour}'}) except: form = ReservationForm() return render(request,'aplikacija/cancelReservation.html',{'form':form,'infoMsg':'INVALID RESERVATION CODE'}) else: form = ReservationForm() print(form.errors) return render(request,'aplikacija/cancelReservation.html',{'form':form,'infoMsg':'FORM INVALID'}) This is the model : class Client(models.Model): name = models.CharField(max_length=256) surname = models.CharField(max_length=256) email = models.CharField(max_length=256) number_of_guests =models.IntegerField() tour = models.ForeignKey(Tour,on_delete=models.CASCADE) total_price = models.DecimalField(decimal_places=2,max_digits=15,default=0) reservation_code = models.CharField(max_length=50,unique=True) This is the form class : class ReservationForm(forms.ModelForm): class Meta: model = Client fields = ('reservation_code',) widgets = { 'reservation_code':forms.TextInput(attrs={'class':'clientFormField'}) } And here is the template : {% extends 'aplikacija/base.html' %} {% block content %} <h2 id="mostPopularTitle">Please enter your reservation code</h2> <form method="POST" action="{% url 'reservation_details' %}" class="contactFormTab clientForm"> {{infoMsg}} {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn">Get … -
Dynamic URL routing not working in Django
Here is my urls.py of app 'api' of project 'REST Api': from django.conf.urls import url from . import views app_name = 'api' urlpatterns = [ url(r'^view/<int:test_id>/$' , views.add_task_to_list, name= "add_task"), url(r'^$', views.index, name= "index") ] and here is my views.py of app 'api': # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from .forms import task_form, list_form from .models import List, Task # Create your views here. def index(request): l_form = list_form(request.POST or None) if l_form.is_valid(): l_form.save() return HttpResponseRedirect('/') # tasks = Tasks() lists = List.objects.all() context = { 'l_form': l_form, 'lists': lists } return render(request, 'api/main.html', context) def add_task_to_list(request, test_id): task = Task() task.list = List.objects.get(pk=test_id) form = task_form(request.POST or None, instance= task) if form.is_valid: form.save() context = { 'task':task, 'form':form } return render(request, "api/create_task.html", context) And here is my models.py of app 'api': # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class List(models.Model): date = models.DateField() author = models.CharField( max_length=100, blank= True ) def __str__(self): return self.author class Task(models.Model): task_name = models.CharField( max_length=150, ) complete_status = models.BooleanField( default= False, blank= True ) priority = models.IntegerField() list = models.ForeignKey(List, on_delete=models.CASCADE) def __str__(self): return self.task_name But … -
Explain how `<<: *name` makes a reference to `&name` in docker-compose?
Trying to understand how the docker-compose file was created as I want to replicate this into a kubernetes deployment yaml file. In reference to a cookiecutter-django's docker-compose production.yaml file: ... services: django: &django ... By docker-compose design, the name of service here is already defined as django but then I noticed this extra bit &django. This made me wonder why its here. Further down, I noticed the following: ... celeryworker: <<: *django ... I don't understand how that works. The docker-compose docs have no reference or mention for using << let alone, making a reference to a named service like *django. Can anyone explain how the above work and how do I replicate it to a kubernetes deployment or services yaml file (or both?) if possible? -
Correct usage of Django's user_permissions and get_user_permissions()?
I'm trying to understand where/how I would Django's user_permissions table and get_user_permissions() method. The only documentation I could find for it is here. For example, in my app, when I assign a user u to a group g >>> u.get_group_permissions() <QuerySet [Permission...>] # the full set of permissions that the group has >>> u.get_user_permissions() set() # an empty set First, I'd assume that get_group_permissions() and get_user_permissions() would be not only both return a QuerySet but have the same permissions. Similarly >>> u.has_perm('app.view_model') # user has permission True >>> u.get_user_permissions() # should permission be in here? set() >>> u.user_permissions.all() # what about here? <QuerySet []> Second, there also doesn't seem to be any built-in methods for adding/revoking/checking for specific user permissions other than doing operations on the user_permissions itself. I guess I'm looking for clarification because I'm confused on what exactly these fields are for. -
Django AJAX finds csrf_token cookie but still returns 403 (Forbidden) error
I'm trying to make an AJAX post request but doing so returns the error 403 (Forbidden) in the browser console and Forbidden (CSRF token missing or incorrect.) in my view. I have followed the official Django documentation regarding AJAX Post requests here to the best of my ability but still run into this error. The strangest part about all of this is that AJAX Posting worked fine before I had re-ordered by my HTML scripts. In fact, I didn't have to manually specify a csrf_token in my JavaScript, all I did was include the js-cookie script via CDN and it worked. So, the root of the problem may lie in the order of my scripts, but I really can't say for sure. Here is everything else I tried: Confirmed that CSRF_USE_SESSIONS and/or CSRF_COOKIE_HTTPONLY is set to False (they are False by default and I never had a need to touch them) Used the JavaScript Cookie library CDN in my HTML Logged the csrf_token in the developer console (can confirm the token is at least being extracted from the cookie) Added the function annotation @ensure_csrf_cookie to my view, without the parameter quotes. Including them with quotes like @ensure_csrf_cookie("MyViewName") returns the error … -
Get pk from URL in django rest framework
I am trying to access the pk from URL but getting the following error: get() got multiple values for argument 'pk' URL: path('grn-barcodes/<int:pk>/', GrnBarcodes.as_view()), Views.py class GrnBarcodes(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self,pk): pk = self.kwargs['pk'] print("pk is", pk) . . . return Response("done") How do I get it in the Function? -
displaying HTMLFIELD content on tinyMCE editor on Django
My problem is that I'm trying to load a previous post content into the tinyMCE editor so that they can edit their previous post. Here's what I have so far: models.py: class Post(models.Model): event = models.OneToOneField(Event,on_delete=models.CASCADE) content = tinymce_models.HTMLField() views.py: def add_post(request,event_id): event = Event.objects.get(pk=event_id) try: existingPost = Post.objects.get(event=event) previousContent = existingPost.content except Post.DoesNotExist: previousContent = "" print(previousContent) form = PostAddForm(title=event.title,previousContent=previousContent) if request.method == 'POST': form = PostAddForm(request.POST,title=event.title,previousContent=previousContent) if form.is_valid(): title = form.cleaned_data.get('title') content = form.cleaned_data.get('content') event.title = title event.save() try: post = Post.objects.get(event=event) except Post.DoesNotExist: post = Post(event=event,content="") post.content = content post.save() messages.success(request,"Post added successfully") else: print("error") messages.error(request,"Post addition unsuccessful") context = { 'form': form, 'event': event, 'previousContent': previousContent } return render(request,'posts/add-post.html',context) forms.py class PostAddForm(forms.Form): title = forms.CharField() content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}, )) def clean(self, *args, **kwargs): title = self.cleaned_data.get('title') content = self.cleaned_data.get('content') def __init__(self,*args,**kwargs): self.title = kwargs.pop('title',None) self.previousContent = kwargs.pop('previousContent',None) super(PostAddForm,self).__init__(*args,**kwargs) self.fields['title'].widget.attrs['value'] = self.title self.fields['content'].widget.attrs['value'] = self.previousContent add-post.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block header %} Add Post {% endblock %} {% block content %} <head>{{ form.media }}</head> <form class="mt-5" id="postForm" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> {{form.title|as_crispy_field }} </div> <div class="form-group"> {{form.content}} </div> <button type="submit" … -
Can't pre-populate Django database
So I've been following this guide from Django 1.1 but I'm actually using Django 2 for how to pre-populate Django database I'm using SQLite database and this is my code with Faker library but it just won't run when I want to run it in the CMD. import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() ## FAKE POPULATION SCRIPT: import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker # Creating a fake generator: fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N = 5): for entry in range(N): # GET THE TOPIC FOR THE ENTRY: top = add_topic() # Create the fake data for that entry: fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry: webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.get_or_create(name = webpg, date = fake_date)[0] if __name__ == '__main__': print("Populating Script!") populate(20) print("Populating Complete!") This is the models.py file of the only app I have in this project. from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): … -
Get the file name of the included Jinja template that has error
I'm trying to get the line number and file name of a Jinja template in which there is a syntax error. For the moment, I've managed to get the line number with something like this: try: response = render_document_template(render_arguments) except TemplateError as error: line_number = error.lineno return Response( [str(error), line_number], status=status.HTTP_500_INTERNAL_SERVER_ERROR ) This works fine when working with templates that don't include other templates. The problem comes when working with templates that include other templates. I'm getting the line number of the included template, BUT I don't know in which of the several included templates the error is actually occurring. So I get something like there was a syntax error in line 10. But it is of not much use, since I don't know to which included file that line number refers to. So my question is, how can I know in which template is the error? -
django and nginx X-Accel-Redirect not working with mp4 file
im using django with nginx, to secure my static files. for the images i can secure with X-Accel-Redirect. but videos i can't secure. it says error response called 403 forbidden. this is my nginx config upstream myframe { server web:8000; } server { include mime.types; location / { try_files $uri @proxy_to_app; } # public static location /static/ { alias /app/static_root/; } # public media location /media/public/ { alias /app/media/public/; } # private media location /media/private/ { internal; alias /app/media/private/; } listen 80; client_max_body_size 256M; location @proxy_to_app { proxy_pass http://myframe; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } nginx err log 2020/07/19 10:11:53 [error] 6#6: *84 open() "/app/media/private/videos/albums/6/1595100896/video.mp4" failed (13: Permission denied), client: 112.134.40.212, server: , request: "GET /myframe/access/8 HTTP/1.1", upstream: "http://172.20.0.3:8000/myframe/access/8", host: "www.myframekw.com", referrer: "http://www.myframekw.com/myframe/" django function to check access def check_customer_access(self, user: object, item: object): returnData = {'status': False, 'http_response': None} try: if item.user_id == user.id: item_url = item.orginal_path.url mime_type = mimetypes.guess_type(item_url)[0] # init http response http = HttpResponse() http['Content-Type'] = mime_type http['X-Accel-Redirect'] = item_url http['Content-Disposition'] = f"attachment; filename='{item_url}'" returnData['http_response'] = http returnData['status'] = True except Exception as err: returnData["status"] = False returnData['error'] … -
Django manytomanyfield relation
I have a list of question ( approx 111 ) in table called Question and list of students in table Students. From frontend i will get each question answers, Hence what will be efficient way to store this data through django ORM. class Questions(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Students(models.Model): name= models.CharField(max_length=50) student_id = models.CharField(max_length=8) def __str__(self): return self.name class StudentAnswers(models.Model): questions = models.CharField(Questions) student = models.ForeignKey('Students', on_delete=models.CASCADE) answers = models.CharField(max_length=1000) What i have done is this , which took 1 minute. for each_question in Questions.objects.all(): each_question.studentanswers.add( StudentAnswers.objects.create(student = Students.objects.get(pk=1), answers ='answer')) ``` -
Django-Rest-Knox: TypeError: 'set' object is not subscriptable
I am trying to use django-rest-knox in my website. However, I seem to be getting the following error: I've tried uninstalling and installing django-rest-knox multiple times. However, the problem is persistent. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "E:\Anaconda\envs\myDjangoEnv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\knox\models.py", line 5, in <module> from knox import crypto File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\knox\crypto.py", line 7, in <module> from knox.settings import CONSTANTS, knox_settings File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\knox\settings.py", line 18, in <module> 'EXPIRY_DATETIME_FORMAT': api_settings.DATETIME_FORMAT, File "E:\Anaconda\envs\myDjangoEnv\lib\site-packages\rest_framework\settings.py", line 213, in __getattr__ val = self.user_settings[attr] TypeError: 'set' object is not subscriptable I've simply run the following command: python manage.py makemigrations INSTALLED_APPS = [ ... 'knox', 'rest_framework', ... ] … -
Boto3 + Django + S3 decoded base64 Image Upload not working
I am getting the image in base64 format through rest api def save_image_to_s3(product_name, product_id, image_base64): s3 = boto3.resource('s3') file_name_with_extension = product_name + str(product_id) + 'product.png' obj = s3.Object(AWS_STORAGE_BUCKET_NAME, file_name_with_extension) obj.put(Body=base64.b64decode(image_base64)) # get bucket location location = boto3.client('s3').get_bucket_location(Bucket=AWS_STORAGE_BUCKET_NAME)['LocationConstraint'] # get object url object_url = "https://%s.s3-%s.amazonaws.com/%s" % (AWS_STORAGE_BUCKET_NAME, location, file_name_with_extension) print "Printing Stored Url = " + object_url return object_url But I am getting below error EndpointConnectionError: Could not connect to the endpoint URL: "https://bucketname.s3.Asia-Pacific-Mumbai.amazonaws.com/xyz.png" After debugging I found the error is coming on below line obj.put(Body=base64.b64decode(image_base64)) My requirement is save the image to S3, get the stored image url and save into database. Please suggest a way forward -
Best way to trigger an action when a many to many field is added or removed in Django
I am trying to figure out the best way to achieve the following, but having no luck. I guess ideally I would like to over ride the add method for the specific field. Is this possible? Given the following model class SomeGroup(models.Model): users = models.ManyToManyField(User) I would like to trigger the below methods anytime SomeGroup.users.add(user) or SomeGroup.users.remove(user) is called def on_user_add() print("A user has been added") def on_user_remove() print("A user has been removed") Any help will be greatly appreciated. -
'django' is not recognized as an internal or external command,
I have been using django commands in my virtual environment for a longtime.... suddenly today When i run this command in my cmd from my Anaconda Env..... django manage.py runserver cmd responded with this 'django' is not recognized as an internal or external command, operable program or batch file. when i ran the command "conda list" it shows django package in the list... do anyone know a solution to this?? -
How do I create a Django formset_factory for each authenticated user?
So I have been using normal forms so far. In this case, I used form = myForm(initial={'authuser':request.user}) code to let user fill his/her own form. (I had authuser as foreign key to User model, obviously). But then I tried to use inlineformset_factory this time, but can't figure out how to do what I've done with normal forms. Any advice on this? Thank you very much. -
ReactJS website opens up as desktop version by default in IOS, changes to mobile version when requested Desktop version
Website link: https://www.ymgrad.com The website is behaving a bit weird on iPhones. Please note: This behavior is not showing on Androids, but only on iPhones. The issue persists amongst all browsers - tested on Chrome, Safari, Opera Mini on two different iPhone X phones. What's the issue? When I open up the website, by default the browsers try to open the mobile version loads. However, to my surprise, this looks like the desktop version instead. What's even more surprising is that if I request the Desktop version of the website, the mobile version shows up instead (which should have shown by default anyway). I've been dealing with this for a couple of months now, and I am finally posting this here. Images which show what I'm talking about: Default Loaded website version is desktop version even though the phone thinks it is mobile version. When requested desktop version, the browser shows mobile version. -
Performance updating large lists: Django filter then bulk_update vs temporary table
Thanks for reading my question! I use django (3.0.8) with postgres 12. Below is a simplified model for Inventory. There are about 1M records. class Inventory(models.Model): account = models.ForeignKey(Account, on_delete=models.PROTECT) item_id = models.LargeIntegerField(unique=True, db_index=True) amount = models.IntegerField() Every hour we receive new snapshots of one Account, e.g. acc_0. That contains a full list of items (~100k records), not deltas. I wanted to apply 3 actions: Set amount=0 where account==acc_0 if item_id not in the new snapshots. Set amount=snapshot['amount'] where account==acc_0 if item_id in the new snapshots. Create new items if snapshot['item_id'] not in Inventory.item_id Each time, most items already exist in DB and their amount is unchanged, i.e. the real delta is quite small (100-1k records). What I'm doing now seems not very efficient: with transaction.atomic(): Inventory.objects.filters(account=acc_0).update(amount=0) for snapshot in snapshots: results = Inventory.objects.filter(item_id=snapshot['item_id']) if len(results) == 0: new_items = ...list comprehension else: update_items = ...list comprehension Inventory.objects.bulk_create(new_items) Inventory.objects.bulk_update(update_items) I was wondering should I upload the snapshot to a temporary table and use JOIN / NOT EXISTS or even better there is a more pythonic way. -
NameError: name 'PostCreateView' is not defined
I'm using Django 3.0.8 I'm getting an error in path('post/new/',PostCreateView.as_view(),name='post-create') in blog/urls.py(blog is an app under my django_project). I've a class named PostCreateView in blog/views.py but it throws NameError:name 'PostCreateView' is not defined. My blog/views.py is here: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post # Create your views here. def home(request): context={ 'posts':Post.objects.all() } return render(request,'blog\home.html',context) class PostListView(ListView): model = Post template_name='blog/home.html' # <app>/<model>_<viewtype>.html context_object_name='posts' ordering=['-date_posted'] class PostDetailView(DetailView): model = Post class PostCreatelView(CreateView): model = Post fields=['title','content'] def about(request): return render(request,'blog\about.html',{'title':'About'}) and blog/urls.py is here: from django.urls import path from .views import PostListView, PostDetailView, PostCreatelView from . import views urlpatterns = [ path('',PostListView.as_view(),name='blog-home'), path('post/<int:pk>',PostDetailView.as_view(),name='post-detail'), path('post/new/',PostCreateView.as_view(),name='post-create'), path('about/',views.about,name='blog-about'), ] What is wrong with this code? Thanks in advance. -
Using Django template logic to determine if a object gets shown or not
I want to be able that if the user chooses Not public as his dropdown option, that the post doesn't get shown, if it is Public it gets shown. Code of index.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {% for post_object in object_list %} {% if post_object.choices == "Public" %} <h1>{{ post_object.post_title }}</h1> <p>{{ post_object.post_description }}</p> {% else %} {% endif %} {% endfor %} </body> </html> models.py code: class Post(models.Model): post_title = models.CharField("Post title", max_length=200) post_description = models.TextField("Small description of your post") post_summary = models.TextField("Post summary") post_public = models.CharField(max_length=300, choices=[('Not public', 'Not public'), ('Public', 'Public')], default="Not public") def __str__(self): return self.post_title How do i know what current option the user choose?