Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the correct way of using ManyToOne relation in Django
I am working on a Job Portal website and having some questions I wonder what's the correct way of using the relations in my case. For example: I have a CompanyProfile where a company can have multiple locations. I have a Job that can have multiple locations aswell. I have a Student, and a Student can make a Curriculum Vitae that exists of SkillSet, Education and Experience. This is wat I have now: A class CompanyProfile A Location Class where a CompanyProfile is a foreignkey of. A Job class where CompanyProfile and Location is foreinkey of. A Skillset, Education and Experience class all 3 of them have foreign key to CV. CompanyProfile class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='company_profile') company_name = models.CharField(max_length=30) Location class Location(models.Model): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE) address = models.CharField(max_length=100, null=True) zip_code = models.CharField(max_length=10, null=True) city = models.CharField(max_length=30, null=True) CV class Cv(models.Model): user = models.ForeignKey(StudentProfile, on_delete=models.CASCADE) Education, Experience and Skillset all same class Education(models.Model): cv = models.ForeignKey(Cv, on_delete=models.CASCADE) ... ... more fields. My question is. Is this the right way or should I Put a foreignkey in CompanyProfile class to Location. And should I put in CV 3 foreign keys of education, experience and skillset or is … -
i need cookie to get updated when user gets online again for notification
here is want i want to do: users can have collections of image about a certain thing (flowers for example). my websites looks at this collections and recommends related images. i want to give users a notification that a recommendation is ready even if browser is closed, users only need to be online. exactly like Pinterest. so i guess my cookie needs to see whether i'm online or not by trying to send something and if i am online my server will send the link to the recommendation section. three question: 1) what code should be in the cookie? 2) best way to send notification? 3) how to do the "sending links to users" asynchronously or with threading? i'm using django but it shouldn't matter, what would you do if you aren't using django, you don't have to answer all of that, if you know even one of them, it's still appreciated -
How do i run a shell script inside docker-compose
I have a use case in which i am trying to build a django based rest api and then use continuous integration using travis CI when changes are pushed to github. I am also using docker to build and docker-compose to scale my services. The problem is i want to run pytest and flake8 when i push my changes to github. Now i have not added any tests and hence the pytest command is giving an exit status of 5. To get around this i tried creating a script to do this : #!/bin/bash pytest; err=$? ; if (( $err != 5 )) ; then exit $err; fi flake8 ; But i cannot get docker-compose to run this . When i run the script using the command : docker-compose run app sh -c "run_script.sh" It gives the below error message : sh: run_script.sh: not found Below is my docker-compose yml file: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" And below is the dockerfile: FROM python:3.7-alpine MAINTAINER Subhayan Bhattacharya ENV PYTHONUNBUFFERED 1 COPY Pipfile* /tmp/ RUN cd /tmp && pip install pipenv && pipenv lock --requirements > … -
Django-webpack-loader uses wrong port (npm run serve increases)
I'm new in webpack and vuejs. I have a problem with https://github.com/owais/django-webpack-loader As far as I know I need to start npm server to serve bundles. (feedbot) milano@milano-desktop:~/PycharmProjects/feedbot/frontend$ npm run serve > frontend@0.1.0 serve /home/milano/PycharmProjects/feedbot/frontend > vue-cli-service serve INFO Starting development server... 98% after emitting CopyPlugin DONE Compiled successfully in 1125ms App running at: - Local: http://localhost:8091/ <<<<<< HERE YOU CAN SEE THE PORT - Network: http://0.0.0.0:8080/ 10:37:55 PM I use this in my template: <div id="app"> <app></app> </div> {% render_bundle 'index' %} I can see in inspect that render_bundle renders wrong url: http://127.0.0.1:8080/index.js How do I make it work? The npm increases port instead of reusing 8080. So either I make django-webpack-loader to somehow recognize which port is in use or npm to reuse 8080. -
Django REST saves Image but returns wrong path
I am trying to save Community image and it saves it to /api/media/imagename.jpg, but when I retrieve a community it gives me /media/imagename.jpg without /api and then it can't find a image. So I have this Community model with FileField: class Community(models.Model): """DB Model for Community""" name = models.CharField(max_length=150, unique=True) description = models.TextField(default="") created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) number_of_members = models.IntegerField(default=1) community_image = models.FileField(blank=False, null=False, default="", upload_to="") def __str__(self): return self.name And I have this in my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") And then this is in my urls.py: # urls.py in authentication_api application router = DefaultRouter() router.register('communities', views.CommunityViewSet) urlpatterns = [ path('', include(router.urls)), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urls.py in root urls file urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('authentication_api.urls')) ] What should I change to it returns correct path to image. If you need any more code sample please comment. -
Python's scipy.optimize.fsolve crashes on (Webfaction) server despite working fine on similar localhost
I have a personal website, written in Django, hosted on Webfaction. I am trying to make a web tool in which users enter some numbers, the server receives them on the backend via AJAX, the server takes them as parameter inputs for a certain system of equations and solves it numerically using some Python package, and the server returns the solution via AJAX and Javascript presents it to the user. This process works flawlessly when I test it on Localhost. But on the Webfaction server, it often crashes after a few iterations of the numerical approximation function, as long as the inputs are not very simple. Both scipy.optimize.fsolve and scipy.optimize.root produce the issue. I have tried multiple "method"s, and they have all produced the issue. Also, I was originally on Webfaction's $10/mo "1GB RAM, 100GB SSD storage, 1TB bandwidth, shared server" plan, and I tried switching to their $30/mo "4GB RAM, 45GB SSD storage, 2TB bandwidth, 2 CPU cores, cloud server" plan--a setup similar to my Localhost--but this doesn't seem to have made even the slightest difference. from scipy.optimize import fsolve import logging from forms import * logger = logging.getLogger(__name__) def dppsubmit(request): form = ParamsForm(request.POST) if form.is_valid(): raw_pd = form.cleaned_data['params'] … -
Best way to send an email with the content of a model instance that may or may not rely on the content of a ManyToManyField
In my app, I need to email an invoice when a new model instance is created. The model, however, has a ManyToManyField that alters the content of the invoice if any of the ManyToManyField options are selected. If an instance is created without any of the ManyToManyField options selected, everything can be handled within the overridden save() method. If an instance is created with any of the ManyToManyField options selected, everything can be handled with the m2m_changed signal. The problem I have to be able to generate and send the invoice if the m2m_changed signal is fired, but if I do that, I don't want to send anything out in the save() method. But I also have to be able to generate and send the invoice in the save() method because if none of the ManyToManyField options are selected, the save() method is the only method that will fire. The question Is there a way to make sure the m2m_changed signal is always fired? Or, is there a way for the save() method to be aware that the m2m_changed signal will fire? -
How to update a django model's field from another model
So I have two models like this : class Subscription(models.Model): ... number_editions = models.IntegerField() ... def __str__(self): return self.client class Shipment(models.Model): ... num = models.IntegerField() ... What I want to do is to update the field "number_editions" (-1) every time an object "num" is created. Any idea how to do it? Thnaks -
How to implement sorting in Django Admin for calculated model properties without writing the logic twice?
In my Django model, I defined a @property which worked nicely and the property can be shown in the admin list_displaywithout any problems. I need this property not only in admin but in my code logic in other places as well, so it makes sense to have it as property for my model. Now I wanted to make the column of this property sortable, and with help of the Django documentation of the When object, this stackoverflow question for the F()-calculation and this link for the sorting I managed to build the working solution shown below. The reason for posing a question here is: In fact I implemented my logic twice, once in python and once in SQL (sort of), which is against the design paradigm of implementing the same logic only once. So I wanted to ask whether I missed a better solution for my problem. Any ideas are appreciated. This is the model (identifyers modified): class De(models.Model): fr = models.BooleanField("[...]") de = models.SmallIntegerField("[...]") gd = models.SmallIntegerField("[...]") na = models.SmallIntegerField("[...]") # [several_attributes, Meta, __str__() removed for readability] @property def s_d(self): if self.fr: return self.de else: return self.gd + self.na This is the Model Admin: class DeAdmin(admin.ModelAdmin): list_display = ("[...]", … -
Django manual control of modified-since
I have an endpoint where I usually cache the data. But I want to refresh the data every few hours. So I want to implement a condition similar to: if header.last_modified - now() > one_hour: return create_new_data_with_last_modified_set_to_now() else: return http_answer_304_not_modified() The problem is that Django's API only supports last_modifed(callback_that_gets_last_modified) that both compares the last modification time, and sets it to the same value on the HTTP response. How can I control these 2 values separately? P.S: The reason I need this is that I send some information that timeouts after X seconds. So if X/2 seconds already passed, I want to refresh it -
Why Django Showing this kind of error and how to fix it?
urls.py `from django.urls import path from.import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), path('ourwork', views.ourwork, name='ourwork'), path('portfolio', views.portfolio, name='portfolio'), path('blog', views.blog, name='blog'), path('careers', views.careers, name='careers'), path('contact', views.contact, name='contact'), ]` views.py `from django.shortcuts import render Create your views here. def index(request): return render(request,'artsoft/index.html') def about(request): return render(request,'artsoft/about.html') def ourwork(request): return render(request,'artsoft/ourwork.html') def portfolio(request): return render(request,'artsoft/portfolio.html') def blog(request): return render(request,'artsoft/blog.html') def careers(request): return render(request,'artsoft/careers.html') def contact(request): return render(request,'artsoft/contact.html') ` sccreen short [The Error page][1] but when i clicking on blog this is work [Blog page][2] [views.py][3] [urls.py][4] [directories of files][5] [1]: https://i.stack.imgur.com/VqXzq.png [2]: https://i.stack.imgur.com/gKTrd.png [3]: https://i.stack.imgur.com/VgWIM.png [4]: https://i.stack.imgur.com/Rckvp.png [5]: https://i.stack.imgur.com/Ut2vw.png -
Django contact form not sending email
I have a simple contact form set up on my about page, and after filling in the fields and clicking submit, I get a "Success!" message that the email was sent. However, the email never arrives in my inbox. I've read numerous posts on here about this problem (seems to be pretty common) but everything I've tried does not work; even using django.core.mail.backends.console.EmailBackend fails to print in the console, yet I still get a "Success!" message when submitting. My settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv("SECRET_KEY") DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.live.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxx@hotmail.com' EMAIL_HOST_PASSWORD = os.environ['EMAIL_PASSWORD'] ... My views.py: ... from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.shortcuts import redirect from .forms import ContactForm ... class AboutPage(TemplateView): template_name = 'database/templates/about.html' def about(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['xxxx@hotmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, 'about.html', {'form': form}) def success(request): return render(request, 'success.html') My urls.py: from django.urls import path from . import views urlpatterns = [ ... path('about/', views.about, name='about'), … -
Cant connect to django process running in container with vs-code
Im having trouble connecting to a django process running inside a container spawned with vs-code. Everything seem to be working and I get the startup message for the server, but when connecting to localhost:8000, I get no response... I get a published port message when starting the container: Published Ports: 8000/tcp -> 127.0.0.1:8000 and also a clean start when starting launch.json debug System check identified no issues (0 silenced). October 13, 2019 - 17:45:05 Django version 2.2.6, using settings 'fpl-django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Why cant I access the site on: localhost:8000? devcontainer.json: // For format details, see https://aka.ms/vscode-remote/devcontainer.json or the definition README at // https://github.com/microsoft/vscode-dev-containers/tree/master/containers/docker-existing-dockerfile { "name": "Existing Dockerfile", // Sets the run context to one level up instead of the .devcontainer folder. "context": "..", // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename. "dockerFile": "../docker/dev/python/Dockerfile", // The optional 'runArgs' property can be used to specify additional runtime arguments. "runArgs": [ // Uncomment the next line to use Docker from inside the container. See https://aka.ms/vscode-remote/samples/docker-in-docker for details. // "-v","/var/run/docker.sock:/var/run/docker.sock", // Uncomment the next line if you will be using a ptrace-based debugger like C++, Go, and Rust. // "--cap-add=SYS_PTRACE", … -
How can I upgrade pip version in cloud foundry for python buildpack
I am trying to host a django application on cloud foundry. I am getting error: "You are using pip version 9.0.1, however version 19.2.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command." Now, how can I upgrade pip version for my application in cloud foundry environment I tried mentioning buildpack in manifest.yml from: https://github.com/cloudfoundry/python-buildpack Manifest.yml file applications: - name: app command: python manage.py runserver buildpack: https://github.com/cloudfoundry/python-buildpack.git -
how to reassign value to a variable after doing arithmetic operations in Django Template Language (jinja2)
I want to do arithmetic operations within Django Template format and also assign the new value to the same Variable I have so far used {{with}} {{set}} and also django-mathfilters but i am unable to reassign value back to the same variable. {% with count=0 %} {% for report in reports %} <tr> <th scope="row">{{set count count|add:"1"}}</th> <td>{{report.submit_time}}</td> <td>{{report.file_name}}</td> {% if report.is_complete %} <td>Complete</td> {% else %} <td>Pending</td> {% endif %} <td>{{report.score}}</td> </tr> {% endfor %} {%endwith%} i want to show numbers in serial in my table -
Changing Django's default list of Common Password
I just try to use Django. when i try to create superuser with the createsuperuser and i try to use some common password like abcd1234 (because abc or 123 isn't allowed), it cannot accept it because apparently that my password is too common, i know that the createsuperuser use somekind of password list to match mine with theirs. I want to ask that whether it is possible to change the password list. i already tried to open manage.py to find the createsuperuser method but i didnt find it because it only contains run(sys.argv) -
Try to build tv-series & movies site with django
I am trying to build a tv series and movies site , but I can't access the Ep from Tv. I am trying to make my url look like that www.SiteName.com/friends/ep/1 but I have no idea what I should write in views.py and urls.py . this is my models.py from django.db import models class Tv(models.Model): title = models.CharField(max_length=250) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title class Episode(self): title = models.CharField(max_length=250) EpisodeNumber = models.IntegerField() slug = models.SlugField() def __str__(self): return self.title -
Run script.py to fetch values everytime the page is loaded in django
Trying to learn django, and I felt the best way to do so is building a simple project. My goal is to execute a bash command through subprocess by taking form input that has some choice fields based on a list derived from file. What I did was execute whatever command I needed to get the list, parse the log file to obtain the list and then use the list in the choice field as options. Then, use the input to fire another subprocess call to execute the required bash command. I have the following code, My form.py from django import forms from . import script from django.core.exceptions import ValidationError class PostForm(forms.Form): p1 = forms.ChoiceField(choices=enumerate(script.choices),label='Player 1') p2 = forms.ChoiceField(choices=enumerate(script.choices2),label='Player 2',required=False) x = forms.IntegerField(required=False) y = forms.IntegerField(help_text='Set to 70 if unknown',required=False) z = forms.IntegerField(required=False) def clean(self): cleaned_data = super(PostForm, self).clean() p2 = cleaned_data.get("p2") cordsx = cleaned_data.get("x") cordsy = cleaned_data.get("y") cordsz = cleaned_data.get("z") if p2 and (cordsx or cordsy or cordsz): # both were entered raise forms.ValidationError("Enter either co-ords or player 2 name") elif not p2 and not (cordsx or cordsy or cordsz): # neither were entered raise forms.ValidationError("You must enter either co-ords or player 2 name") return cleaned_data My script: import … -
Django rest related model not included
I have a TwitchChannel model which has a ForeignKey relationship to CustomUser. class TwitchChannel(models.Model): login = models.CharField(max_length=25) display_name = models.CharField(max_length=25) twitch_user_id = models.CharField(max_length=50) email = models.EmailField(null=True, blank=True) profile_image_url = models.URLField(null=True, blank=True) access_token = models.CharField(default="none", max_length=100) refresh_token = models.CharField(default="none", max_length=100) live = models.BooleanField(default=False) channel_data = JSONField() created = models.DateTimeField(auto_now=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) def save(self, **kwargs): make_password(self.access_token) make_password(self.refresh_token) super().save(**kwargs) def __str__(self): return self.display_name def get_channel_url(self): return f"https://twitch.tv/{self.login}" In my UserSerializer I want to include this TwitchChannel when it exists. The following are my serializers. class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) twitch_channel = TwitchChannelSerializer(read_only=True, many=True) def create(self, validated_data): user = UserModel.objects.create( email=validated_data["email"], first_name=validated_data["first_name"], last_name=validated_data["last_name"] ) user.set_password(validated_data["password"]) user.save() return user def update(self, instance, validated_data): if 'password' in validated_data: password = validated_data.pop('password') instance.set_password(password) class Meta: model = UserModel depth = 3 fields = ( "id", "first_name", "last_name", "email", "password", "twitch_channel") extra_kwargs = {"password": {"write_only": True, }} class TwitchChannelSerializer(serializers.Serializer): class Meta: model = TwitchChannel fields = ( 'user_id', 'login', 'display_name', 'email', 'profile_image_url', 'access_token', 'refresh_token', 'live', 'channel_data', 'created', 'user' ) However, when I do a request for the user the field isn't even included at all. { "id": 3, "first_name": "Patrick", "last_name": "Hanford", "email": "testing@streambeacon.tv" } I get no error, but the field is non-existent. -
I have Django project I want to show agreement and privacy and policy show one per user login first time
I want to add to agreement and privacy and policy show one per user login first time and after admin change, an agreements or policy .etc that time show a to a user. I have Django project I need to accept any way user agreement and user term and policy if the user accepts all then go to the user dashboard. other user needs to login then accept. then goes to dashboard. the same need to cookies and session accept don't show to the same user. django front end user login and registration added I have added models with user_checked modal. and templates for agreement term and privacy models class user_check(): agreement1 =models.BooleanField() agreement2 = models.BooleanField() pravacy = models.BooleanField() views from django.shortcuts import render # Create your views here. def aggement1(): return render('agreement1.html') def aggement2(): return render('agreement2.html') def pravacy(): return render('pravacy') when user login first time show an agreement 2 step and user term and policy need to accept. cookies and session notification show to user screen if they accept then don't show I am a Django beginner developer -
Order Filtered Queryset Count in Django
I am trying to create a kind of ranking: there are 'students' and there are transactions of items. And if the item is a beer, it counts towards the beer_list. I wrote this manually but this isn't sorted: beer_list = {} for transaction in Transactions.objects.all(): if transaction.item.beer: if transaction.student.student_ID in beer_list: beer_list[transaction.student.student_ID]['beer_count'] += transaction.item_count else: beer_list[transaction.student.student_ID] = { 'nickname': (transaction.student.nickname if transaction.student.nickname else 'Anon'), 'beer_count': transaction.item_count } I tried sorting it with beer_list = sorted(beer_list.items(), key=lambda x: x[1]) but this throws an error, that this comparison isn't usable with dict to dict usage. Is there a simple solution for this? I am thinking of something like Transactions.objects.filter(item.beer=True) and then using this filtered list to count the objects possibly with an annotation? -
django set boolean field value in views
I need to set all BooleanField values to False with button in my template. model: class VyberJedla(models.Model): nazov_jedla = models.CharField(max_length=100) ingrediencie = models.CharField(max_length=500) vybrane = models.BooleanField(default=False) def __str__(self): return self.nazov_jedla view: def vymazatVybrane(request): jedlo = VyberJedla.objects.all jedlo.vybrane = False jedlo.save() return redirect('/') template(button): <a href="{% url 'vymazatVybrane' %}"> <button type="button"> DELETE COMPLETED </button></a> error: AttributeError at /vymazatVybrane 'method' object has no attribute 'vybrane' -
Django NoReverseMatch error when I try to connect to my URL
I am getting a NoReverseMatch error when I try to connect to my URL, and I am not sure what the problem is. Thank you for any help. Here is my code: cart/models.py from shop.models import Product class Cart(models.Model): cart_id = models.CharField(max_length=250, blank = True) date_added = models.DateField(auto_now_add = True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() class Meta: db_table = 'CartItem' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product cart/views.py It seems as though the error stems from the add_cart method here, saying that there is no reverse for it. from shop.models import Product from .models import Cart, CartItem from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() else: messages.add_message(request, messages.INFO, 'Sorry, no more available!') except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart ) cart_item.save() return … -
Render ajax post to HTML in Django with render_to_string
I am writing an page that with a form of several inputs wrapped in selectize.js on the top. By clicking a button, I wish to return some queries info based on inputs. I am using ajax to post inputs to avoid page reloading. I am following DJANGO render new result values from AJAX request to HTML page to render the queried result cat_result based on ajax post data in HTML. def cat_select(request): cat_result=[] cat_selected=[] cat_name=['l2','l3'] cat_selected=list(map(lambda x:request.POST.get(x, '').split(','), cat_name)) cat_result=c_result(["US"],cat_selected) #list of tuples I want to get print(cat_selected) print(cat_result) html=render_to_string(request, 'result.html', {'cat_result': cat_result}) return JsonResponse({'cat':cat_result,'html':html},safe=False) But I get below error on render_to_string File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\_os.py", line 32, in safe_join final_path = abspath(join(base, *paths)) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\ntpath.py", line 115, in join genericpath._check_arg_types('join', path, *paths) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\genericpath.py", line 149, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'WSGIRequest' There is the function that works with the main base.html which result.html extend from. def search_index(request): ##something to populate input options for l2 and l3 print(results) context = {'l2':l2, 'l3':l3} return render(request, 'esearch/base.html', context) base.html <form id="cat_select">{% csrf_token %} … -
Making a script that changes Django settings
I have a django project with 3 completely different templates, each with its own folder. Would it be possibile to make a python script that changes django's settings (file paths to static files and templates) when executed? Can anyone point me to a tutorial or give me advice on how would I go about achieving this on my own?