Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
use django "include" inside a js function
I am doing a search page in which parameters are sent by ajax and then upon reception of the queryset I rebuild my cards. The whole thing is classic and working ok, here is a simplified version of the thing. Lots of lines killed or modified since it is not really the subject of the post let getobject = async (value,url) => { var res2 = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify({ value: value, }) }) let data2 = await res2.json(); videoitems.innerHTML = '' modalbin.innerHTML = '' data2["data"].forEach(async item => { if (item.ext == '.mp4') { const dynamicreation = async () => { let dyncontent3 = await createnewcard(item) let placing = await videoitems.appendChild(dyncontent3); } const nooncares2 = await dynamicreation() } else if (item.ext == ".pdf") { const dynamicreation2 = async () => { let dyncontent4 = await createnewcard(item) let placing2 = await videoitems.appendChild(dyncontent4); } const nooncares4 = dynamicreation2() } }) } the createnewcard function var createnewcard = item => { var dyncontent = document.createElement("div"); dyncontent.innerHTML = `<div class="m-2 extralarge-modal video${item.id}"> <div data-reco="${item.id}" class="extralarge-modal bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700"> <div class="p-5"> <p class="mb-3 font-normal text-gray-700 dark:text-gray-400"> ${item.title} </p> </div> … -
Django redirect not working in my view function
From my crop crop_prediction view I am trying to redirect it to 'http://localhost:8000/Efarma/crop_detail/' page but instead of this it render the current html page ,the home page which is also the starting page of this website. Some error is showing in my console '[26/Apr/2022 22:31:29,457] - Broken pipe from ('127.0.0.1', 62868)' but I have no idea what is it. To go to crop_detail page i have to manually put it in search box. urls.py:- from django.urls import path, include from .import views urlpatterns = [ path('', views.home), path('crop_prediction/', views.crop_prediction), path('crop_detail/', views.crop_info) ] views.py:- def home(request): return render(request, 'Efarma/index.html') def crop_prediction(request): global resultJson, firebase print(request.POST) print(request.GET) if request.method == "POST": N = float(request.POST.get("nitrogen")) P = float(request.POST.get("phosphorus")) K = float(request.POST.get("potassium")) ph = float(request.POST.get("ph")) rainfall = float(request.POST.get("rainfall")) city = request.POST.get("city") if weather_fetch(city) != None: temperature, humidity = weather_fetch(city) data = np.array([[N, P, K, temperature, humidity, ph, rainfall]]) print(temperature, humidity, "--------kkk-------") my_prediction = pickle.load( open('CropRecommendation\model\model.pkl', 'rb')) final_prediction = my_prediction.predict(data) value = final_prediction[0] firebase = firebase.FirebaseApplication( 'https://e-farma-5dc42-default-rtdb.firebaseio.com/') predicted_crop_info = firebase.get(value, None) predicted_crop_info["crop"] = value resultJson = dumps(predicted_crop_info) return redirect('http://localhost:8000/Efarma/crop_detail/') else: return redirect('http://localhost:8000/Efarma/crop_detail/') def crop_info(request): print(resultJson) return render(request, "Efarma/crop_detail.html", {"result": resultJson}) error:- -
Running multiple independent docker containers for web services
I'm trying to run a few services on my server, by using separate docker image for each service: nginx - with a configuration for all available services below and access to the files on the server - should be always running Wordpress - for hosting a Wordpress web page (and probably PHP?) - will be almost always running on the server Django - for hosting a Django web page - will be sometimes running only Flask RESTful API - maybe in the future will be added I'm using docker-compose to configure nginx and django app, but I cannot run only nginx container without django (I've tried to use links and depends_on in docker-compose.yml). So long story short - I want to be able to add, run and stop containers for web services independently. -
In Django, is there a way you can limit a user to registering for an event only once?
I'm a newbie to Django, trying to build site to allow people to register for football matches. At the moment, a user can register multiple times for the same match, which is obviously not ideal! Is there a way that I can identify if the currently logged in user has already registered, and then replace the register button with a message telling them that they have already registered? I guess I need some kind of Boolean value in my EventDetail view, and then I can make a conditional statement in the template, but I'm unsure as to how to implement this. I hope this question is clear, it's my very first post! views.py: class EventDetail(View): def get(self, request, id, *args, **kwargs): event = get_object_or_404(Event, pk=id) registrations = Registration.objects.filter(event=event) total_participants = 0 for person in registrations: total_participants += 1 if person.guest: total_participants += 1 remaining_spaces = event.max_participants - total_participants template = "event_detail.html" context = { "event": event, "total_participants": total_participants, "registrations": registrations, "remaining_spaces": remaining_spaces, } return render(request, template, context) template {% extends "base.html" %} {% block content %} <p>{{ event.title }}</p> <p>{{ total_participants }} / {{ event.max_participants }} ({{ remaining_spaces }} spot{{ remaining_spaces|pluralize }} remaining!)</p> {% if total_participants < event.max_participants %} <a … -
Django - How to pass current url parameters if any to a new url after pressing a button
My current page has a filter that the user can fill if wanted. In the same page there is a button that redirects the user to a new url that downloads a file. My question is: How i can pass the first page url parameters and pass them to the new url/view? If i add them in my url and they are not filled then i have an error. -
django.templates.exceptions.TemplateDoesNotExist
Even in the settings.py, I have added the INSTALLED_APPS section but still, it is not working. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # this is for the authentication 'django.contrib.contenttypes', # this tells about the MIME type 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # it help us to host the static files 'HelloWorld', ]` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], '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', ], }, }, ] -
How to use swagger_auto_schema decorator in django if the class based view does not have any serializer_class?
I have a class based view as: class DetailView(GenericAPIView): @swagger_auto_schema(responses={201: 'Created'}) @authorize(CustomPermission) def post(self, *args, **kwargs) -> Response: // code..... return Response(status=HTTPStatus.CREATED) First: The use of swagger_auto_schema without any serializer is throwing error as: AssertionError: DetailView should either include a serializer_class attribute, or override the get_serializer_class() method. And I don't want to use serializer for this endpoint as I don't need that. But the swagger_auto_schema keeps on throwing this error. I want to know whether there is any way to avoid the use of serializer and get the swagger documentation of this endpoint. Second: I also want to add authorisation of this endpoint in the doc. I know there is a security field in swagger_auto_schema, but don't know how to make it to use for my custom permission class ie CustomPermission Thanks. -
when I type python manage.py runserver it gives me this error __init__() takes 1 positional argument but 4 were given
I am working on a django project having django 2.1 version. now I want to run it successfully on local server. but when I type python manage.py runserver, it gives me an error log which is given below. can anyone can guide me how to run it successfully? what part of the code should I look for to fix it? Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x0000013BF20405E0> Traceback (most recent call last): File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\Dell\Documents\Satkardeep Django\wowtasks.com_django\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked … -
Why DAO is not used in most python web application like flask, django and sanic?
I've worked in lots of python web project. I also used flask, django and sanic to develop web applications and restful api services. Recently I heard DAO from my friend who writes both java and python code. Obviously DAO has its advantages but why I see no use of DAO (but most use ORM directly) in my past python web projects and similar projects in github? -
Dynamic URL's with multible layers
Im making a website using Django, where im making dynamic URLs. However i'm fairly new to programming and haven't been able to find out how to make dynamic URLs with more than 1 parametre. I'm making a site called "kartotek", which are user specific defined by the varible "kl_id", and therefore has a dynamic URL with following path: path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"), On this page, is there a button with which you choose a patient and come to another URL called "reg" with the following path: path('reg/<str:kl_id>/<str:pt_id>/', views.reg, name="reg"), I have the following code in views.py: def kartotek(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) E_patient = kliniknavn.patient_set.all() context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient} return render(request,'DentHelp/kartotek.html', context ) def reg(request ,kl_id , pt_id): kliniknavn = Klinik.objects.get(navn=kl_id) ptid = Patient.objects.get(id_nr=pt_id) context = {'ptid':ptid, 'kliniknavn':kliniknavn} return render(request,'DentHelp/reg.html', context) I think the problem is the template code, which I'm kinda confused how to make, I was trying this: {% for patient in E_patient %} <a href="{% url 'reg' klinik.navn, patient.id_nr %}" class="btn btn-primary">Vælg patient</a> {% endfor %} Any have an advise? -
Only view detailpage if user is none
I have two models, an user model and a key model. Where the key model is a foreignkey in the user model. I want to make it so the detailpage of each key is only accessible if the particular key is not connected to any user. I have made a test_func with the UserPassesTestMixin but I am not able to write the requirement correctly. This is my view class KeyView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Key template_name = 'base/key.html' def test_func(self): user = self.request.user if user.is_teacher == True and Key.objects.filter(user__isnull=True): return True return False -
Auto generate and save data to SlugField
Hello I have a function to auto generate data for my SlugField but i dont know how to implement a save method to execute it. Ive tried calling the function from the save method but it raises an error of 'instance not defined'. Any suggestions will help. Thanks. def ran_str_gen(size=6, chars=string.ascii_letters + string.digits): return ''.join(secrets.choice(chars) for s in range(size)) def slug_gen(instance, new_slug=None): if new_slug is not None: slug=new_slug else: slug = slugify(instance.title) op = instance.__class__ qs_exists = op.objects.filter(slug=slug).exists() if not qs_exists: new_slug = '{slug}-{ranstr}'.format(slug=slug, ranstr=ran_str_gen()) return slug_gen(instance, new_slug=new_slug) return slug class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField() def save(self, *args, **kwargs): slug_gen() -
Django: how to extends a view to another view without copy and paste?
i have a view that shows my navigation bar, i am adding the navgigation bar dynamically from the database, but th problem is that i have to add that same piece of code to all my views for the navigation text to show up and that is making my code so length, is there a way to automatically extends the peice of code that is getting my navigation to all the views, so when i go to another page like the about page or contact, or profile page i can still see the navigation bar. Now only when i see the navigation bar is when i go to the index.html views.py def index(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } def about_page(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } def contact_page(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } def profile_page(request): designcatlist = DesignCategory.objects.all() prglangcatlist = ProgrammingLanguagesCategory.objects.all() howtocatlist = HowToCategory.objects.all() context = { ... } NOTE as you can see in the code above, i need to add the same piece of code for the naviation to show up on … -
How to redirect users to a mobile app in Django view?
I have a Django web application and I'm trying to redirect users to my mobile app in one of the views. def magic_link(request, token): return redirect(f"{settings.FRONTEND_URL}/magic_link/{token}") This redirect link is like: appname://magic_link/token. However, I'm getting the following error. DisallowedRedirect at /magic_link/{token}/ Unsafe redirect to URL with protocol 'appname' How can I fix this issue and redirect users to the mobile app in Django view? -
Reverse for 'password_reset_confirm' not found
I have django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error after I put in email address into password_reset.html and click send button. Why is it looking for password_reset_confirmat this point in the first place? password_reset.html {% extends "base.html" %} {% block content %} <form method="post"> {% csrf_token %} <h1>Forgot your password?</h1> <p>Enter your email address below, and we'll email instructions for setting a new one.</p> {{ form.as_p }} <button name="submit" class="btn">Send me instructions</button> </form> {% endblock content %} urls.py from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from .forms import UserLoginForm from . import views app_name = "users" urlpatterns = [ path('login/', auth_views.LoginView.as_view( template_name='users/login.html', authentication_form=UserLoginForm), name="login"), path('logout/', auth_views.LogoutView.as_view(next_page='index'), name="logout"), path('register/', views.register, name="register"), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view( template_name="users/password_reset_done.html"), name="password_reset_done"), path('reset_password/', auth_views.PasswordResetView.as_view( template_name="users/password_reset.html", success_url=reverse_lazy('users:password_reset_done')), name="reset_password"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name="users/reset_password_complete.html"), name="password_reset_complete"), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( success_url=reverse_lazy('users:password_reset_complete')), name="password_reset_confirm"), path('activate/<uidb64>/<token>', views.activate, name="activate"), ] -
unhashable type 'list' when i enter on change_list in Django
I search for days for a solution for this problem. after touching the admin.py file to override the get_queryset and get_form methods I ran into the unhashable type 'list' error, which has no information on where the error is located. I removed the override for the get_queryset and get_form methods, but I still get the same result. [The error][1] I find this error when I want to filter a list by overriding the get_queryset method or when I try to enter an element of the form's list. The files in my project are as follows: APP => Main admin.py @admin.register(Notification) class NotificationsAdmin(admin.ModelAdmin, ExportCsvMixin): form = NotificationForm add_form = NotificationForm list_display = ('title', 'description', 'created_at', 'updated_at', 'author') fieldsets = ( ('Information', { 'fields': ('author', 'title', 'subject', 'description', 'signature') }), ('Images', { 'fields': ('banner', 'image', 'image2', 'image3') }), ('Send to', { 'fields': ( 'send_to', 'send_all', ) }), ('Logs', { 'fields': ('created_at', 'updated_at') }), ) readonly_fields = ('created_at', 'updated_at') actions = ['export_as_csv'] list_per_page = 20 # list_max_show_all = 30 def get_form(self, request, obj=None, **kwargs): if request.user.groups.filter(name="RSM's").exists(): self.readonly_fields = ('author', 'created_at', 'updated_at') else: self.readonly_fields = ( 'created_at', 'updated_at', ) form = super(NotificationsAdmin, self).get_form(request, **kwargs) form.current_user = request.user return form # get_queryset will return the … -
Admin Page and Home Page broken after set up environ in Django
I created an application with Django backend and React frontend. In the project, I place an .env file in the root folder my_project/ .env my_app/ __init__.py apps.py settings.py urls.py views.py wsgi.py frontend/ public/ src/ build/ static/ js/ main.4dfd1f01.js css/ main.5c1407a3.css Then I use "django-environ" as my env library and do the setting as following in setting.py import os import environ ENV = environ.Env( DEBUG=(bool, False) ) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Take environment variables from .env file environ.Env.read_env(os.path.join(BASE_DIR, '.env')) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'frontend/build'], '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', ], }, }, ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'frontend/build/static' ] urls.py: from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('sub-app/', include('sub-app.urls')), path('', TemplateView.as_view(template_name='index.html')), ] Everything works fine except my root URL (localhost:8000/) and admin URL (localhost:8000/admin): The problem on admin: when I input localhost:8000/admin in the browser, it simply redirects to a nonsense URL (like: http://127.0.0.1:8000/127.0.0.1:8000/sub-app/ca/admin/) **I don't even have any 'ca' anywhere in any of my urls.py … -
How to update GeoDjango model with area fields
Here the model: from django.contrib.gis.db import models class City(models.Model): mpoly = models.MultiPolygonField() area = models.IntegerField(null=True) I want to update all records at once to set the area. I've tried : from django.contrib.gis.db.models.functions import Area, Transform City.objects.all().update(area=Area(Transform("mpoly", 2154))) Which fails with "DataError: value too long for type character varying(8)"... Do you have an elegant one liner to do it ? -
imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
def trash_view(request): global i, addr, passwrd, conn if request.method == 'POST': imap_url = 'imap.gmail.com' conn = imaplib.IMAP4_SSL(imap_url) conn.login(addr, passwrd) conn.select('"[Gmail]/Trash"') result1, data1 = conn.search(None, "ALL") mail_list = data1[0].split() text = "You have reached your trash folder. You have " + str(len(mail_list)) + " mails in your trash folder. To search a specific email say search. To go back to the menu page say back. To logout say logout." Hi friends, while i can work on "INBOX" , for "TRASH" section, it gives me this error"imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED". how can i solve this? Thank you -
Forward slash "/" vs "os.path.join()" vs "joinpath()" for STATIC_ROOT and MEDIA_ROOT (Django)
I found there are 3 concatenation ways using forward slash "/", "os.path.join()" or "joinpath()" for "STATIC_ROOT" and "MEDIA_ROOT" as shown below and these 3 concatenation ways work properly for me. Forward slash "/": # "settings.py" STATIC_ROOT = BASE_DIR / 'static' MEDIA_ROOT = BASE_DIR / 'media' "os.path.join()": # "settings.py" STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') "joinpath()": # "settings.py" STATIC_ROOT = BASE_DIR.joinpath('static') MEDIA_ROOT = BASE_DIR.joinpath('media') So now, which way do you recommend to use, forward slash "/", "os.path.join()" or "joinpath()" for "STATIC_ROOT" and "MEDIA_ROOT"? -
Heroku. ImportError: cannot import name 'ugettext_lazy' [duplicate]
I have deployed my project to Heroku. But I got "Internal server error" "ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/init.py)" Yes, I know that I should write "gettext_lazy" instead. But I can't find this file in my project. I got this error only after deploy. I don't understand where it is situated. Help me, please. -
Forward slash "/" concatenation for STATIC_ROOT and MEDIA_ROOT (Django)
I found sometimes forward slash "/" is used to concatenate "BASE_DIR" and "static" or "media" for "STATIC_ROOT" and "MEDIA_ROOT" in "settings.py" as shown below: # "settings.py" # Here STATIC_ROOT = BASE_DIR / 'static' # Here MEDIA_ROOT = BASE_DIR / 'media' So, it's possible to concatenate BASE_DIR which is 'PosixPath' type and 'static' which is 'str' type with forward slash "/". But when I tried to concatenate 'str' type and 'str' type with "/": # "settings.py" STATIC_ROOT = 'abc' / 'static' I got this error below: TypeError: unsupported operand type(s) for /: 'str' and 'str' And for 'int' type and 'str' type with "/": STATIC_ROOT = 123 / 'static' I got this error below: TypeError: unsupported operand type(s) for /: 'int' and 'str' Then for 'MyClass' type and 'str' type with "/": # "settings.py" class MyClass: pass STATIC_ROOT = MyClass() / 'static' I got this error below: TypeError: unsupported operand type(s) for /: 'MyClass' and 'str' So, can we only concatenate 'PosixPath' type and 'str' type with forward slash "/"? Aren't there any other types to concatenate with forward slash "/"? -
Django admin won't load on my local after logging in
I'm new to python and django. I've copied my production app, that another developer wrote, onto my local. It's working perfectly. When I run django admin I get the login form. But when I enter my ID and PW I get redirected to the same login form, only it's blank; I never get logged in. The server console reads: [26/Apr/2022 06:25:21] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 [26/Apr/2022 06:25:21] "GET /admin/ HTTP/1.1" 302 0 [26/Apr/2022 06:25:21] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 11020 I don't understand what's needed to change or get added. Any help appreciated. -
How do i pass list to ModelMultipleChoiceField
This is the participant selection form class EventFormAdmin(ModelForm): name = forms.TextInput(attrs={'class':'form-control'}), manager = forms.Select(attrs={'class':'form-select'}), venue = forms.Select(attrs={'class':'form-select'}), event_date = forms.TextInput(attrs={'class':'form-control'}), participants = forms.ModelMultipleChoiceField( **queryset=Participant.objects.filter().values(participant_list),** #filter for participants who applied for a specific event widget=forms.CheckboxSelectMultiple ), description = forms.Textarea(attrs={'class':'form-control'}), class Meta: model = Event fields = ('name', 'manager', 'venue', 'event_date', 'participants', 'description') How do i put participant_list in ModelMultipleChoiceField in the function, I described the filter by values that I try to pass to the form field def update_event(request, event_id): event = Event.objects.get(pk=event_id) participant_list = Participant.objects.filter( event = event_id ) if request.user.is_superuser: form = EventFormAdmin(request.POST or None, instance=event) else: form = EventForm(request.POST or None, instance=event) if form.is_valid(): form.save() return redirect('all_events') return render(request, 'events/update_event.html', { 'participant_list':participant_list, 'event': event, 'form':form }) Thanks -
How to display multiple views in a Django project's template?
I have a Django project with multiple apps and I would like to manage the template from the project root folder. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', "DIRS": [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': {...} }] In the homepage index.html of the project I'm trying to display num_exchanges and num_accounts generated in the views.py of app1 and app2. The problem is that only num_exchanges is printed not the second variable. If I switch the include in urlpatterns then the second variable is generated not the first one. How can I print both variables ? urls.py (project) urlpatterns = [ path('admin/', admin.site.urls), url(r"^", include("app1.urls"), name='app1'), url(r"^", include("app2.urls"), name='app2'), ] index.html (project) {% load static %} {% block content %} <h2>App1</h2> <p>Records in database:</p> <ul> <li><strong>Exchanges:</strong> {{ num_exchanges }}</li> </ul> <h2>App2</h2> <p>Records in database:</p> <ul> <li><strong>Account:</strong> {{ num_accounts }}</li> </ul> {% endblock %} views.py (app1) from django.shortcuts import render from app1.models import Exchange def app1_stats(request): num_exchanges = Exchange.objects.count() context = { 'num_exchanges': num_exchanges } return render(request, 'index.html', context=context) urls.py (app1) from django.urls import path from app1.views import app1_stats urlpatterns = [ path('', app1_stats, name='index'), ] views.py (app2) from django.shortcuts import render from app2.models import Account def app2_stats(request): num_accounts = Account.objects.count() context = { …