Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Posts list page, Django Wagtail
I am making a news site, there is a page where all articles are displayed. But if there are many articles, then the page will be huge. my code : {% block content %} <div class=" container" style="margin-top: 60px;"> {% for post in posts %} <div class="row" style="padding-top: 30px "> <div class="col-sm-3"> {% image post.preview_image fill-250x250 as blog_img %} <img style="border-radius: .3525rem" href="{{ post.url }}" src="{{ blog_img.url }}"> </div> <div class="col-sm-9"> <a href="{{ post.url }}"> {{ post.title }} </a> <br/> <p> {{ post.intro }}</p> </div> </div> {% endfor %} </div> {% endblock content %} what i want to do -
Heroku Push Failing Module dj_database_url Not Found
I am trying to push my simple Django app onto Heroku (using Windows) and I am running into an error related to dj_database_url. It says that the module is not found, but I do have everything installed and confirmed through pip. Any ideas why this isnt working? requirements.txt Django>=2.2.13,<3.0 dj-database-url==0.5.0 gunicorn>=20.0.4 whitenoise>=5.1.0 error: -----> Python app detected -----> Installing python-3.6.12 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting Django<3.0,>=2.2.13 Downloading Django-2.2.17-py3-none-any.whl (7.5 MB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting pytz Downloading pytz-2020.5-py2.py3-none-any.whl (510 kB) Installing collected packages: sqlparse, pytz, Django Successfully installed Django-2.2.17 pytz-2020.5 sqlparse-0.4.1 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 211, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in … -
Django Crontab not writing csv file
I am trying to run some jobs in django-crontab. They have been added successfully. Here is the code snippet. CRONJOBS = [ ('0 0 * * *', 'landingpage.my_crons.get_users','>> /home/root_user/scheduled_job.log'), ('0 0 * * *', 'landingpage.my_crons.data_collector'), ] crons appear when i do crontab show 8e70613793052f5793f86106c92994fe -> ('0 0 * * *', 'landingpage.my_crons.get_users', '>> /home/root_user/scheduled_job.log') d72fb010328cdc02e4b984fdc5f7db05 -> ('0 0 * * *', 'landingpage.my_crons.data_collector') when I run these using hashes they run fine and write files fine but when they run as scheduled they don't write files Even though it is empty but log file is being generated which means jobs are running but they are unable to write files that are being generated by script. Files are csv files based on bigquery data -
Django Heroku Commit Failure at Requirements
I am receiving the following error when I try and deploy my new app to Heroku. It looks like it's failing when it tries to install all of my requirements.txt line items, specifically at PyAudio which I am not using in my app at all. My requirements file was generated using pip freeze > requirements.txt which has 155 line items (seems way high for my simple app). Is this what's causing the issue? -----> Python app detected -----> Installing python-3.6.12 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. ! Push rejected, failed to compile Python app. ! Push failed -
How to pass arguments to QueryDicts and consecutively pass it to a django form to be used inside it
Description: I'm playing with django forms to fill in Completed_Exercise Model instances for those users that have completed successfully a determined exercise by use of ModelForm class, but since a Completed_ExerciseForm has three fields, two of which correspond to ForeignKey fields, i dont need to render them on template but the score one (hilariously user can do self-qualification), so the thing is i decided to pass both of them as arguments to ModelForm instance through a request.GET copy. I googled for an hour and tried & corrected stuff... but even so im making the same mistake, as far as i know this can be done likewise by passing them as kwargs to the form, but its not the intended way. Any help is really appreciated. Result: I cant access to QueryDict from inside of the form Models: class Completed_Exercise(models.Model): possible_scores = list(zip(range(1,8), range(1,8))) exercise = models.OneToOneField(Exercise, default=None, on_delete=models.CASCADE) points = models.IntegerField(default=0, choices=possible_scores) student = models.ForeignKey('accounts.Student', on_delete = models.CASCADE, related_name='completed_exercises') def __str__(self): return self.name #Student belongs to other django app, despite its placed alongside the first one. class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="student") pui = models.CharField(max_length=20, blank=True, default='') grade = models.CharField(max_length=1, blank=True, default='') score = models.IntegerField(default=0) reputation = models.IntegerField(default=0) … -
Trouble using letsencrypt with Django, Heroku, and Google Domains
I'm having trouble setting up my custom domain. I'm learning all this for the first time so there's a lot of confusion right now. Right now I can load my site at the custom domain, but none of the forms work. I think that's because it's HTTP right now, so I'm trying to get SSL. I'm using Heroku's free tier at the moment, so I can't use Heroku's SSL. I'm trying to get SSL using letsencrypt and I get this error running "certbot certonly --standalone": Detail: Invalid response from http://www.example.com/.well-known/acme-challenge/PIA0KiB2f7I5qVssgGY_3dbMuOgdlu0URheGUqbal0Y [34.196.106.64]: My settings.py DEBUG = False SECURE_SSL_REDIRECT = False if DEBUG: SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False else: SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Finally, I'm not sure if I set up DNS correctly, so here's what I have right now: A synthetic record with subdomain @.example.com -> www.example.com, Temporary redirect, Do not forward path, Disable SSL A custom resource record with Name: www, Type: CNAME, TTL: 1hr, Data: DNS Target from heroku -
django , Not Found The requested resource was not found on this server
I'm using django 3.1.4 keep having problem "Not Found The requested resource was not found on this server" when try to open the orders details in orders.html I'm use <td><a href="{{ order.get_absolute_url }}" class="btn btn-primary d-inline">Details</a></td> in the urls.py using from django.urls import path from . import views from .models import OrderStatus path('market/orders/', views.VendorOrders.as_view(), name='market_orders'), path('orders/<int:pk>/', views.OrderDetail.as_view(), name='order_detail'), -
Django DetailView + Delete Item from Ajax Form
So here is my issue. The user can create a Client using a form. Once created, the created client appears in a DetaiLView In this DetailView, I put a form to add specific events related to the client, thanks to an ajaxified form so that new events appear without refreshing the page. So far everything is okay. Now I would like to allow the user to delete one event if he wants to. So I have done the HTML/AJAX parts. However, since it is a DetaiLView, I am having troubles to delete a specific event. Here is my Views.py : class CollectionDetail(LoginRequiredMixin, FormMixin, DetailView): model = Collection form_class = ImportantFactsForm template_name = 'taskflow/collection_detail.html' success_url = None def get_context_data(self, **kwargs): context = super(CollectionDetail, self).get_context_data(**kwargs) context['important_facts'] = ImportantFactsForm() return context def post(self, request, *args, **kwargs): form = ImportantFactsForm(request.POST) tgt = self.get_object() if form.is_valid(): new_fact = form.save(commit=False) new_fact.collection_important_facts = tgt new_fact.save() return JsonResponse({'new_fact': model_to_dict(new_fact)}, status=200) else: return redirect('taskflow:collection_all') #here I need to implement the delete function. Here is my collection_detail.html <div class="card-body"> <div class="tab-content"> <div class="tab-pane active" id="Canal1"> <form class="justify-content-center mx-3" id="createFactForm" method="post" data-url="{% url 'taskflow:collection_detail' pk=object.pk %}"> {% csrf_token %} <div class="form-group"> {{important_facts.doc_ref|as_crispy_field}} </div> <div class="form-group"> {{important_facts.note|as_crispy_field}} </div> <button type="submit" class="btn btn-outline-success" … -
How to modify computed queryset values ? (Reversed many - to - one relationship)
class Style(Model): id .... name .... class Song(Model): ... style = ForgeignKey(Style, related_name="songs") queryset = Style.objects.all() queryset[0].songs = queryset[0].songs.filter(something=1) #or queryset[0].songs.set(queryset[0].songs.filter(something=1)) This is my actual code, but it does not work except for filtering... I would like to assigned queryset.songs new filtered songs... or is there another way how to efficiently filter in this case ? -
Hi everyone! Where in pycharm do i need to paste this code.... {"python.linting.pylintArgs": [ "--load-plugins=pylint_django" ],}
** I know that in VS it's muck easy but i'm new to coding and i like pycharm. Please help! ** File "/Users/alexe/PycharmProjects/pythonProject1/btre_project/listings/views.py", line 3, in <module> from .models import listing ImportError: attempted relative import with no known parent package ``` -
Django: Select a valid choice. That choice is not one of the available choices
I have a nested choice field: The top one is used to select a smartphone brand and the bottom one is used to select a smartphone model of the said brand. The problem I face is such that when restricting the bottom choice using AJAX, my form is invalid. However, the POST request with and without restriction are exactly the same: No restriction: {'name': 'Ok iPhone 12 Mini', 'price': Decimal('345'), 'color': <Color: Red>, 'condition': <Condition: Refurbished by manufacturer>, 'storage': <StorageChoice: 128>, 'phone_model': <PhoneModel: iPhone 12 Mini>, 'description': '...', 'image': <InMemoryUploadedFile: pic.jpg (image/jpeg)>} With restriction: {'name': 'Ok iPhone 12 Mini', 'price': Decimal('345'), 'color': <Color: Red>, 'condition': <Condition: Refurbished by manufacturer>, 'storage': <StorageChoice: 128>, 'description': '...', 'image': <InMemoryUploadedFile: pic.jpg (image/jpeg)>, 'phone_model': <PhoneModel: iPhone 12 Mini>} The only difference I can see is order, which should not matter in the case of a dictionary. views.py: def product_add(request): form = AddProductForm() if request.method == "POST": form = AddProductForm(request.POST, request.FILES) form.is_valid() form.cleaned_data['phone_model'] = PhoneModel.objects.get(id=request.POST['phone_model']) form.cleaned_data.pop('make', None) print(form.cleaned_data) if form.is_valid(): form.cleaned_data['seller'] = request.user.customer Product.objects.create(**form.cleaned_data) else: print(form.errors) cart = get_cart(request) context = {'form': form, **cart} return render(request, 'store/product_add.html', context) def load_models(request): make_id = request.GET.get('make') models = PhoneModel.objects.filter(phone_make=make_id) return render(request, 'part/product_add_model_options.html', {'models': models}) forms.py: class AddProductForm(forms.ModelForm): class Meta: … -
Removing username from UserCreationForm and auto generating username for user based on email, first name and last name
I am trying to auto generate username for users as they sign up, however, I do not know where to set the username. I do not want to user signals, so therefore I want to set the username for users when the user signs up. In my UserCreationForm I have remove the username by: users = None and inside the SingUpForm(UserCreationForm) method I have: class SignUpForm(UserCreationForm): class Meta: fields = ( "first_name", "last_name", "email", ) However, I do not know how to set the username for the user, should I set the username for user inside the signup view? user = form.save(commit=False) user.username = generate_username(user.first_name, user.last_name, user.email) user.save() Or should I have the generate_username() method inside my custom creation form? -
How to know which users have seen certain post
I'm developing a Django web app in which I need to know which users have seen certain posts, I'd like to do this by adding a 'seen_by' field in the Post model, but I really don't know if it's possible to do it that way. The only way I can think of doing this is by making a function in which if an user visits an object, somehow send information to this object that the user visited it. Obviously I'm relatively new to programming in Django, I don't know if this can be done through signals or how, but I'd very much appreciate any help or advice specifically for this issue! -
How do I start my server in debug mode for my VS Code Django application?
I'm using Visual studio Code 1.52.1. I want to debug a Django application. I created this launch.json file ... launch.json { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/usr/src/app" } ], "port": 3500, "host": "127.0.0.1", } ] } and added the sections between "start new section" and "end new section" to my manage.py file ... #!/usr/bin/env python import os import sys if __name__ == '__main__': # start new section from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import ptvsd ptvsd.enable_attach(address=('0.0.0.0', 3500)) print('Attached!') # end new section if 'test' in sys.argv: print("test activated!") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "article_project.settings.test") elif os.environ['DJANGO_DEVELOPMENT'] == 'true': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "article_project.settings.dev") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "article_project.settings.prod") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) However, when I start up my server, I get an error. $ python manage.py runserver Traceback (most recent call last): File "manage.py", line 9, in <module> if settings.DEBUG: File "/Users/davea/Documents/workspace/article_project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Users/davea/Documents/workspace/article_project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: … -
Django circular import error, trying to allow location to access activity
ImportError: cannot import name 'Activity' from partially initialized module 'vacaplusapi.models.activity' (most likely due to a circular import) (/Users/name/project/server/projectname/models/activity.py) models/activity.py from django.db import models from .activity import Activity class Activity(models.Model): activity = models.OneToOneField(Activity, on_delete=models.CASCADE) description = models.CharField(max_length=255,) date = models.DateField(default="0000-00-00",) photo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) models/location.py from vacaplusapi.models import Activity from vacaplusapi.models.vacauser import VacaUser from django.db import models from .vacauser import VacaUser class Location(models.Model): time = models.DateField(models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)) activity = models.ForeignKey(Activity, on_delete=models.DO_NOTHING, related_name="activity") user = models.ForeignKey(VacaUser, on_delete=models.DO_NOTHING, related_name="vacauser") title = models.CharField(max_length=50) description = models.TextField(max_length=200) photo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) -
Best model for storing list of dates | Django
I'd like to store the different launch dates for my Django object for multiple regions, e.g. object 1: US: July 29, 2014 Asia: July 30, 2014 UK: August 1, 2014 I'm not sure what is the best model to use. Is it better to create a different DateField field for each region, or is there a better way to group them all together in a JSON object, or other type? I'll be displaying them together on a page. I'm expecting to run queries to show, for example, all releases in a region, or to display the first release date for that object. Thanks -
Heroku Django cant find template
Despite that I have 'DIRS': [os.path.join(BASE_DIR, 'templates')], in my settings, still Heroku cant find the template. By the way Heroku finds some templates, but it seems that he cant finds those on CBV's. Any idea what might me be problem? Thank you in advance. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [BASE_DIR / 'templates'], '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', ], }, }, ] -
Loop through JSON from django model in template
I don't know how to loop thorugh JSON object with javascripit in template (I know how to do it in HTML part but i need it to be in javascript). I figure out that if I safe my JSON object in variable like this: <script> let schedule = "{{ barber.schedule.schedule_day | safe}}" </script> it's saved as string type and I can't work with it, schedule[0] shows first character which is [ I can't JSON.parse it either because error appears "Unexpected token ' in JSON at position 2" i guess it's because my schedule has single quotes insted of dubble ones this is how it my schedule looks when I console.log it [{'start': 8, 'end': 10}, {'start': 12, 'end': 14}, {'start': 15, 'end': 16}] this is how JSON from models looks like { "schedule_day": [ { "start": 8, "end": 10 }, { "start": 12, "end": 14 }, { "start": 15, "end": 16 } ] } views.py class Barber_schedule(DetailView): model = Barber context_object_name = 'barber' models.py schedule_template = ''' { "schedule_day": [ { "start": 8, "end": 16 } ] } ''' class Barber(models.Model): name = models.CharField(max_length=30) start_time = models.IntegerField(default=8, validators=[MaxValueValidator(16), MinValueValidator(0)]) JSON_schedule_template = json.loads(schedule_template) schedule = models.JSONField(default=JSON_schedule_template) photo = models.ImageField(upload_to='barber_avatar', default='default.png') def … -
How to get ajax data in django views?
Here I simply want to get data from ajax call in my django views. I am using type GET ajax call for my purpose. I dont know how to get data from that into my django views.I am newbie please tell me how can i fix all that. <span class="test">yes</span> ajax call <script> /* On focus out on input nickname, call AJAX get request to check if the nickName already exists or not. */ $(".test").focusout(function (e) { e.preventDefault(); // get the nickname var text = $(this).text(); // GET AJAX request console.log('test hoon') console.log(text) $.ajax({ type: 'GET', url: "{% url 'dashboard' %}", data: {"text": text}, success: function (response) { // if not valid user, alert the user }, error: function (response) { console.log(response) } }) }) </script> Views.py class Dashboard(TemplateView): template_name = "dashboard.html" def get(self,*args, **kwargs): amount = self.request.GET.get('text') print("I m here !",amount) return render(amount,'dashboard.html',) -
How to read images uploaded via post request using opencv
I have an opencv script on document scanner and I want to create a post request that returns the scanned image as a response. I get the below error when I tried to read the image(using opencv) via post request. What are the possible way I can get around this. I have tried the various method but is not working for me. Modey.py class ImageScanner(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) ImageFile = models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.ImageFile) def save(self, *args, **kwargs): super(ImageScanner, self).save(*args, **kwargs) Img = Scanner(self.ImageFile) Opencv script def Scanner(image): # now = timezone.now() # load the image and compute the ratio of the old height # to the new height, clone it, and resize it image = cv2.imread(image) ratio = image.shape[0] / 500.0 orig = image.copy() image = imutils.resize(image, height = 500) # convert the image to grayscale, blur it, and find edges # in the image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 75, 200) # show the original image and the edge detected image print ("STEP 1: Edge Detection") cv2.imshow("Image", image) cv2.imshow("Edged", edged) seriliazer.py from rest_framework import serializers from .models import ImageScanner from django.contrib.auth.models import … -
Case 1: Convert following UnitTest Code into PyTest:
How to convert following unitest code into a pytest code class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test creating a new user with an email is successful""" email = "test@londonappdev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Normalize Email""" email = "teast@AIOWoev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): """Creating user with no email fails""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, "test123") I have written following tests into a pytest but has issue with test_new_user_invalid_email, how to correct it: def test_create_user_with_email_successful(client) -> None: email = "test@londonappdev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) assert user.email == email assert user.check_password(password) def test_new_user_email_normalized(self): """Normalize Email""" email = "teast@AIOWoev.com" password = "Password123" user = get_user_model().objects.create_user(email=email, password=password) assert user.email == email.lower() def test_new_user_invalid_email(self): """Creating user with no email fails""" with pytest.raises(ValueError) as e: get_user_model().objects.create_user(None, "test123") -
Django redirecting after clicking Like button
I'm doing Like/Unlike system in my project. After clicking Like button should just redirect on the same page but updated with +1 like but it is not. Have looked on youtube videos with this system and thay got it worked but I can't figure it out what is the problem with my code. views.py def like_view(request, pk): cocktail = get_object_or_404(AddCocktails, id=request.POST.get('cocktail_id')) liked = False if cocktail.likes.filter(id=request.user.id).exists(): cocktail.likes.remove(request.user) liked = False else: cocktail.likesadd(request.user) liked = True return HttpResponseRedirect(reverse('cocktails:cocktail-details', args=[str(pk)])) class CocktailDetails(LoginRequiredMixin, DetailView): model = AddCocktails template_name = 'cocktails/cocktail-details.html' def get_context_data(self, *args, **kwargs): cocktail_data = AddCocktails.objects.filter(id=self.kwargs['pk']) context = super().get_context_data(**kwargs) stuff = get_object_or_404(AddCocktails, id=self.kwargs['pk']) total_likes = stuff.total_likes liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context['cocktail_data'] = cocktail_data context['total_likes'] = total_likes context['liked'] = liked return context urls.py path('cocktail-details/<int:pk>/', CocktailDetails.as_view(), name='cocktail-details'), path('likes/<int:pk>/', like_view, name='likes'), template {% for cocktail in cocktail_data %} <h4>Cocktail Name</h4> {{ cocktail.cocktail_name }} <h4>Cocktail Category</h4> {{ cocktail.cocktails_category }} <h4>Type of Glass</h4> {{ cocktail.crockery_category }} <h4>Method Category</h4> {{ cocktail.method_category }} <h4>Ingredients</h4> {{ cocktail.ingredients }} <h4>Execution</h4> {{ cocktail.execution }} <img src="{{ cocktail.image.url }}" width="350" height="350"> <form action="{% url 'cocktails:likes' cocktail.pk %}" method=POST> {% csrf_token %} {% if liked %} <button type="submit" name="cocktail.id" value="{{ cocktail.id }}" class="btn unlike">Unlike </button> {% else %} <button type="submit" … -
Django Get Root Path From Current URL
I am developing a Django website using the Wagtail CMS. I have a navbar at the top of the page where using template tags, it loops through pages in the navigation variable. {% for item in navigation.menu_items.all %} <a class="nav-link {% if request.get_full_path == item.link %}active{% endif %}" href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank"{% endif %}>{{ item.title }}</a> {% endfor %} Say that the URL is http://localhost:8000/blog/ and the page URL is the same, then the active class is applied to that iteration. The problem arises when I am on a page with the URL such as http://localhost:8000/blog/example-blog-post/, this does not match with http://localhost:8000/blog/ and the active class is not applied, even though I am in the blog. Is there a way to strip the URL and only keeping the root path, so http://localhost:8000/blog/example-blog-post/ becomes http://localhost:8000/blog/ so that the active class can be applied to subpages in the directory? -
How to access user infos from consumer.py django?
I am building a social media app with react.js and django, django-rest-framework, djoser, django-channels==3.0.2.. well the problem is i want to make an notification system on friend request and on like of post and comment. The problem is I want to have some kind of security that when I send a request through the websocket from react, I want to check if the sender is the authenticated user,by sending the user id on the websockets, and comparing it to the logged in user's id.Since I can't get the self.scope['user'] because i'm using Djoser for authentication, is there any other way to achieve this ? -
bootstrap table: filter control not working
With my bootstrap table I want to use the extension Filter Control Server side I'm using django. I include following css and js: {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/bootstrap-table.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/extensions/filter-control/bootstrap-table-filter-control.min.css"> <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/bootstrap-table.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.1/extensions/filter-control/bootstrap-table-filter-control.min.js" ></script> And here my html table: <table id="table" data-toggle="table" data-pagination="true" data-pagination-h-align="left" data-pagination-detail-h-align="right" data-page-size="25" data-page-list="[10, 25, 50, 100, all]" data-search="true" data-show-columns="true" data-filter-control="true" data-show-search-clear-button="true" data-show-refresh="true" data-url="../get_track_list"> <thead> <tr> <th data-field="datetime_start" data-formatter="DateFormatter" data-sortable="true" data-switchable="false" data-searchable="false">Date</th> <th data-field="name" data-formatter="ActivityLinkFormatter" data-switchable="false">Name</th> <th data-field="sport" data-formatter="SportSymbolFormatter" data-sortable="true" data-searchable="false" data-filter-control="select">Sport</th> </tr> </thead> </table> My data-url is a json file from a django request. The resulting table looks like this: I don't have any errors in the browser console. I also see the the filter-control div was created but not the dropdown field? What I'm doing wrong, so that the data-filter-control="select" field is not created? The table is rendered without using any js functions, in my js file are just the custom data-formatter