Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I was trying to run django qcluster in my local machine and getting this error - Any help would be really appreciated
I'm doing this to run the DjangoQ - This is my Q_CLUSTER config inside my settigns.py file - Q_CLUSTER = { 'name': 'default_orm', 'compress': True, 'save_limit': 0, 'orm': 'default' } python manage.py qcluster File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'BaseDatabaseCache.__init__.<locals>.CacheEntry' -
TypeError: create_user() missing 3 required positional arguments(when createsuperuser)
I get this error when trying to create superuser: TypeError: create_user() missing 3 required positional arguments: 'first_name', 'last_name', and 'role' Is this the proper way to create it? I want to create superuser without username, just with email, and user can login only with their email addresses, and now when I create superuser it wants email, how I wanted, but gives me the error too. class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, role, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, role=role, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_employee = True user.is_headofdepartment = True user.is_reception = True user.is_patient = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractUser): ADMIN = 1 RECEPTION = 2 HEADOFDEPARTMENT = 3 EMPLOYEE = 4 PATIENT = 5 NOTACTIVE = 6 ROLE_CHOICES = ( (ADMIN, 'Admin'), (RECEPTION, 'Reception'), (HEADOFDEPARTMENT, 'HeadOfDepartment'), (EMPLOYEE, 'Employee'), (PATIENT, 'Patient'), (NOTACTIVE, 'NotActive'), ) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, default=True, null=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_headofdepartment = models.BooleanField(default=False) is_reception = models.BooleanField(default=False) is_patient … -
get current domain name in settings.py file
I am running a multisite project with various tenant domains. In my settings.py file, I have a variable name called TENANT_DOMAIN that I would want to set the current tenant domain name before the settings file is run. How do I go about this? -
Django reset password using phone number or email
I am creating a mobile app with django and drf. I am giving users the option to register using phone number or email. For email I can obviously use the built in PasswordResetView however I have no idea how to reset password using the phone number. Here is my User model class User(AbstractBaseUser): email = models.EmailField( null=True, blank=True, verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name='username', max_length=100, unique=True) phone_number = PhoneField( max_length=10, blank=True, null=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' objects = UserManager() -
Deploying Django application on LAN
I have a Django application that I want to deploy on LAN for use/production. I need a help how to deploy it on Windows Server (Step by step). -
in python how to access half iterate forloop value outside without if condition
i am iterating a large number of list like 100,000 data. I want to know how much iteration is completed outside of the loop. I don't want to use if condition. if condition increases execution time. def callme(): for data in range(100000): # i want to return 'data' after every 5 seconds. # without if condition return data -
how i can solve these error on django runserver
Whenever i want to run a server of django these error message shows in my VS code (django) PS C:\python\New folder\django\To_Do> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\python\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\python\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python\New folder\django\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\python\New folder\django\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run -
python django: How to fix error saying: AttributeError at / 'Home' object has no attribute 'get'
i'm trying to create two pages for my website in django. I get an Error: AttributeError at /'Home' object has no attribute 'get' The above 'Home' is a class in my models but I do not know why it says 'Home object no attribute get' when I have called Home.objects.all() in my views.py My models: from django.db import models class Product(models.Model): name = models.CharField(max_length=20) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Home(models.Model): heading = models.CharField(max_length=10) words = models.CharField(max_length=10000) My views: from django.http import HttpResponse from django.shortcuts render from .models import Product, Home def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def home(request): home_obj = Home.objects.all() return render(request, 'home.html', {'Home': home_obj}) My app urls: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('fruits/', views.index), path('', views.Home), ] index.html: {% extends 'base.html' %} {% block content %} <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">₹ {{ product.price }}</p> <a href="#" class="btn btn-primary">add to cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} home.html: <h2>{{ home_obj.heading }}</h2> <p>{{ home_obj.words }}</p> … -
How to search for objects in the Django User model
I have a Profile model: from django.contrib.auth.models import User class Profile(models.Model): first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=100, blank=True) And a search contacts view: class SearchContactsView(ListView): model = Profile template_name = 'users/contact_search.html' context_object_name = 'qs' def get_queryset(self): q1 = self.request.GET.get('contact_name') q2 = self.request.GET.get('contact_location') if q1 or q2: return Profile.objects.filter(Q(first_name__icontains=q1) | Q(last_name__icontains=q1), location__icontains=q2) return Profile.objects.all() It is working fine but I would like to be able to search for contacts via the user field as well. Does anyone know a way to do that? -
What command do we use to create a folder in pycharm?
I was coding in python. I typed this code python3 manage.py startapp products in order to create a folder, and I tried to find the folder, but I did not see nothing appeared. May someone help me to fix it please? -
'AnonymousUser' object has no attribute 'authenticated'?
I am using Django Version: 3.0.2. Student registration is working and user is saving to database successfully. The problem is after login it is showing 'AnonymousUser' object has no attribute 'authenticated'. Please any one solve my problem? views.py: from django.contrib.auth.models import User, Group, auth def studentregistration(request): if request.method == 'POST': form = StudentRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['user_name'] password = form.cleaned_data['password'] confirmpassword = form.cleaned_data['confirm_password'] email = form.cleaned_data['email'] if password == confirmpassword: if User.objects.filter(username=username).exists(): messages.error(request,'user already exists please login') return render(request, 'login.html') elif User.objects.filter(email=email).exists(): messages.error(request, 'email already registered please login') return render(request, 'login.html') else: user=User.objects.create_user(username=username, password=password, email=email) user.save() messages.success(request, "Successfully registered, Please login") return render(request, 'login.html') else: messages.error(request, 'password and confirmation password do not match') return render(request, 'studentregistration.html') #return HttpResponseRedirect('studentregistration.html') else: form = StudentRegisterForm() return render(request, 'studentregistration.html', {'form': form}) def login(request): if request.method == 'POST': username = request.POST.get('user_name', '') password = request.POST.get('password', '') user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('exam_pattern') else: messages.error(request,'invalid credentials') return render(request, 'login.html') else: return render(request,'login.html') Here, i am autheticated user, but i am getting 'AnonymousUser' object has no attribute 'authenticated' after login. def render_questions(request): if not request.user.authenticated: return render(request, 'login.html') else: global exam_session exam_session = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) questions = … -
Django Channels error with received messages
I have a simple chat app example from channels dockerized but im having a problem when i open 2 chats. If i open the first window and send a message, the consumers capture my message and reply to all channels in group (only me at the moment) Normal test Then if i open another window and send a message i receive two messages in the same window (same socket) and not other message in the first window-chat New window and two messages BUT i can send messages from the old window, im just going to see this messages in the new window. No messages from user2 But i send messages, i cant see it and user2 can see it My consumer # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username … -
How can i upload a image in database using django?
I have a python code for processing image. What i want now is- I want to upload an image from Webapp using django I want to process the uploaded image. I want to show the final output & store the result in server. can anyone help me with code & details? -
How to have a check that User must Select at least one of the two Foreign Keys in Django Rest Framework
I am trying to make a Django App. I am facing this issue that I need to bound the user to at least select one of the foreign keys. The logic being the user should have his own Idea or he needs to request one of the ideas posted by the teacher. My code looks like this. Models.py class RequestFYP(models.Model): requested_to = models.ForeignKey(Faculty, on_delete=models.CASCADE, related_name='Teacher') requested_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Student_Idea = models.ForeignKey(FYP, on_delete=models.CASCADE, null=True, blank=True) Related_Idea = models.ForeignKey(Idea, on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name_plural = 'Requests' def __str__(self): return self.requested_by Serializers.py class RequestFYPSerializer(serializers.ModelSerializer): requested_by = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = RequestFYP fields = '__all__' API.py class RequestFYPView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = RequestFYPSerializer def get_queryset(self): return RequestFYP.objects.filter(requested_by=self.request.user) def create(self, request, *args, **kwargs): serializer = RequestFYPSerializer(data=request.data) if serializer.is_valid(): serializer.save(requested_by=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Unable to save data into Foreign key fields in Django Rest Framework
I'm working on a project where I have to enroll students in a course. I have a model called Enrollment with two foreign key fields to Course, and Student. I'm trying to save course and student in Enrollment model when they submit. But after calling the save method also response returns a response as course and student are required. My models class Course(models.Model): course_name = models.CharField(max_length=300,default=None) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) course_description = models.TextField(null=True) course_cover = models.ImageField(null=True,blank=True,upload_to='course_covers/') def __str__(self): return self.course_name``` class Enrollment(models.Model): enroll_key = models.CharField(max_length=100,default="Text here",null=True) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True) student = models.ForeignKey(StudentProfile,on_delete=models.CASCADE,null=True) def __str__(self): return self.course.course_name class Meta: unique_together = [['course','student']] Serializer class CourseEnrollSerializer(serializers.ModelSerializer): class Meta: model = Enrollment fields = ['enroll_key','course','student'] My views @api_view(['POST']) @permission_classes([IsAuthenticated]) def EnrollCourse(request,pk): course = Course.objects.get(id=pk) print("course",course) student = StudentProfile.objects.get(user=request.user) print("student",student) serializer = CourseEnrollSerializer(data=request.data) print(serializer) print("loading the serializer...") if serializer.is_valid(): serializer.save(course=course,student=student) else: print("Serializer not valid",serializer.errors) return Response(serializer.errors) urls.py path('enrollcourse/<int:pk>/',views.EnrollCourse,name='enroll_course'), #pk is course primarykey What I get after printing serializer.errors {'course': [ErrorDetail(string='This field is required.', code='required')], 'student': [ErrorDetail(string='This field is required.', code='required')]} -
no module named 'social' when I'm trying to get a new facebook access_token in the postman using my new heroku domain name instead of localhost:8000
There Are The Steps I Followed To get an access_token after pushed my project into heroku I Changed My Site Url Of My App On Facebook from localhost:8000 to https://whispering-hamlet-67095.herokuapp.com/ changed my ALLOWED_HOSTS In Settings.py To ALLOWED_HOSTS = ["localhost","whispering-hamlet-67095.herokuapp.com"] This Step=> ### Testing On PostMan To Get facebook access_token As Usual Like I Used To Do When My Project is Only Running Locally But I Got This error When I Changed The Url From localhost:8000/ to https://whispering-hamlet-67095.herokuapp.com/ So What Should I Do To Use Facebook access_token with my new heroku domain and solve this error And There Are My settings.py code : import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ---------- SECRET_KEY = 'lr2g%2&4666(ghg%&dqhlzcm=f9$5&%q6l*z1+v7vh+khxackr' DEBUG = True ALLOWED_HOSTS = ["localhost","whispering-hamlet-67095.herokuapp.com"] ---------- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'egystoreapp', 'rest_framework_social_oauth2', 'social_django', 'oauth2_provider', 'bootstrap3', ] ---------- MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ---------- ROOT_URLCONF = 'egystores.urls' ---------- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] ---------- WSGI_APPLICATION = 'egystores.wsgi.application' ---------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ---------- AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, … -
ModuleNotFoundError: No module named 'mysite' (PythonAnywhere0
I'm trying to deploy my Django site using PythonAnywhere. The steps I followed were from https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/ This is the code in my WSGI File This is what it says in my error log -
Using Django Rest Framework to initiate data processing on the backend
I have a fully functioning Django application and I am now adding an API using Django Rest Framework. I will creating a React front end which will use the API provided via DRF. I have worked out how to use DRF to create endpoints for my models using ModelViewSets and ModelSerializers. These work fine. I now need to create an endpoint that initiates some data processing. The endpoint will need to accept a date as input and then call some code to do the processing. My standard Django application currently does this by accepting a date via a Django form and then initiating a celery task. Here is the view: class GenerateRosterView(LoginRequiredMixin, FormView): """Generate Roster View.""" template_name = "generate_roster.html" form_class = GenerateRosterForm def get_form_kwargs(self): """Pass request to form.""" kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs def get_success_url(self): """Get success URL.""" return reverse("roster_generation_status", args=(self.task_id,)) def form_valid(self, form): """Process generate roster form.""" start_date = form.cleaned_data["start_date"] self.request.session["start_date"] = start_date.date().strftime( "%d-%b-%Y" ) result = generate_roster.delay(start_date=start_date) self.task_id = result.task_id return super().form_valid(form) Here is the form: class GenerateRosterForm(forms.Form): """Generate Roster Form.""" def __init__(self, request, *args, **kwargs): """Get default start date from session.""" super().__init__(*args, **kwargs) if "start_date" in request.session: start_date = datetime.datetime.strptime( request.session["start_date"], "%d-%b-%Y" ) else: start_date = … -
Django - How can I set a Model's field using the existance of a ForeignKey as a condition?
I am trying to create a Django app where there are two main models - Team and Person. A Person can use the app as an User or can belong to a Team, and, in that case, the User will be the Team. class Team(models.Model): name = models.CharField(max_length=50) team_user = models.ForeignKey( User, on_delete = models.CASCADE, null = True, blank = True ) class Person(models.Model): person_user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True) team = models.ForeignKey( Team, on_delete = models.CASCADE, null = True, blank = True ) I am trying to develop a File structure like this: /root /Team_01 /Person_01 (non-User) /files.csv /Person_02 (non-User) /files.csv /Person_03 (User) /files.csv I have read the documentation and I was trying to do something with the comment from Evgeni Shudzel in this post, but my problem is that I don't know how to set the file's path for the Person model so that if the Person is member of a Team, the path is "/team_id/person_id" and if not, the "/team_id" part is excluded. The pseudocode I have in mind: if Person.team exists: files = models.FileField(upload_to="TEAM_ID/PERSON_ID/") else: files = models.FileField(upload_to="PERSON_ID/") How can I implement this pseudocode? Thank you! -
django alternative to prevent header poison
Firstly I don't speak English very well, but anyway... i know I need to use allowed_hosts, but I need to use all "*" and a header attack can cause something like: <script src = "mysite.com/js/script.js"> <script> to <script src = "attacker.com/js/script.js"> <script> or mysite.com/new_password=blabla&token=blabla8b10918gd91d1b0i1 to attacker.com/new_password=blabla&token=blabla8b10918gd91d1b0i1 But all static files are load on a nodejs server "cdn.mysite.com" and all domains are in the database, so I always take the domain from the database to compare with the request header, and use the domain from the database of data to send anything to the client: views.py: def Index(request): url = request.META['HTTP_HOST'] cf = Config.objects.first() if cf.domain == url: form = regForm() return render(request, 'page/site/home.html', {'form': form}) elif cf.user_domain == url: ur = request.user.is_authenticated if ur: config = {'data' : request.user} lojas = 'json.loads(request.user.user_themes)' return render(request, 'app/home.html', {"config":config, "lojas":lojas}) else: forml = loginForm() return render(request, 'page/users/login/login.html', {'form':forml}) else: redirect("//" + cf.domain) Would that still be unsafe to use this way? -
Show product instance in Django UpdateView with Select Boxes
I need to show the product instance in the select boxes. I am very sure I followed the get_object and get_initial method pretty well but the form does not seem to initiate with the product I want to update. Any other way to do this? Model: class Order(models.Model): options = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=options, null=True, max_length=200) def __str__(self): return self.status class Meta: ordering = ['-date_created'] My View: class OrderUpdateView(UpdateView): model = Order form_class = OrderUpdateForm template_name = 'crmapp/update-order.html' context_object_name = 'order' success_url = '/' def get_initial(self): initial = super(OrderUpdateView, self).get_initial() content = self.get_object() initial['customer'] = content.customer initial['product'] = content.product initial['status'] = content.status return initial def get_object(self, *args, **kwargs): product = get_object_or_404(Order, pk=self.kwargs['pk']) return product The Url: path('update-order/<str:pk>/', OrderUpdateView.as_view(), name='update-order') The HTML <div class="container"> <div class="row"> <div class="col-sm-6 offset-3"> <br><br><br><br> <form action="{% url 'update-order' order.pk %}" method="POST"> {% csrf_token %} {{ form.as_p}} <button class="btn btn-primary btn-block" type="submit">Save</button> </form> <br><br><br><br> </div> </div> -
How to get a users lat and long via button press in Django?
I'm in the process of trying to create an app that can grab a users lat and long when a button is press/clicked. I plan on storing the lat and long inside of a model field for each individual press/click. Only to be used later on inside of an interactive map, displaying every lat and long that has been stored. Looking into Leaflet or Google Maps API to implement a map. I've read the Django documentation on GeoIP2 and I think it may be my best option but I'm not sure if there are any better options? As far as implementing GeoIP2 goes, it's really as simple as what I have below, correct? from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() lat,lng = g.lat_lon(user_ip) model_field_example_lat = lat model_field_example_lng = lng -
Django migrate rollback multiple migrations on failure
Django migrations has excellent behavior in terms of single migrations, where, assuming you leave atomic=True, a migration will be all-or-nothing: it will either run to completion or undo everything. Is there a way to get this all-or-nothing behavior for multiple migrations? That is to say, is there a way to either run multiple migrations inside an enclosing transaction (which admittedly could cause other problems) or to rollback all succeeded migrations on failure? For context, I'm looking for a single command or setting to do this so that I can include it in a deploy script. Currently, the only part of my deploy that isn't rolled back in the event of a failure are database changes. I know that this can be manually done by running python manage.py migrate APP_NAME MIGRATION_NUMBER in the event of a failure, but this requires knowledge of the last run migration on each app. -
I want to get an ID from the URL and query my data. Django Rest Framework
I am making a Marvel based API and I want to get the ID from the url and query the fields from that ID. my models.py: class Characther(models.Model): name = models.CharField(max_length=100) comics = models.TextField() events = models.TextField() series = models.TextField() stories = models.TextField() my views.py class CharList(generics.ListCreateAPIView): queryset = Characther.objects.all() serializer_class = CharSerializer def get(self, request, id): id = request.GET.get('id', '') return render(request, self, {'comics': get_object_or_404(comics, pk = id)}) class ComicList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'comics') serializer_class = ComicSerializer class EventsList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'events') serializer_class = EventsSerializer class SeriesList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'series') serializer_class = SeriesSerializer class StoryList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'stories') serializer_class = StorySerializer my url : urlpatterns = [ url(r'^v1/public/characters/(?P<id>[\w-]+)/', views.ComicList.as_view(), name = 'comics') ] -
how to make green color body using using is_grater_priority
`class Todolist(models.Model): title = models.CharField(max_length=255) detail = models.TextField(max_length=255, null=True, blank=True) created = models.CharField(max_length=255) is_grater_priority=models.BooleanField(default=False)` i have done this, but not working Now what should i do to make this workable ` {% if list %} {% for obj in list %} {% if obj == is_grater_priority %} <p class="text-success"><strong>Title:- </strong> {{obj.title}} </p> <p class="text-success"><strong>Details:- </strong> {{obj.detail}} </p> <p class="text-success"><strong>Sheduled:- </strong> {{obj.created}} </p> <a href="{% url 'todolist:edit_todolist' obj.id %}">Edit</a> <a href="{% url 'todolist:delete_todolist' obj.id %}">Delete</a> <hr> {% else %} <p><strong>Title:- </strong> {{obj.title}} </p> <p><strong>Details:- </strong> {{obj.detail}} </p> <p><strong>Sheduled:- </strong> {{obj.created}} </p> <a href="{% url 'todolist:edit_todolist' obj.id %}">Edit</a> <a href="{% url 'todolist:delete_todolist' obj.id %}">Delete</a> <hr> {% endif %} {% endfor %} {% else %} <h2>No list avilable</h2> {% endif %}`