Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Avoid duplicate entries for the same field
I have a model choice in django. which has foreign key relationship with user model and items model. Each user can choose as many items as he wants from items model, the choice model will keep track of how many users have chosen what items. a particular user could be able to choose an item only once, but my problem is that when user1 select any item no other user can choose that one again. this is my code for choice fill. Views.py def choice_fill(request, cid): item_list = item.objects.all() title = "Choice Filling" page = "Choice Filling" if request.method == "POST": usr = user.objects.get(id=request.session['id']) # return render(request, 'success.html',{'stud':stud}) if usr.isactive != 1: messages.error(request, "Your registration process is incomplete.") else: if not choice.objects.filter(item_id_id=cid, isactive=1).exists(): userid = usr.id c = choice(user_id_id=studid, item_id_id=cid, isactive=1) c.save() else: return HttpResponse('multiple Entry for same college') models.py class user(models.Model): fullname = models.CharField(max_length=50) password = models.CharField(max_length=10) email = models.EmailField(unique=True) class item(models.Model): name = models.CharField(max_length=50) password = models.CharField(max_length=10) institute_code = models.IntegerField(unique=True) class choice(models.Model): user_id = models.ForeignKey(user, on_delete=models.CASCADE) item_id = models.ForeignKey(item, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.datetime.now()) updated_at = models.DateTimeField(default=timezone.datetime.now()) isactive = models.BooleanField() -
Is it possible to wrap Django code to ensure all database access for the ORM has "using" set by default?
I have a Django project that handles connections with multiple databases. I have a Database Router that handles the logic of which objects to store in a specific database which I easily use in my views, so no issue there at all. For example: class ClientDatabaseRouterMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, args, kwargs): if 'client_url' in kwargs: # kwargs = {key: value.lower() for key, value in kwargs.items()} thread_local.client_url = kwargs['client_url'].lower() else: if hasattr(thread_local, 'client_url'): del thread_local.client_url class ClientDatabaseRouter: def _default_db(self): from django.conf import settings if hasattr(thread_local, 'client_url'): db = thread_local.client_url if db in settings.DATABASES: return db else: if settings.DEBUG: if hasattr(settings, 'DEBUG_CLIENT_DB'): return settings.DEBUG_CLIENT_DB return None def db_for_read(self, model, **hints): instance = hints.pop('instance', None) if instance: if instance._state.db is not None: return instance._state.db if model._meta.app_label == 'client': return 'clients' if model._meta.app_label == 'django_celery_beat': return 'default' return self._default_db() db_for_write = db_for_read def allow_relation(self, obj1, obj2, **hints): return obj1._state.db == obj2._state.db def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'default': return app_label == 'django_celery_beat' if not app_label == 'client': if db == 'clients': return False else: return db == 'clients' return None However, I also use Celery and … -
How can I retrieve form data from Django CreateView?
I have a Django blog where the users can set the status of each post (active, inactive) when creating them. I am using Django's generic class-based views and would like to redirect the user to their created post only when the status is set to "active", otherwise they should be redirected to the homepage. How can I retrieve this submitted info from the form to create an if statement? For example: if status == "a"... views.py from .models import Listing from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import CreateView class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'status', 'content'] template_name = 'blog/post-form.html' success_message = 'Your post has been created.' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) -
How can I reference a user globally in Django for all Exceptions?
I have two questions that correlate. 1) Does django-rest-framework have a way to reference a user globally? 2) Does django / python allow me to change the generic exception class to include this user ID as meta every time it throws? I know I can create custom exception classes and raise them in code, but what about an exception I don’t correctly handle? For example, let’s say a divide by zero exception is thrown but I didn’t correctly handle it, right now my logs just say “Divide by zero exception”. Is there a way to update this globally so if a user is logged in it says “Divide by zero exception for user_id {id}“? class SomeExternalApiHelper: @staticmethod def do_api_call(): url = 'https://example.com' # do api request try: home_value = 100 / 0 except Exception as e: # Exception occurs here, I want to be able to reference user_id, without having # to pass the user_object all the way down into this call raise Exception("Something went wrong for user ID {0}".format(user_id)) class AddNewHouse(APIView): def post(self, request, format=None): # I can call request.user here and access the user object SomeExternalApiHelper.do_api_call() -
Django: Using current user as a foreign key to projects model
I am building a web-app where people can write projects. The projects are stored in a model and I want to use the user as the foreign key so I can show the user their projects on a webpage. Instances are entered through a form. The code always assigns the default value (1) and and not the user. Can any of you see what's causing this bug? Here is the code for the creation of the model in models.py: class PersonalProject(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() code = models.TextField() def __str__(self): return self.title Heres the code for the form view to create the project in views.py: def newproject(request): if User is None: messages.error(request, "Must be signed in") return redirect('main:dashboard') if request.method == "POST": form = NewProjectForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main:dashboard') else: messages.error(request, "Error") else: form = NewProjectForm() return render(request, "main/newproject.html", {"form":form}) Heres the code for the homepage view in views.py: def dashboard(request): messages.info(request, request.user.username) return render(request=request, template_name="main/dashboard.html", context={"structuredprojects": StructuredProject.objects.all(), "personalprojects": PersonalProject.objects.filter(user__username=request.user.username)}) I really hope you can help - I've been stuck on this for a while -
no python application found for uwsgi setting
I am setting with djano and uwsgi $uwsgi --ini uwsgi.ini My Django root is here /var/www/html/myapp/current It must be quite simple setting however I am not sure the yet. I have these two files /var/www/html/myapp/current/myapp/settings.py /var/www/html/myapp/current/myapp/wsgi.py [uwsgi] chdir=/var/www/html/myapp/current module=myapp.wsgi:application env DJANGO_SETTINGS_MODULE=myapp.settings http-socket = 0.0.0.0:8008 processes = 1 threasds = 1 master = 1 max-requests = 100000 The error is below, but I can't dig the detailed logs. spawned uWSGI worker 1 (pid: 27353, cores: 1) --- no python application found, check your startup logs for errors --- [pid: 27353|app: -1|req: -1/1] 172.17.1.143 () {28 vars in 334 bytes} [Thu Mar 26 17:37:01 2020] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) -
Business logic in django manager outside of query interaction
This will be a spin-off about the infinite dispute on where to put your business logic in Django. After reading tons of related question on Stack Overflow and the django docs, I'm still undecided whether to put business logic in a separate module (e.g. service.py) or encapsulate it inside a model.Manager. What cause me esitating on using manager in this case is its intro in the django doc: A Manager is the interface through which database query operations are provided to Django models Indeed, I need to create a function which autonomously analyses data from a model and passes them to a view that will forward them to the front-end. This is not actually a query the front-end performs on the db. Rather, it's the back-end notifying the user if a particular data has been found. So, according to the django doc, this is not exactly the case for relying on manager. -
Reverse for 'remove' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['remove\\/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)\\/\\$$']
I want the remove obj function to be triggered when the user click on it but its throwing error I have tried searching but cannot find solution I want to display a list ob objects and as soon as a user clicks on the object it gets deleted patients.html <body> {% include 'pages/nav.html' %} <div class="container"> <p>patients <a class="btn btn-primary btn-lg" role ="button" href="/patientadd">Add Patients</a> </p> <div class="list-group"> <br> <br> {% for i in names %} <a href="{% url 'remove' pk=i.pk %}" class="list-group-item">{{i}}</a> {% endfor %} </div> </div> </body> views.py not the whole view def removeObj(request, pk): object = get_object_or_404(request,pk) object.delete() model.py from django.db import models from django.contrib.auth.models import User class Patient(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField() numvisit = models.IntegerField() detail = models.TextField(max_length=300) # url pattern urlpatterns = [ path('admin/', admin.site.urls), path('register/',register,name="register"), path('patients/',patients,name="patients"), path('patientadd/',patientAdd,name="patientadd"), path('login/',login,name="login"), path(r"remove/(?P<pk>\d+)/$",removeObj,name="remove"), path('register/logout/',logout,name="logout"), path('',home), ] -
Python anywhere deploying static django files wont work followed tutorial 100 %
I am trying to deploy my static files from my django app using python everywhere. I have followed 3 different tutorials now and none of them have worked. my STATIC_URL is set to /static/ and my STATIC_ROOT is '/home/coursePlanner/CoursePlanner/static' I collected all static files to the static root folder ('/home/coursePlanner/CoursePlanner/static) and If I use the python anywhere file broswer they are certainly all there. in my python anywhere WSGI file, path is set to '/home/coursePlanner/CoursePlanner' and os.environ['DJANGO_SETTINGS_MODULE'] is set to 'CoursePlanner.settings'. Finally, in the static files section of the webapp settings, URL = '/staitc/' and directory=/home/coursePlanner/CoursePlanner/static. When I open my webpage none of my static files load. Furthermore If I go to http://courseplanner.pythonanywhere.com/static/css/styles.css I get the following page: Page not found (404) Request Method: GET Request URL: http://courseplanner.pythonanywhere.com/static/css/styles.css Using the URLconf defined in CoursePlanner.urls, Django tried these URL patterns, in this order: admin/ [name='courseplanner-planner'] validate/ getRec/ search/ reqBarHandler/ getUnits/ The current path, static/css/styles.css, didn't match any of these. but if i go to the request URL in the python anywhere file manager, the file is present literally at that exact URL. What is going on? Any help would be greatly apperciated as Ive literally spent almost two full days trying … -
update field of queryset before passing to formset in django
i have a queryset that contains age of traveller. qset = Travellers.objects.filter(traveller_type='1') print(qset) print(qset[0].traveller_age) travellers_formset = TravellersFormset(queryset = qset) this gives give: <QuerySet [<Travellers: Travellers object (16887)>]> 33 i intend have a flag (is_renewal), which if true, should update the age of traveller by a year before passing to queryset to formset. so i'm doing something like this if travel_quote.is_renewal: print('starting renewal section') for each in qset.iterator(): print(each) print(each.traveller_age) each.traveller_age = each.traveller_age + 1 print(each.traveller_age) print('renewal section completed, checking for updated age') print(qset[0].get_fields()) this gives starting renewal section <QuerySet [<Travellers: Travellers object (16887)>]> 33 34 renewal section completed, checking for updated age 33 <<<<< i want this to be 34 instead of 33 after the loop -
how could I see in django the code of import lib utilizing shortcut keys in windows?
how to see in django the code of import lib utilizing shortcut keys in windows? Ad example the code behind djmoney etc. ? I remember that it is necessary to place the mouse on the library and press shortcut keys (ctrl+...) but I don't remember what. Thanks you and good evening from Italy -
django: python manage.py runserver issue
I am using Windows 10 and installed django via Anaconda conda install -c anaconda django after that I created a new project django-admin startproject website When I navigte into the folder where the manage.py file is an run python manage.py runserver I get the following output and nothing happens. Any ideas? -
Django : OneToOneField - RelatedObjectDoesNotExist
I have this two following classes in my model: class Answer(models.Model): answer = models.CharField(max_length=300) question = models.ForeignKey('Question', on_delete=models.CASCADE) def __str__(self): return "{0}, view: {1}".format(self.answer, self.answer_number) class Vote(models.Model): answer = models.OneToOneField(Answer, related_name="votes", on_delete=models.CASCADE) users = models.ManyToManyField(User) def __str__(self): return str(self.answer.answer)[:30] In the shell I take the first Answer: >>> Answer.objects.all()[0] <Answer: choix 1 , view: 0> I want to get the Vote object: >>> Answer.objects.all()[0].votes Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Hippolyte\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related_descriptors.py", line 420, in __get__ raise self.RelatedObjectDoesNotExist( questions.models.Answer.votes.RelatedObjectDoesNotExist: Answer has no votes. But an error occured. I don't understand why the related_name is not recognized. Could you help me ? -
Custom vs Generic Views in Django
The question is about generic views, and their use in practice. They are presented as a better, cleaner, alternative for writing custom views, however they didn't seem to simply the view code much, and seemed very case specific. So in practice, are these generic views used extensively, with custom ones written only for very specific cases? Or is it the opposite, and generic views only exist for minimalists/case specific needs? -
Avoid race condition during creating object with incremented field
I'm trying to create MyModel object but I want to set bar field to already existed largest bar value in db for specified foo. The problem here are race conditions. I wanted to perform all logic on db side in one step without sucess. I have found solution but it's not the most elegant way. Infinite loops are always bad idea. from django.db import models, IntegrityError from django.db.models import Max class MyModel(models.Model): foo = models.UUIDField(primary_key=True, default=uuid4) bar = models.PositiveIntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['id', 'other_id'], name='unique_id_other_id' ) ] @classmethod def create_my_model(cls, data): while True: bar = (cls.objects.filter(foo=data['foo']).aggregate(Max('bar')).get('bar_max') or 0) + 1 try: cls.objects.create(bar=bar, **data) except IntegrityError: continue I will be glad if anyone can point me any direction how to handle this. BR -
Djongo not connecting to mlab server
I am using djongo with django2 to connect to mlab mongodb instance. settings.py 'default': { 'ENGINE': 'djongo', 'NAME': 'neon', 'HOST': 'mongodb://username:password@ds249605.mlab.com:49605/mlab1', } } although I am using this settings, the PyMongo connects to the local instance of mongodb. log Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/database.py", line 856, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/database.py", line 819, in list_collections _cmd, read_pref, session) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1454, in _retryable_read read_pref, session, address=address) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1253, in _select_server server = topology.select_server(server_selector) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/topology.py", line 235, in select_server … -
I need help to integrate duo_python 2FA into Django-mama-cas
I've setup django-mama-cas as a primary central authentication server for serveral department websites. The websites reside in a drupal/php web framework and use phpCAS for the CAS client. I need to integrate duo_python somehow to the django-mama-cas server. I am not sure where to start and any advice on what files or classes to edit is what I am looking for. From what I imagine those [files, classes, etc] to be, are below: settings.py import os import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, PosixGroupType # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! with open('/n/fs/stage/signon/cas_container/casServer/secret_key.txt') as f: SECRET_KEY = f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['signon.example.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mama_cas', ] 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 = 'casServer.urls' # Django Templates Settings: https://docs.djangoproject.com/en/2.2/topics/templates/ 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', ], }, }, ] # WSGI Settings: https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ WSGI_APPLICATION = 'casServer.wsgi.application' # Database Settings: https://docs.djangoproject.com/en/2.2/ref/databases/ DATABASES = … -
login_required decorator on a class based view in django
I have a working class based view. But when adding @login_required I get the error: AttributeError: 'function' object has no attribute 'as_view' Something is happening to the ResultListView here: from django.urls import path from .views import ResultListView urlpatterns = [ path('meetings/', ResultListView.as_view(), name='meetings'), ] My views.py: @login_required class ResultListView(ListView): template_name = ... def get_queryset(self): return Result.objects.filter(rider__user=self.request.user) Which is all working fine until I put the decorator in. Very confused now, I don't see why ResultListView should loose its attributes when sending it through the decorator. -
Get the last and unique element of the list based on date
Here is my data and code: [ (datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 24), 'Raport'), (datetime.date(2020, 3, 23), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 24), 'Document'), (datetime.date(2020, 3, 23), 'Document'), (datetime.date(2020, 3, 25), 'Analize'), (datetime.date(2020, 3, 24), 'Analize'), (datetime.date(2020, 3, 23), 'Analize'), ] Here is django (2.2) code: sorted(DataSet.objects.values_list('doc_type', flat=True).distinct(), reverse=True) I need to get the last and unique element of each document doc_type together with the date. At the moment I have the same list of documents: ['Raport', 'Document', 'Analize'] but I need: [(datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 25), 'Analize')] Can someone provide me some hint? Thanks. -
Django View: ConnectionError: HTTPSConnectionPool
I have a django view in a production project: @csrf_exempt def test_view(request): ... Clients who intended to use this endpoint for a redirect says that its not working. I try to test it locally. If I access the url using the browser it works fine but every time I try to access this endpoint in a script locally. I get this error: import requests r = requests.get('http://mywebsite.com/test/?test_run=me') print(r.text, r.status_code) error: File "venv\lib\site-packages\requests\adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='mywebsite.com', port=443): Max retries exceeded with url: /test/?test_run=me(Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000011424D0ABE0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)) Process finished with exit code 1 Any idea of resolving ? -
Linking a model in Django
I have two models LeaveType and MyUser class LeaveType(models.Model): type_ = models.CharField(max_length=50, null=False, blank=False) total_leave_per_year = models.IntegerField(null=False, blank=False, default = 0) def __str__(self): return self.type_ Say, Leave types are: 1. Annual Leave of 20 days per year 2. Sick Leave of 5 days per year class MyUser(models.Model): dob = models.DateField(auto_now_add=True) leave = models.ForeignKey(LeaveType, on_delete=models.CASCADE, related_name="lms_leave_type") Now, When a user apply for an annual for 2 days then his/her remaining leave will be 18 days per year. Now how can I manage this? I have tried to use Inline ways but it does not work for me. Another method I tried is building another model containing user object, leave type object and his/her remaining leaves. Is this a better way or we have another better than this? Thank You. :) -
Order a Django queryset by another dict
So, right now I have this model and a calculated dictionary class User(models.Model): user_id = models.AutoField(primary_key=True) #scores dict {user_id: score} scores = {1: 9, 2: 2, 3: 1, 4: 5} I need to order the queryset based on each user score in the scores dict. Something like this Views.py queryset.annotate(score=scores['user_id']).order_by('score') -
get django rest api Image field url as data to generate QRcode
Im absolute beginner and currently trying to generate qr code so ,how would i get or retrive the url of image field in views.py so that i can add data to make qr code basically the original image is first posted in aws with django rest framework models.py from django.db import models class Picture(models.Model): Original_Image = models.ImageField(upload_to="media/images") QR_Embedded_Image = models.ImageField('QR_Embedded_Image') created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('App', views.PictureView) urlpatterns = [ path('', include(router.urls)), path('upload-image/', views.UploadImage.as_view(), name="UploadImage"), ] views.py class PicturesView(viewsets.ModelViewSet): queryset = Pictures.objects.all()[:2] serializer_class = PicturesSerializer def create(self, request): image_url = upload_files_to_s3("image.jpeg") qr_code = qrcode.QRCode(box_size=2) qr_code.add_data('image url ') qr_code.make() qr_code_img = qr_code.make_image(fill_color= "#000000" , back_color= "white") qr_code_img.save(' ') -
How to get key-value of context in Django?
I try to query to get all of Topic of Post. Each Post belong multiple Topic. I got this but i don't know how to pass to Template. This is my code. In template i got posts but i can't access topics of single posts. Thank for help. models.py class Post(models.Model): title = models.CharField(unique=True, max_length=121) content = models.TextField() published = models.DateField(default=timezone.now) def __str__(self): return self.title class Topic(models.Model): topic_name = models.CharField(primary_key=True,unique=True, max_length=60) posts = models.ManyToManyField(Post) def __str__(self): return self.topic_name views.py def codinglife(request): posts = Post.objects.filter(topic__topic_name__contains='codinglife') #Get posts belong topic 'codinglife' context = { 'posts': Post.objects.filter(topic__topic_name__contains='codinglife') } # for each post get topic this post belong many topic for post in posts: context[post.id] = Topic.objects.filter(posts=post) return render(request, 'site/topiclistview.html', context) Template {% extends "site/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ post.published }}</small> {% comment 'need to show topic her' %} {% endcomment %} </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} -
Django Quiz make it repeatable
I found this via google: https://github.com/sibtc/django-multiple-user-types-example I would like to change this quiz so that a checkbox asks if the quiz may be repeated when creating it. I have added the repeat in the models. class Quiz(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes') name = models.CharField(max_length=255) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='quizzes') repeat = models.BooleanField(default=False) and also ind the craete and updateview class QuizCreateView(CreateView): model = Quiz fields = ('name', 'subject', 'repeat', ) Now of course I would like the quiz to be repeated. For this purpose I have in the appropriate view: @method_decorator([login_required, student_required], name='dispatch') class QuizListView(ListView): model = Quiz ordering = ('name', ) context_object_name = 'quizzes' template_name = 'classroom/students/quiz_list.html' def get_queryset(self): student = self.request.user.student student_interests = student.interests.values_list('pk', flat=True) taken_quizzes = student.quizzes.values_list('pk', flat=True) queryset = Quiz.objects.filter(subject__in=student_interests) \ #.exclude(pk__in=taken_quizzes) \ .annotate(questions_count=Count('questions')) \ .filter(questions_count__gt=0) return queryset Here I have temporarily removed the corresponding exclude. Then I see the quiz in the list, but unfortunately I cannot call it up again. Now I get the template error: Exception Type: TemplateDoesNotExist Exception Value: students/taken_quiz.html How can I have the quiz repeated now?