Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Persist Logged-out User's Session When User Logs In - Add-to-cart Scenario
I want to allow non-logged-in (anonymous) users to add items to their cart. The flow: Non-logged-in User loads homepage and clicks "products" link On "products" listview page, user clicks product to detail page On detail page, user clicks an Add-to-Cart button A Javascript fetch occurs to a Django view Distilled down "Add to cart" function: def add_to_cart(request): data = json.loads(request.body) request.session.create() if request.session.session_key is None else request.session.session_key cart, created = Cart.objects.get_or_create(session_key=request.session.session_key, user_id=request.user.id) product = get_add_to_cart_product() cart.products.add(product) response = { 'message': 'success', ... } return JsonResponse(response, status=200) add_to_cart just creates a session if none existed, uses session key in cart creation, and adds the product to the cart. User then goes to checkout page At this point, let's just say the session_key is 74hh8kte1hptt984so5fhl5vfzyq4unb User will need to login or create an account. This is where problems begin. Once user logs in, session_key changes to something else. I was using LoginView as seen below... My original urls.py: from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from django.conf.global_settings import LOGOUT_REDIRECT_URL from .views import CustomLoginView app_name = 'accounts' urlpatterns = [ path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', LogoutView.as_view(), {'next_page': LOGOUT_REDIRECT_URL}, name='logout'), ] but request.session.flush() or request.session.cycle_key() essentially wipes out the previous session_key. These two … -
#DJANGO - I need to display two (or more) rows of a table in my view, currently I can only display one of the rows
Hello people I am working with ticket creation and there is a 1-N relationship, (a ticket can have multiple messages) I have a view that creates a ticket, in the creation process a message is added - All right here I have a view that adds a new message to the ticket(s), thus 'activating' the 1-N - All right here I have a ticket detail view view (code below) - Here starts my difficulty def ticket_by_id(request, ticket_id, message_id): mesTicket = MessageTicket.objects.get(pk=message_id) ticket = Ticket.objects.get(pk=ticket_id) return render(request, 'support/ticket_by_id.html', {'ticket': ticket, 'messageticket': mesTicket}) the code view above works when the ticket has only one message, but how can I display the multiple messages in this view? Sorry but it was inevitable to use images here For example in the image below there is my database, highlighting two lines that are linked to ticket 9 database, highlighted in ticket messages 9 Below is an image of my ticket detail view my detail view of the ticket How should I display in the view the two messages (or 3, or 4, anyway... more than one) that are related to the ticket, as I would show in my view (image 2) lines 9 and 12 … -
How to prefetch for individual object? (AttributeError: object has no attribute 'select_related')
How do I prefetch for a single object? I.e. select_related for a ForeignKey for one object: # models.py class Bar(models.Model): title = models.CharField() class Foo(models.Model): bar = models.ForeignKey(Bar) b1 = Bar.objects.create(title="Bar") f1 = Foo.objects.create(bar=b1) Foo.objects.all().first().select_related("bar") # AttributeError: 'Foo' object has no attribute 'select_related' -
How can I change my database from sqlite3 to mysql in Django
I've worked with mysql in my django project but in pycharm the default database is SQLite, i've created a MySQL database but I have a database connection problem (when I run makemigrations and migrate commands, everything runs successfully but the database is still empty!) so I guess if I could Change db.sqlite3 file to db.mysql maybe I can solve my problem settings.py and I don't know if db.sqlite3 file is normal to be like that or that's a problem db.sqlite3 but pressing "Reload in another encoding" may change the content of the file reload in another encoding -
CKEditor, Django and EasyPrint
I have an application that renders PDF files from a CKeditor content. I am having problems when rendering is generate because the text from CKeditor is rendered with the Default Font and Size, but not the style the user saved. I would to know how can I extract the style to applied to the template before rendering -
Can't use swagger in Django 4.0?
After installing Django 4.0 and configuring swagger, 'TypeError: 'set' object is not reversible' occurs. Is it possible that Django 4.0 can't use swagger? -
Django Account Verification Email Template shows HTML Code
I'm trying to test an email template for my Django Account Verification Email. But everytime I send the email instead of seeing the html page rendered properly with bootstrap the Email shows the HTML Code in plaintext, what can I do fix this? acc_verification_email.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="col d-flex justify-content-center w-40 h-100 bg-primary"> <div class="row"> Learning-Electronics </div> <div class="row"> <div class="col"> <div class="row"> Obrigado por te registares! </div> <div class="row"> Verifica o teu endereço de E-mail </div> </div> </div> <div class="row"> <p><h2>Olá {% autoescape off %} {{user.first_name}} {% endautoescape %}</h2></p> <p>Estás quase pronto para começar! Clica no botão abaixo para verificar o teu e-mail e desfrutares da nossa plataforma de aprendizagem</p> </div> <div class="row"> {% autoescape off %} <button type="button" class="btn btn-warning" href="http://{{ domain }}{% url 'account:activate' uidb64=uid token=token %}">VERFICA O EMAIL</button> {% endautoescape %} </div> <div class="row"> <p><h3>Obrigado,</h3></p> <p><h3>Da Equipa Learning-Electronics</h3></p> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> views.py ... (some code) current_site = get_current_site(request) mail_subject = 'Ativação de conta no Learning-Electronics' message = render_to_string('acc_active_email.html', { 'user': account, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(account.pk)), 'token': … -
Django logging errors into seperate files by timestamp
I have set up a Django log successfully with the following code: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, }, } And from this, I'm able to find errors logged in the 'debug.log' file that's define above. However what I'd like to achieve is that any Django error is sent to an individual and timestamped log file. For example, if a ValueError is encountered, it would save it to a file named something like: debug_2022-03-04_1143.log I searched some other answers on this, but most seemed to be talking about timestamping at logged intervals, and I couldn't find a solution to the objective I listed above. Any help is appreciated. -
NamedTemporaryFile triggers SuspiciousFileOperation
In django version 3.2.12, I try to download an image for which I have an URL and store it inside an ImageField. It looks like this: def load_image_from_url(self): image_file = NamedTemporaryFile(delete=True, dir='project/media') with urlopen(self.extra_large_url) as uo: assert uo.status == 200 image_file.write(uo.read()) image_file.flush() image = File(image_file) self.image.save(image.name, image) When I create the NamedTemporaryFile, the path generated is an absolute path. In django.core.files.utils, it get blocked in this condition: if allow_relative_path: # Use PurePosixPath() because this branch is checked only in # FileField.generate_filename() where all file paths are expected to be # Unix style (with forward slashes). path = pathlib.PurePosixPath(name) if path.is_absolute() or '..' in path.parts: raise SuspiciousFileOperation( "Detected path traversal attempt in '%s'" % name ) With a dir argument set for the NamedTemporaryFile, the issue remains even if the folder is a subdirectory of the project. Is there a better solution than doing this: self.image.save(os.path.basename(image.name), image) -
Django serialization
serialization is not getting all values i have this object and and assign a property to it, but in a moment of serialization the value that i assign is not serialized @login_required(login_url='auth:login') def get_instance_provisioning(request): instance_pk = request.GET.get('instance_pk') viewpoints_list = CViewPoint.objects.filter(instance_id=instance_pk) five_mins = timedelta(minutes=5) ten_mins = timedelta(minutes=10) now_time = timezone.now() paginator = Paginator(viewpoints_list, 1) viewpoints = [] page = request.GET.get('page') try: viewpoints = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. viewpoints = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. viewpoints = paginator.page(paginator.num_pages) for viewpoint in viewpoints: # checkedIn info checked_in = PmsCheckin.objects.filter( cviewpoint=viewpoint).order_by('id') viewpoint.is_checkedin = "checked-in-status" if len( checked_in) > 0 else "checked-out-status" data = serialize("json", viewpoints) return JsonResponse(data) -
django use subquery to annotate count of distinct values of foreign key field
I am trying to annotate the quantity of distinct products but I have not been successful as of now. I get error such as: ProgrammingError: subquery must return only one column LINE 1: ..._id", "shop_selectedproduct"."create_date", COUNT((SELECT U0... I have the following models: class ShopItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) store = models.ForeignKey(to=Store, on_delete=models.CASCADE) name = models.CharField(max_length=250) class SelectedProduct(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="products", null=True, blank=True) product = models.ForeignKey(ShopItem, null=True, blank=True, on_delete=models.SET_NULL) class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="orders") status = models.PositiveIntegerField(choices=OrderStatus.choices, default=OrderStatus.CART) number = models.CharField(max_length=36, blank=True, null=True) my attempt to count distinct shopitems such as p1, p2, p3, p4 and p5 where p1 quantity should be 3 because it is selected three times, whereas others may only have a quantity of one since we only selected one of each products. My attempt as of now is this: # order = 1 SelectedProduct.objects.filter(order=order).annotate(quantity=Count(Subquery(ShopItem.objects.filter(id=OuterRef("product"))))) is there anyway I could count how many times a product is selected and annotate that on the selected_product such as: p1.quanity > 3 p2.quanity > 3 p3.quanity > 3 p4.quanity > 1 p5.quanity > 1 I'd appreciate any insights. -
Understanding relationship direction of Model fields in Django
I have used Django for quite awhile but not sure I fully grasp how the relationships should work. this is best described in example so here goes. Let's assume there is a Company which has several Departments and each Department can have several Roles in it. Then, each Role can have several Employees. The questions come about how the fields should be laid out when it comes to accessing the data. Some of the questions that come up may seem obvious and may be better understood as I write them out but bare with me because I am using this to learn. Should it be: Example 1 (redundant): class Company(models.Model): name = charfield departments = m2m(Department) roles = m2m(Role) employees = m2m(Employee) class Department(models.Model): name = charfield roles = m2m(Role) employees = m2m(Employee) class Role(models.Model): name = charfield employees = m2m(Employee) class Employee(models.Model): name = charfield Example 2 (not redundant): class Company(models.Model): name = charfield departments = m2m(Department) class Department(models.Model): name = charfield roles = m2m(Role) class Role(models.Model): name = charfield employees = m2m(Employee) class Employee(models.Model): name = charfield Example 3 (fields look upwards): class Company(models.Model): name = charfield class Department(models.Model): name = charfield company = FK(Company) class Role(models.Model): name … -
Multiple IF statements in Django/Python
I was wondering if someone could help me out here, I'm struggling to group my IF statements together in such a way to achieve my results. I'm pretty new to python/django so any advice would be greatly appreciated. I'm trying to make a 'Like' and a 'Dislike' button for my webpage. I have it all set up and I can have each individual element working but I can't seem to group them. What I'm trying to say is this, this will allow me to 'like' my post: class PostLike(View): def post(self, request, slug, *args, **kwargs): post = get_object_or_404(Post, slug=slug) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) return HttpResponseRedirect(reverse('image_details', args=[slug])) This will allow me to 'dislike' my post: class PostLike(View): def post(self, request, slug, *args, **kwargs): post = get_object_or_404(Post, slug=slug) if post.dislikes.filter(id=request.user.id).exists(): post.dislikes.remove(request.user) else: post.dislikes.add(request.user) return HttpResponseRedirect(reverse('image_details', args=[slug])) As you can see, my code is basically duplicated and they both work well individually, what I'm trying to do is combine them into one function where if I have already 'liked' my page, I can click the 'dislike' button to dislike my page and remove my 'like' Many thanks in advance! -
In django i runned migrations successfully but my database is still empty?
I worked in pycharm professional, I create my database and test it successfully database creation , I create my model in models.py and i runned makemigrations then migrate successfully running makemigrations then migrate and the new python file generated successfully 0001_initial.py but when i oppened my database it was empty! -
Django Rest Framework Analytics
I've been searching the internet for hours and can't find answer so this is my last resort. Do you guys have any idea what's the best way to capture how much a user has sent let's say get request for a specific endpoint? I also want it to be distinguishable by whether the user sent a request on a mobile app or on a website (the same endpoint). I thought about making a model something like: class Visit(models.Model) product = models.ForeignKey('Product') user = models.ForeignKey('User') on_mobile = models.BooleanField(default='False') on_website = models.BooleanField(default='False') times_visit = models.IntegerField(default=0) and shooting if Visit.objects.get(user=self.request.user, product=self.kwargs['pk']).exists(): times_visit += 1 Visit.objects.create(user=self.request.user, product=self.kwargs['pk']) Do you have any idea how "check" whether user sent it through mobile app or website? Or maybe there is some other better way? I would be thankful for any kind of help. -
render media file to html template from views.py django
I am trying to show image from views.py to jinga2 html template. Here is code models.py class SkinModel(models.Model): pic=models.ImageField(upload_to='images',blank=True) forms.py class SkinForm(forms.ModelForm): class Meta: model=SkinModel fields = "__all__" views.py def home(request): if request.method=='POST': form = SkinForm(request.POST,request.FILES) if form.is_valid(): img=form.cleaned_data['pic'] if img: fs = FileSystemStorage() filename = fs.save(img.name, img) path = fs.url(filename) print(path) return render(request,'home.html',{'form':form,'path':path}) home.html {% load static %} <img src="<img src="{{ path }}">" ,width="500" height="400"> the print statement shows the path like /media/bcc_38Mf6gh.jpg but i dont know how to render it on html template -
Session variables don't hold across API calls
This is the API function that's being called, so the request.session['uid'] doesn't hold its value when the react server makes another request to another call that utilizes the same session variable. The django server is hosted on local and then the calls are made using that IP so localhost:8000/postSignIn. def postsignIn(request): email = request.POST.get('email') pasw = request.POST.get('pass') request.session['email'] = email cursor = connection.cursor() cursor.execute("SELECT U.user_id FROM \"User\" U WHERE U.email = '{0}' ".format(str(email))) useridfetch = cursor.fetchone() request.session['uid'] = useridfetch[0] try: user = firebaseauthenticator.sign_in_with_email_and_password(email, pasw) return HttpResponse(request.session['uid']) except: message = "Invalid Credentials" return render(request, "Login/Login.html", {"message": message}) -
Adding unique id to new dynamically created form using django htmx
I am trying to create a dynamic form where the user can create as many questions as they want and at the same time add answers to each questions as many as they want(max number of answer is 4). I am using htmx to add new question and answer. I am able to add more questions when clicking the 'Add Question' button and more answers when clicking the 'Add Answer' button. However, when i tried to add more answers on Question 2 or 3, it will add a new answer form in Question 1 only. I want the answer to be added to their respective questions. Do help me with this issue. add_quiz_questions.html {% load crispy_forms_tags %} <div class="container-fluid"> <!-- Main Content Here --> <form method="POST" enctype="multipart/form-data"> <div class="card shadow mb-4"> <!-- <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary ">Post Your Announcements</h6> </div> --> <div class="card-body"> {% csrf_token %} {{ questionform.question|as_crispy_field}} <div> {{ answerform.answer|as_crispy_field}} {{ answerform.correct_answer|as_crispy_field}} <div id="addanswer"></div> </div> <button hx-get="{% url 'add_quiz_answer' %}" hx-swap="beforeend" hx-target="#addanswer" class="btn btn-info">Add Answer</button> <button type="submit" class="btn btn-primary">Save</button> </div> <div id="addquestion"></div> </div> <button hx-get="{% url 'add_quiz_question' %}" hx-swap="beforeend" style="margin-bottom:30px" hx-target="#addquestion" class="btn btn-info"> Add Question</button> </form> </div> create_question.html {% load crispy_forms_tags %} {% csrf_token %} <div … -
Unable to connect to Postgres DB living in one docker-compose file with django app in separate docker-compose file
I have a large monorepo Django app that I want to break into two separate repositories (1 to handle external api requests and the other to handle my front end that I plan on showing to users). I would still like to have both django apps have access to the same db when running things locally. Is there a way for me to do this? I'm running docker for both and am having issues with my front end facing django app being able to connect to the Postgres DB i have set up in a separate docker-compose file than the one I made for my front end app. External API docker-compose file (Postgres DB docker image gets created here when running docker-compose up --build) --- version: "3.9" services: db: image: postgres:13.4 ports: - "5432:5432" environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres api: restart: always build: . image: &img img-one command: bash start.sh volumes: - .:/app ports: - "8000:8000" depends_on: - db env_file: - variables.env Front end facing docker-compose file (This is the one I want to be able to connect to the DB above): --- version: "3.9" services: dashboard: restart: always build: . image: &img img-two volumes: - .:/code ports: … -
Getting the latest entries for every group
I am trying to build a simple storage example in django 4.0 where stuff is inserted to a storage table defined like this: class material_storage(models.Model): storage_id = models.AutoField(primary_key=True) material = models.ForeignKey(itemtype, on_delete=models.PROTECT) amount = models.IntegerField(null=True) price = models.FloatField(null=True) timestamp = models.DateTimeField(default=timezone.now) To retrieve the latest entry for every material within this table I need something looking like this in SQL: SELECT material_id, amount, price, MAX(timestamp) FROM assetmanager_material_storage GROUP BY material_id Since I'm new to Django, I haven't managed to recreate this query yet. I found some threads suggesting solutions like: material_storage.objects.values('material').annotate(latest_record=Max('timestamp')) but that's not working in my case, instead throwing an error "name 'Max' not defined". The other approach would be to go like this: material_storage.objects.all().latest('timestamp') but this would only return the latest object in the whole table and I couldn't figure out for now how to apply "latest" on every material instead of all records. So I am kinda stuck now. If somebody could tell me what I'm missing, I would be grateful. thx in advance. -
autobahn.exception.Disconnected: Attempt to send on a closed protocol
I have a web server uploaded on a server that receives messages from a Windows app and sends them to a front end in the browser Its late there is a slight delay in receiving and sending and when I checked the django logs I get this message from time to time 2022-03-03 21:04:54,257 ERROR Exception inside application: Attempt to send on a closed protocol Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/usr/local/lib/python3.8/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/usr/local/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/app/backend/server/./script/consumers.py", line 242, in chat_message await self.send(text_data=json.dumps({ File "/usr/local/lib/python3.8/site-packages/channels/generic/websocket.py", line 209, in send await super().send({"type": "websocket.send", "text": text_data}) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 81, in send await self.base_send(message) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line … -
Book.objects.all() doesnt return anything although books exist in the database Django
I have a books page that shows all books in the database but it doesn't show any books although books do exist in the database and on the admin page and I don't know why. the model for the book is: book_status = [ ('Available', 'Available'), ('Borrowed', 'Borrowed'), ] id = AutoField(primary_key=True) title = models.CharField(max_length=250) author = models.CharField(max_length=250, null=True, blank=True) borrowing_period = models.IntegerField(null=True, blank=True) publication_year = models.IntegerField(null=True, blank=True) isbn = models.IntegerField(null=True, blank=True) status = models.CharField(max_length=50, choices=book_status, null=True, blank=True) slug = models.SlugField(_("slug"), null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Book, self).save(*args, **kwargs) the views function: def books(request): searchf = Book.objects.all() if request.method == 'POST': cat = request.POST['category'] if cat == 'ISBN': isbn = None if 'search' in request.POST: isbn = request.POST['search'] if isbn: searchf = searchf.filter(isbn__icontains=isbn) elif cat == 'Title': title = None if 'search' in request.POST: title = request.POST['search'] if title: searchf = searchf.filter(title__icontains=title) elif cat == 'Author': author = None if 'search' in request.POST: author = request.POST['search'] if author: searchf = searchf.filter(author__icontains=author) elif cat == 'Year': Year = None if 'search' in request.POST: Year = request.POST['search'] if Year: searchf = searchf.filter(publication_year__icontains=Year) return render(request, 'books.html', { 'books': searchf, 'category': Category.objects.all() }) … -
Passing Json from Django view to template Javascript
I'm trying to pass a json response from a view to javascript. For some reason I can't access any keys inside javascript. I can only access the whole json object, but none of the nested keys attached to it. Json(simplified for the purpose of reading): { "protected": [ { "category": "nmtd", "name": "NMTD", "userId": 257 } ] } views.py: def index(request): request_pr = requests.get('https://endpoint-address', cookies = request.COOKIES) pr_colors = json.dumps(request_pr.json()) context = { 'pr_colors': pr_colors } return render(request, 'index.html', context) Javascript: <script type="text/javascript"> var received_data = "{{ pr_colors }}" console.log(received_data) </script> There are two different kinds of problems. If I set JSON.parse("{{ praga_colors }}") I get Uncaught SyntaxError: Unexpected token & in JSON at position 1 If I just try to access the element directly without JSON.parse() I get all the values as undefined. If I try to access by position praga_colors[1], I get a letter by letter string. What is the proper way to handle this? -
Wagtail page promote tab - "Show in Menu" - How does it work?
The default Wagtail page model includes the "Show in Menu" option on the promote tab. I've been searching through the documentation for awhile now trying to find more information about how this works and I don't see anything. What is this option used for, and how do I hook into that field so that I can build a simple list of links to be used is some arbitrary template like a footer? Am I supposed to just build my own queryset of admin models and then filter on that value, or is there a simpler utility include with Wagtail that I can use directly? -
Cascading Multiselect Option List using Javascript
I have found a code online that satisfies my need of cascading option list. But I also need to make multiple selections. When I add multiple to select tag it allows me to make multiple selections however it shows as if only 1 option was choosed. Here is the code I am using: Javascript: var root_1_Object = {{ url_categories|safe }} window.onload = function() { var root_1_Sel = document.getElementById("root_1"); var root_2_Sel = document.getElementById("root_2"); var root_3_Sel = document.getElementById("root_3"); for (var x in root_1_Object) { root_1_Sel.options[root_1_Sel.options.length] = new Option(x, x); } root_1_Sel.onchange = function() { //empty root_3_S- and root_2_S- dropdowns root_3_Sel.length = 1; root_2_Sel.length = 1; //display correct values for (var y in root_1_Object[this.value]) { root_2_Sel.options[root_2_Sel.options.length] = new Option(y, y); } } root_2_Sel.onchange = function() { //empty root_3_S dropdown root_3_Sel.length = 1; //display correct values var z = root_1_Object[root_1_Sel.value][this.value]; for (var i = 0; i < z.length; i++) { root_3_Sel.options[root_3_Sel.options.length] = new Option(z[i], z[i]); } console.log(root_3_Sel); } } Html: <select name="root_1" id="root_1" multiple required/> <option value="" selected="selected"></option> </select> <br><br> <select name="root_2" id="root_2" multiple required/> <option value="" selected="selected"></option> </select> <br><br> <select name="root_3" id="root_3" multiple required/> <option value="" selected="selected"></option> </select> <br><br>