Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
__init__.py issue in django test
I have an issue with running a test in my Django project, using the command python manage.py test. It shows: user:~/workspace/connector$ docker-compose run --rm app sh -c "python manage.py test" Creating connector_app_run ... done Found 0 test(s). System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK I was debugging it and I know that it's probably a "init.py" file. If I'm deleting file init.py from app.app (I have read somewhere that it can help) then I'm receiving an error: ====================================================================== ERROR: app.tests.test_secrets (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: app.tests.test_secrets Traceback (most recent call last): File "/usr/local/lib/python3.9/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/usr/local/lib/python3.9/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/app/app/tests/test_secrets.py", line 12, in <module> from app.app import secrets ModuleNotFoundError: No module named 'app.app' why did this error occur? Pycharm projects normally see import and what I know from version 3.4 it's not obligatory to put init.py into folders to make the package. This is the github link: https://github.com/MrHarvvey/connector.git Can you explain me what I'm I doing wrong here? -
how to add a profile object by using objects.create method
simply my error is this Exception has occurred: TypeError User() got an unexpected keyword argument 'User' here is the data I receive from the post request in view.py if request.method == "POST": student_surname = request.POST.get('student_surname') student_initials = request.POST.get('student_initials') student_birthday = request.POST.get('student_birthday') student_username = request.POST.get('student_username') student_email = request.POST.get('student_email') student_entrance = request.POST.get('student_entrance') student_contact = request.POST.get('student_contact') student_residence = request.POST.get('student_residence') student_father = request.POST.get('student_father') student_other_skills = request.POST.get('student_skills') student_sports = request.POST.get('student_sports') student_password = request.POST.get('student_password') I can create user object it's working in view.py user = User.objects.create_user( username=student_username, email=student_email, password=student_password ) some data is related to profile in view.py student_profile = User.objects.create( User=user, #Error line surname=student_surname, initials=student_initials, entrance_number=student_entrance, email=student_email, father=student_father, skills=student_other_skills, sports=student_sports, birthday=student_birthday, contact=student_contact, address=student_residence, ) student_profile.save() profile definition in models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) surname = models.CharField(max_length=50) initials = models.CharField(max_length=10, blank=True) entrance_number = models.CharField(max_length=10, blank=True) email = models.EmailField(max_length=254, blank=True) father = models.CharField(max_length=50, blank=True) skills = models.CharField(max_length=50, blank=True) sports = models.CharField(max_length=50, blank=True) birthday = models.DateField(null=True, blank=True) contact = models.CharField(max_length=100, null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True) # other fields here def __str__(self): return self.user.username I believe the error is in User = user line can somebody tell me how to initialize this profile object correctly AND save record in the database at the time of … -
Django Rest Framework ignores default value
Any idea why does Django Rest Framework ignore default values? class MyClass(models.Model): some_field = models.CharField(default='Yes') class MyClassSerializer(serializers.ModelSerializer): class Meta: model = MyCLass fields = ['some_field'] class MyClassListCreateAPIView(ListCreateAPIView): queryset = MyClass.objects.all() serializer_class = MyClassSerializer When I send {'some_field': None} /null/something like this. I always get: Bad Request: /myurl/ [02/Dec/2022 16:44:59] "POST /myurl/ HTTP/1.1" 400 114 When changed to: class MyClass(models.Model): some_field = models.CharField(default='Yes', blank=True, null=True) it works but always sets the NULL value. Is this expected behaviour? Should I change the mechanics of my POST request to include changing value to default when user doesn't provide one? -
django_quill modelform QuillField does not render in form
I cannot seem to get QuillField to render in my form. Every other field renders just fine. I cannot find what I am missing here. I have gone over django_quill_editor oficial docs and scoured google. I am at a loss. Here are the files. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'blog', 'django_quill', forms.py from .models import UserPost class UserPostForm(forms.ModelForm): class Meta: model = UserPost fields = ('title', 'image', 'content') models.py from django_quill.fields import QuillField class UserPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) image = models.ImageField(upload_to='images/', blank=True, null=True) categories = models.ManyToManyField('Category', related_name='userposts') content = QuillField() date_published = models.DateField(auto_now_add=True) url = models.SlugField(max_length=500, unique=True, blank=True, editable=False) def save(self, *args, **kwargs): self.url = slugify(self.title) super(UserPost, self).save(*args, **kwargs) views.py from .forms import UserPostForm def userposts_create_view(request): form = UserPostForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect("landingpage:home") context= {'form': form,} return render(request, 'userpost_create.html', context) -
Django, looping through openweather icons always displays the last icon instead of appended city icon
I am trying to build out a weather app using openweather api and what I want to do is replace the icon png's with my own customized icon set. In order to do this, I have referenced the openweather api png codes as seen here: https://openweathermap.org/weather-conditions. I have written some code that states if this code equals '01d' then replace the icon code with my custom data image src. The issue is when looping through (after I have added a city), I am always appending the last image which in this case is the data code for '50n' rather than the correct weather code for that city. here is the code in my views.py: def weather(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=<MYAPPKEY>' cities = City.objects.all() weather_data = [] for city in cities: city_weather = requests.get(url.format(city)).json() weather = { 'city' : city, 'temperature' : city_weather['main']['temp'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'], } icon = weather['icon'] if icon == '01d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/01d.svg' elif icon == '01n': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/01n.svg' elif icon == '02d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/02d.svg' elif icon == '02n': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/02n.svg' elif icon == '03d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/03d.svg' elif icon == '03n': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/03n.svg' elif icon == '04d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/04d.svg' … -
JSON API not displaying all values on my HTML
Good day all, I am a newbie programmer, I am working on a website using Django where I use a JSON API I generated online to print the prices of cryptocurrencies. I am having a challenge as my API is not displaying all the values I want it to display on my html. please note that I've checked with console to ensure the API is working correctly and I confirmed it does but the challenge is I cannot seem to understand why I cannot print it out on my HTML. Below is my code that I am using to print the prices. The prices that is showing on my HTML is from Bitcoin to Uniswap while the remaining is not showing. My JAVASCRIPT CODE var btc = document.getElementById("bitcoin"); var eth = document.getElementById("ethereum"); var doge = document.getElementById("dogecoin"); var lite = document.getElementById("litecoin"); var bin = document.getElementById("binancecoin"); var card = document.getElementById("cardano"); var xrp = document.getElementById("ripple"); var pol = document.getElementById("polkadot"); var uni = document.getElementById("uniswap"); var btc_cas = document.getElementById("bitcoin-cash"); var sol = document.getElementById("solana"); var chain = document.getElementById("chainlink"); var poly = document.getElementById("matic-network"); var theta = document.getElementById("theta-token"); var shiba = document.getElementById("shiba-inu"); var vec = document.getElementById("vechain"); var stel = document.getElementById("stellar"); var file = document.getElementById("filecoin"); var aav = document.getElementById("aave"); … -
In Django save multiple filenames (NOT files) for multiple FileFields
In Django I would like to save multiple filenames (NOT files) for multiple FileFields in a Model. I have: 2 Models: One to hold FileFields for different file types (there are identical numbers of files for each type being submitted); the other to hold relevant info of the files. 2 ModelForms: One for each Model. 1 view: To handle the logic for getting filenames from the files and saving them, and discarding the actual file. I have searched many Stack Overflow questions and have derived something that gets me close, but is incorrect. In localhost:8000/admin/ I can see my broken attempt gets me a record for each uploaded file, BUT each record has the same data (the name of the last file in the list for each field). models.py from django.db import models from decimal import Decimal from django.core.validators import FileExtensionValidator # Model for storing related info class RelatedInfo(models.Model): info_name = models.CharField("Name", max_length=255) some_value = models.DecimalField( default=Decimal(0.1), decimal_places=2, max_digits=5 ) X_path = models.CharField(max_length=255, null=True) Y_path = models.CharField(max_length=255, null=True) # Additional fields... # Model for storing filenames class FilesModel(models.Model): related_info = models.ForeignKey( RelatedInfo, on_delete=models.CASCADE ) X_name = models.CharField(max_length=255, blank=True, null=True) X_file = models.FileField( null=True, validators=[FileExtensionValidator(allowed_extensions=["txt"])] ) Y_name = models.CharField(max_length=255, blank=True, null=True) … -
Django REST Framework - return a value from get_queryset?
I am trying to return a value from get_queryset. def get_queryset(self): if self.request.user.is_superuser: return StockPriceModel.objects.order_by('ticker').distinct() elif not self.request.user.is_authenticated: print('in') print(self.request.data) last_price = StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time')[0].last_price print(last_price) return last_price last price gets printed without an issue. In return I get various errors: TypeError at /api/stock-prices-upload/ 'float' object is not iterable If I try to return till: StockPriceModel.objects.all().filter( ticker=self.request.data['ticker']).order_by('-last_date_time') It works. As soon as I try to return just the 0 position queryset I get errors. I assume this is because get_queryset is supposed to return a queryset. Not sure how to return just the value. -
Django DRF validate() is not executed with multiple serializer inheritance
I am trying to achieve the following behavior: class Serializer1(serializers.Serializer): field1 = serializers.CharField() class Serializer2(serializers.Serializer): field2 = serializers.CharField() field3 = serializers.IntegerField() field4 = serializers.IntegerField() def validate(self, data): if data['field3'] > data['field4']: raise serializers.ValidationError('field3 must be < field4') class Serializer3(Serializer1, Serializer2): ... serializer = Serializer3(data=data, many=True) serializer.is_valid() serializer.errors EXPECTED: >> [{ 'field1': [ErrorDetail(string='field can't be empty', code='blank')], 'field2': [ErrorDetail(string='field can't be empty', code='blank')], 'non-field-errors': [ErrorDetail(string='field3 must be < field4', code='invalid')] }] REAL: >> [{ 'field1': [ErrorDetail(string='field can't be empty', code='blank')], 'field2': [ErrorDetail(string='field can't be empty', code='blank')], }] Comments: I wonder why validate() method of Serializer2 doesn't get executed, and how to get the expected behaviour? what am I missing? I was trying to achieve the expected logic by implementing Custom class-based validator like so: class IsBigger: requires_context=True def __call__(self, serializer_field): ### serializer_field seems useless here since this object doen't give me access to fields ### see what does dir(serializer_field) do print(dir(serializer_field)) raise serializers.ValidationError('Test Error') class Serializer2(serializers.Serializer): field2 = serializers.CharField() field3 = serializers.IntegerField(validators=[IsBigger()]) field4 = serializers.IntegerField() >> ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', … -
How to define custom check according to my rules and how to implement Django
I using Python 3.10, Django 4.1.2, djangorestframework==3.14.0 (front separately) In an order, the products received field is empty by default. As we receive the order, we must remove these elements from the ordered field and transfer them to the received ones. received products must contain only products from requested Products After submitting request with amount of received products, this particular products should be removed from requested Products and addiing to recived_products I have two ideas for a theoretical implementation. Using the patch, the received_product and the elements in it Separate method I have this code: class Orders(models.Model): delivery_model_choices = (("Pickup", "Pickup"), ("Delivery", "Delivery")) order_status_choices = (("Draft", "Draft"), ("Open", "Open"), ("Partially Received", "Partially Received"), ("Received", "Received"), ("Cancelled", "Cancelled")) costumer = models.ManyToManyField(Costumers) products = models.ManyToManyField(Products) recived_products = ??? date_create = models.DateTimeField(auto_now_add=True) delivery = models.CharField(max_length=40, choices=delivery_model_choices) delivery_date = models.DateField() order_status = models.CharField(max_length=40, choices=order_status_choices) total_price = models.CharField(max_length=10) Please, I ask you for a correct example on this implementation. I'm still new to development -
Django ORM left join subquery
I have the following model: class Transaction(models.Model): created_by_id = models.IntegerField() quantity = models.FloatField() transaction_type = models.SmalIntegerField() transaction_status = models.SmallIntegerField() related_transaction_id = models.IntegerField( blank=True, null=True, ) And the table currently holds this data: id created_by_id quantity transaction_type transaction_status related_transaction_id 27 25 1 2 3 24 26 25 0 2 1 25 25 10 -1 2 2 null 24 10 -1 2 2 null 23 10 -1 2 2 null 22 10 -1 2 2 null 21 25 1 1 1 null I want to replicate the following SQL statement in Django's ORM (this is the exact output I am looking for): WITH pending_status AS ( SELECT id AS pending_id, transaction_status AS pending_status FROM transaction WHERE transaction_status = 2 ), done_or_rejected AS ( SELECT id AS related_id, related_transaction_id, transaction_status AS current_status FROM transaction WHERE transaction_status != 2 AND transaction_type = 2 ), all_transactions AS ( SELECT id AS original_id, created_by_id, quantity, transaction_status, transaction_type FROM transaction ) SELECT original_id, created_by_id, quantity, related_id, coalesce(current_status, transaction_status) as status, transaction_type FROM all_transactions LEFT JOIN pending_status ON pending_status.pending_id = all_transactions.original_id LEFT JOIN done_or_rejected ON done_or_rejected.related_transaction_id = pending_status.pending_id AND pending_status.pending_status != done_or_rejected.current_status WHERE (related_id IS NULL AND transaction_status = 1 AND transaction_type != 2) OR (related_id IS NULL … -
Django query to find value of objects from previous period (if exists)
I have a simple django project and I am trying to keep track of ranks for certain objects to see how they change over time. For example, what was the rank of US GDP (compared to other countries) over last 3 years. Below is the postgres db structure I am working with: Below is what I am trying to achieve: What I am finding challenging is that the previous period value may or may not exist and it's possible that even the entity may or may not be in the pervious period. Period can be year, quarter or months but for a specific record it can be either of one and stays consistently same for all the years for that record. Can someone guide me in the right direction to write a query to achieve those tables? I am trying to avoid writing heavy forloop queries because there may be 100s of entities and many years of data. So far I have only been able to achieve the below output: I am just trying to figure out how to use annotate to fetch previous period values and ranks but I am pretty much stuck. -
using different serializers Django
hope someone can help me out. I am trying to call different serializes depending on some factors, and one of the factor is if the field called "code" (which is inside MyCards table) is not null then call the rewardsSerializer. the point is that I am not managing to get to get the value of code to see if it's None or not. down here you can see how I have tried to get the value of "code" with no success ''' class MyCardsViewSet(ModelViewSet): serializer_class = MyCardsSerializer queryset = MyCards.objects.all() def get_serializer_class(self): if self.request.GET.get('code') != None: return RewardSerializer if self.action == 'update': return UpdateMyCardsSerializer else: return MyCardsSerializer ''' -
I want my url to end with details/logged-in-user/
I am creating a profile page for a project. Whenever user tries to fill in their details, i want the url trailig to be localhost:8002/detail/logged-in-user.username. Example localhost:8002/detail/dubsy My problem now is that whenever i edit the username in the url and provide another username that is not logged in, it still renders out the page and i don't want this. views.py @login_required(login_url="signin") def details(request, username): user = User.objects.get(username=username) form = Details() if request.method == "POST": form = Details(request.POST, request.FILES) if form.is_valid(): detail = form.save(commit=False) detail.username = request.user detail.save() return redirect(success, pk=detail.pk) else: form = Details(initial={"matricno":request.user.username}) return render(request, "details.html", {"form":form}) urls.py from django.urls import path from . import views urlpatterns = [ path("details/<str:username>/", views.details, name="details"), ] So my problem is that i want to prevent rendering out the page for a user who is not logged in. -
'<' not supported between instances of 'int' and 'str' in search view Django
I just found that error yesterday I don't know what happend everthing was working just fine until I full testing the website TypeError at /home/search_view/ '<' not supported between instances of 'int' and 'str' Request Method: GET Request URL: http://127.0.0.1:8000/home/search_view/?csrfmiddlewaretoken=MzGKJGMz7C3uoJgFIILHdZcaLihBfOHQbLGNzyEi9X0HzptGqNbOREi5AS5cQZxo&q=bahrain Django Version: 3.2.8 Exception Type: TypeError Exception Value: '<' not supported between instances of 'int' and 'str' Exception Location: C:\Users\moham\Desktop\Tm471_final\tm471\travel_guide\views.py, line 174, in get_queryset Python Executable: C:\Users\moham\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.6 Python Path: ['C:\\Users\\moham\\Desktop\\Tm471_final\\tm471', 'C:\\Users\\moham\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\moham\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\moham\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\moham\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\moham\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 02 Dec 2022 13:33:52 +0000 that error happend when I try to search with any words like this example views.py class SearchView(ListView): template_name = 'travel_guide/view_list.html' paginate_by = 20 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: country_results = country.objects.search(query) city_results = city.objects.search(query) articles_results = articles.objects.search(query) print(query) # combine querysets queryset_chain = chain( country_results, city_results, articles_results, ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a list return qs return country.objects.none() HTML file {% extends 'base.html'%} {% load class_name %} {% block content %} <div class="container"> … -
type object 'Teachprofile' has no attribute '_meta'
Models.py class Teachprofile: owner=models.ForeignKey(User,on_delete=models.CASCADE,default=1) name=models.CharField(max_length=51) DOB=models.DateField() Address=models.TextField() Place=models.CharField(max_length=51) City=models.CharField(max_length=51) State=models.CharField(max_length=51) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default=1) Forms.py class Teachprofeditform(forms.ModelForm): class Meta: model = Teachprofile exclude = ['owner'] When I running the server,I get error as File "D:\Newproject\elearn\views.py", line 7, in <module> from .forms import UserRegistrationForm,CourseeditForm,ExameditForm,MarkeditForm,Teachprofeditform,Stuprofeditform File "D:\Newproject\elearn\forms.py", line 32, in <module> class Teachprofeditform(forms.ModelForm): File "D:\Newproject\env\lib\site-packages\django\forms\models.py", line 306, in __new__ fields = fields_for_model( File "D:\Newproject\env\lib\site-packages\django\forms\models.py", line 181, in fields_for_model opts = model._meta AttributeError: type object 'Teachprofile' has no attribute '_meta' I tried so many ways to debug,but didn't get the expected results.Also unable to migrate.I have to run the server. -
Django Admin ERR_QUIC_PROTOCOL_ERROR
Django Admin list view page for a single model returns a blank page. it only load some of the buttons. console shows this error Failed to load resource: net::ERR_QUIC_PROTOCOL_ERROR. Have been trying somethings but couldn't solve this one. Also it doesn't happen on local machine. I am using django jet. tried using the vanilla django admin but still the same error. Other than this model all the other model's list view page is working fine. If anyone has faced this error in the past or know anything about it, suggest me some fixes. any help would be appreciated. Thanks -
How to make Django render URL dispatcher from HTML in Pandas column, instead of forwarding raw HTML?
I want to render a pandas dataframe in HTML, in which 1 column has URL dispatched links to other pages. If I try to render this HTML, it just keeps raw HTML, instead of converting the URLS: utils.py import pandas as pd df = pd.DataFrame(["2022-007", "2022-008", "2022-111", "2022-222", "2022-555", "2022-151"], columns=["column_of_interest"]) df["column_of_interest"] = df['column_of_interest'].apply(lambda x: '''<a href="{{% url 'columndetails' {0} %}}">{0}</a>'''.format(x) df_html = generate_html(df) context={"df" : df_html} def generate_html(dataframe: pd.DataFrame): # get the table HTML from the dataframe table_html = dataframe.to_html(table_id="table", escape=False) # construct the complete HTML with jQuery Data tables # You can disable paging or enable y scrolling on lines 20 and 21 respectively html = f""" {table_html} <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script> <script> $(document).ready( function () {{ $('#table').DataTable({{ // paging: false, // scrollY: 400, }}); }}); </script> """ # return the html return html views.py def column(request): context = get_context(request) return render(request, "database/column.html", context) def columndetails(request, column_of_interest): return render(request, "/columndetails.html") urls.py urlpatterns = [ path('columndetails/<str:column_of_interest>/', views.labrequest_details, name="columndetails")] toprocess.html {% extends "database/layout.html" %} {% load static %} {% block body %} <link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet"> <br /> <div style="float: left;" class="container" id="labrequestoverview"> {{ df|safe }} </div> Everything shows normal, and the HTML is rendered almost as should, … -
Wagtail SteamFields for community user generated content instead of editor, author workflow
I really like StreamFields, but I don't want the baggage of Wagtail's Publishing system. For example, consider a Forum community site. Instead of using CK Editor or BBCode, Markdown etc form input. I want to give users the option of StreamField based input to construct posts or replies Is this possible? If yes, what steps would I need to take or edits to Wagtail do I need to do? I'm guessing using a permission system while keeping the user as a limited admin would be the thing to do, since removing the user from admin doesn't seem to be possible since Wagtail is heavily reliant on Django Admin. -
How can we get selected menu with multiple pages
Please see the below screenshot I want to get selected this contacts menu if I click on the View contacts page which is redirect me to another page. (see screenshot-2) for contacts menu it's working fine if I click on to the contacts menu but if I click on to the view contact it's not showing me contacts menu selected. So how can I get selected if I am in another page? basically I want this functionality for all menus. Here is the code : javascript <script> const currentLocation = location.href; const menuItem = document.querySelectorAll('.sidebar-menu a'); const menuLength = menuItem.length for(let i=0; i<menuLength;i++){ if(menuItem[i].href === currentLocation){ alert("in if condition"); alert(menuItem[i].href); menuItem[i].className = "active" } sidebar-menubar code <div class="sidebar"> <div class="sidebar-logo"> <a href="#"> <img src="{% static 'images/paramLogo_sideBar.png' %}" alt=""></a> </div> <div class="sidebar-menu"> <ul> <li> <a class="nav-link homecls" href="{% url 'home' %}"> <img class="sidebar-icon" src="{% static 'images/home.png' %}" alt="">Home</a> </li> <li> <a class="nav-link contactscls" href="{% url 'broadcastlist' %}"> <img class="sidebar-icon" src="{% static 'images/contacts.png' %}" alt="">Contacts</a> </li> <li> <a class="nav-link messagescls" href="{% url 'howToSend' %}"> <img class="sidebar-icon" src="{% static 'images/messages.png' %}" alt="">Messages</a> </li> <li> <a class="nav-link dashboardcls" href="{% url 'dashboardSMS' %}"> <img class="sidebar-icon" src="{% static 'images/dashboardIcon.png' %}" alt="">Dashboard</a> </li> </div> -
React JS - Capturing selected items from SELECT Multiple field
I'm using a form where an admin can create a class and add students to the class. I'm using SELECT multiple to allow the admin to select multiple students. My question is how do I capture the selected range and export that to a list. I have tried to use dataset but no luck. function ClassesCreate(props) { const [token, setToken] = useState(""); const [hasToken, setHasToken] = useState(""); useEffect(() => { if(localStorage.getItem("token")){ setToken(localStorage.getItem("token")); setHasToken(true); } }, []); function createClasses(){ let login_token = localStorage.getItem("token") let data={ class_number:document.getElementById("ClassNumber").value, course:document.getElementById("Course").value, semester:document.getElementById("Semester").value, lecturer:document.getElementById("Lecturer").value, student:document.getElementById("Student").dataset } axios.post(BaseUrl+"attendance/classes_viewset/", data, {headers:{ "Authorization": "Token "+login_token }}).then(response=>{ alert("Create successful") }).catch(error=>{ console.log(error) }) } return ( <div> <p>Class Number: <input type={"text"} id={"ClassNumber"}/> </p> <p> Course: <select id={"Course"}> <Course/> </select> </p> <p> Semester: <select id={"Semester"}> <Semester/> </select> </p> <p> Lecturer: <select id={"Lecturer"}> <Lecturer/> </select> </p> <p> Students: <select id={"Student"} multiple > <Student/> </select> </p> <p> <button className={"btn btn-danger"} onClick={createClasses}>Create</button> </p> </div> ); } export default ClassesCreate; INSPECT/CONSOLE from browser AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 400" name : … -
Django Redis problem with Docker: InvalidCacheBackendError: No module named 'django.core.cache.backends.redis'
StackOverflow! This is the first question I am asking but I have received many other answers from here thanks a lot. So my problem is that I want to use Redis through docker for the cache but got this error. django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'django.core.cache.backends.redis.RedisCache': No module named 'django.core.cache.backends.redis' My cache settings are this. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', } } I took them from Django documentation. I used this command to start a Redis instance in docker. docker run --name some-redis -d redis I saw a few older posts that didn't help me with the problem. -
How to escape double quotation symbol during lambda apply operation on dataframe column?
I have a pandas column, in which I want to replace the strings with a href hyperlinks that link to a certain url in urls.py when using Django. I managed to get the following: import pandas as pd df = pd.DataFrame(["2022-007", "2022-008", "2022-111", "2022-222", "2022-555", "2022-151"], columns=["column_of_interest"]) df["column_of_interest"] = df['column_of_interest'].apply(lambda x: '<a href=' "{{% url 'columndetails' {0}%}}" '>{0}</a>'.format(x)) This results for example in the following: df["column_of_interest"][0] "<a href={% url 'columndetails' 2022-007%}>2022-007</a>" However, when I run this in Django, and try to get the redirect the following error occurs: Request URL: http://127.0.0.1:8000/%7B%25 The current path, {%, didn’t match any of these. I think this problem would be resolved if I can manage to get this output as per the Django docs: df["column_of_interest"][0] "<a href="{% url 'columndetails' 2022-007%}">2022-007</a>" ↑ ↑ How can I change my .apply(lambda x) to include double quotation marks before and after the {}? I tried escaping with \\ and throwing round the single and double quotation marks, but can't seem to solve this problem easily. -
How to run javascript through the for loop?
I created a search and highlight field for my model objects. The page takes a text input and filters the objects like Documents.objects.filter(content) I'm using read more and highlight functions to highlight the input word and show the part of the long content. But I can't click some read-mores on the row. For example, I can't click the 1st and 3rd row (it returns javascript:void(0) but there is no action) but I can click the other rows. How can I fix that? <div id="highlights" > <div class="row"> <div class="col-md-12" > <div class="box"> <p class="countParawords-{{ forloop.counter0 }}" id="paragraph-{{ forloop.counter0 }}"> {{ document.content }} </p> </div> </div> <input id="typed-text-{{ forloop.counter0 }}" type="text" class="hidden_input" placeholder="Type text" value="{{ key_word }}"> </div> </div> <script> {% for doc in documents %} var opar = document.getElementById('paragraph-{{ forloop.counter0 }}').innerHTML; $(document).ready(function() { var maxLength = 300; var moretxt = "...Read More"; var lesstxt = "...Read Less"; $(".countParawords-{{ forloop.counter0 }}").each(function() { if(opar) { var paragraph = (document.getElementById('paragraph-{{ forloop.counter0 }}')); var search = document.getElementById('typed-text-{{ forloop.counter0 }}').value; search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); var re = new RegExp(search, 'g'); if (search.length > 0) paragraph.innerHTML = opar.replace(re, `<span style="background: #cead00">$&</span>`); } else{ console.log("No data") } var myStr = paragraph.innerHTML if ($.trim(myStr).length > maxLength) { var … -
With drf-yasg, how can i show multiple openapi schemes?
Used: Django 2.2, drf-yasg 1.17.1, python 3.9 How can I show with drf-yasg multiple openapi schemes? API returning different responses, depending on the request. Example: Basic response Is it possible in drf-yasg to show responses like this? Expected Result In the yaml file, this is implemented using oneOf. Code example: responses: '200': content: application/json: schema: properties: count: type: integer next: type: string previous: type: string results: oneOf: - $ref: '#/components/schemas/BaseStocks' - $ref: '#/components/schemas/Apteka36.6Stocks' - $ref: '#/components/schemas/FarmiyaStocks' - $ref: '#/components/schemas/MailruStocks' - $ref: '#/components/schemas/NeofarmStocks' - $ref: '#/components/schemas/YandexStock' - $ref: '#/components/schemas/UtekaStocks' Is it possible to repeat such a construction with drf-yasg?