Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to force users to go through OTP before accessing the password reset form in Django?
path('PassChangeForm/',views.PassChangeForm, name="PassChangeForm" ), i don't want user type PassChangeForm in the URL bar of the browser, and they got PassChangeForm page, They must attempt previous page before accessing this page Suppose I have 2 Functions in my views.py the first function is to enter OTP and the second function is to get the password reset form I just want, User doesn't access that password reset form directly (like type url name or url in the URL bar of the browser). They must attempt the previous page which is Entering OTP and then they got a form of password reset. -
Unable to Login Django Admin
I'm unable to access the admin panel after deploying my Django project on an Ubuntu server using nginx and gunicorn, but wrong password is authenticated on admin panel still on entering correct details it reloads and shows admin panel login page again HTTPS SETTINGS SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True HSTS SETTINGS SECURE_HSTS_SECONDS = 3153600 SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SESSION_ENGINE = 'django.contrib.sessions.backends.db' -
django project error ValueError: source code string cannot contain null bytes
django i have django project when i run python manage.py runserver in my client, project runs good. but when i push project into my vps when i run python manage.py runserver this error is showing up why!? and how can i solve it Traceback (most recent call last): File "/home/roubinaa/public_html/env/roubinaa/manage.py", line 22, in <module> main() File "/home/roubinaa/public_html/env/roubinaa/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/roubinaa/public_html/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/roubinaa/public_html/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/roubinaa/public_html/env/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/roubinaa/public_html/env/lib/python3.9/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/home/roubinaa/public_html/env/lib/python3.9/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/roubinaa/public_html/env/lib/python3.9/site-packages/django/contrib/admin/__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "/home/roubinaa/public_html/env/lib/python3.9/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed ValueError: source code string cannot contain null bytes i try to install full package of my project on the … -
How to resolve CORS error when accessing 'localhost:8000/auth/jwt/create' with Django, Djoser, and Simple JWT?
me estoy trabajando con django djoser y my autenticacion esta basada en simplejwt. my error se trata de cuando accedo a "localhost:8000/auth/jwt/create" me da un error de cors no mermitido, tengo todo bien configurado, cors middleware y todo en la configuracion de rest framework, solo es en esta ruta q me da error y cuando accedo con post, sy accedo con option methods no me da ningun error. erfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff -
Django HTML: Background Image only shows on one templates html file and not on other templates
I'm making a portfolio website using django. My templates are master.html, home.html, about.html, all_categories.html, app_projects.html, and project.html. Every html files extends to the master.html and the master.html loads static. I don't know why but every possible solution that I can think of only resulted in the background-image only appearing on the home.html. home.html with background image all_categories.html with no background image First thing I tried is to have the master.html show the background image so all html files extended to it will also have background image as well. Same outcome, it only shows on the home.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'myglobal.css' %}"> <title>{% block title %}{% endblock %}</title> </head> {% for y in H_Info %} <body style="background-image: url({{y.bg_photo}});background-repeat: no-repeat; background-attachment: fixed; background-size: cover;"> <header> <nav class="navibar" style="background-color:#e3c378"> <div class="navbar-logo"> {% for x in H_Info %} <a href="/" style="text-decoration:none;color:#000000;margin-left: 100px;">{{ x.lastname }} Portfolio</a> {% endfor %} </div> <ul class="navbar-menu" style="margin-right: 100px;;"> <li class="navbar-menu-item"><a href="/categories/">Portfolio</a></li> <li class="navbar-menu-item"><a href="/about/">About</a></li> </ul> </nav> </header> <main class="main-content"> {% block content %} {% endblock %} </main> </body> {% endfor %} </html> But then I think maybe I should have put it on the overall css … -
How to store text mixed with HTML tags and properly display the tags in a Django and jinja2 project?
I take text of an article from PostgreSQL database where it is stored in TEXT type and then insert into html template using jinja as in the expample below: <p>{{article.text}}</p> The problem is that atricle should be divided into paragrafs, which means html tags need to be put inside text. I have tried writing html tags inside the text, like is example below: ...development. Simplicity... However, tags is displayed as a part of an ordinary text. Are there any options to store text mixed with HTML tags? Or, perhaps, there is an alternitive solution? -
Separate form fields to "parts"; render part with loop, render part with specific design, render part with loop again
I want to render part of the form via a loop in template and a part with specific "design". # forms.py class HappyIndexForm(forms.Form): pizza_eaten = forms.IntegerField(label="Pizzas eaten") # 5 more fields minutes_outside = forms.IntegerField(label="Minutes outside") class TherapyNeededForm(HappyIndexForm): had_therapy_before = forms.BooleanField() # about 20 more fields class CanMotivateOthers(HappyIndexForm): has_hobbies = forms.BooleanField() # about 20 more fields The only purpose of HappyIndexForm is to pass the 7 fields to other forms that need work with the "HappyIndex" (it is a made up example). I have designed a very nice and complex template for the HappyIndexForm. The fields of TherapyNeededForm exclusive of the HappyIndexFormfields I want to simply loop over. <!-- template.html --> {% for field in first_ten_fields_therapy_needed %} {{ field }} {% endfor %} {% include happyindexform.html %} {% for field in second_ten_fields_therapy_needed %} {{ field }} {% endfor %} Task: Loop over first ten fields of TherapyNeededForm, then display the specific template I wrote for the fields coming from HappyIndexForm called 'happyindexform.html', then loop over second ten fields of TherapyNeededForm. My problem: If I loop over the fields and include my 'happyindexform.html' the fields coming from inheritance get displayed twice. I for sure can also write the specific template for all … -
Escaping % in django sql query gives list out of range
I tried running following SQL query in pgadmin and it worked: SELECT <columns> FROM <tables> WHERE date_visited >= '2023-05-26 07:05:00'::timestamp AND date_visited <= '2023-05-26 07:07:00'::timestamp AND url LIKE '%/mymodule/api/myurl/%'; I wanted to call the same url in django rest endpoint. So, I wrote code as follows: with connection.cursor() as cursor: cursor.execute(''' SELECT <columns> FROM <tables> WHERE date_visited >= '%s'::timestamp AND date_visited <= '%s'::timestamp AND url LIKE '%%%s%%'; ''', [from_date, to_date, url]) But it is giving me list index out of range error. I guess I have made mistake with '%%%s%%'. I tried to escale % in original query with %%. But it does not seem to work. Whats going wrong here? -
Django quill editor affecting html video tag
So i have a model that collects the description for a course. It is a quill field as shown below: class Course(models.Model): description = QuillField(null=True, blank=True) and i have a model form: class SubTopicForm(ModelForm): class Meta: model = CourseContentSubTopic fields = ['description'] Anytime i try to render this form in the frontend by doing this: {{form.media}} {{form.description}} My html video tag stops working. I noticed the problem comes when i add {{form.media}} to the html file. i have tried looking thorough the docs but i have not seen anything that has proven helpful. -
get str foreign key value of fourth table using python django queryset
I've created four models in django. First Model: class Country(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=2, null=True) Second Model: class Comapny(models.Model): company_name = models.CharField(max_length=20) country_id = models.ForeignKey(Currency, blank=True, null=True, on_delete=models.CASCADE) distance_unit = models.CharField(max_length=20, null=True) created = models.DateTimeField(auto_now=True, null=True) last_modified = models.DateTimeField(auto_now=True, null=True) status = models.BooleanField(default=True) Third Model: class Route(models.Model): company = models.ForeignKey(Comapny, on_delete=models.SET_NULL, null=True) routeid = models.CharField(max_length=100, null=True) source = models.CharField(max_length=50, null=True) destination = models.CharField(max_length=50, null=True) Fourth Model: class ShouldCost(models.Model): run_id = models.UUIDField(default = uuid.uuid4, editable = False) should_cost_name = models.CharField(max_length=50) should_cost_value = models.FloatField(max_length=100) month_year = models.CharField(max_length=100) user_id = models.CharField(max_length=100) route_id = models.CharField(max_length=10000, null=True) uploaded_at = models.DateTimeField(auto_now=True, null=True) status = models.BooleanField(default=True) Using Fourth Model I'm showing data in html table. I want to show country in that html page. but I didn't have country foreign key in Fourth Model. So Now I want to fetch it based on route_id --> company_id --> country_id but route id is not ForeignKey.However I'm saving route_id only but in CharFeild. So How can I get country_id from fourth model? -
Simplest way to import function and variable from another .js file in Django?
Similar question such as this exists, but I think none of the answers make it explicit how to import variables and functions in another .js file and use them. Let's make it simple. Given the following Django project, what would be the simplest approach to make import succeed, which means to make 3 print on console? Folder structure: ... static a.js b.js templates index.html ... File content: // a.js function Add(a, b){return a + b;} // b.js console.log(Add(1, 2)); <!DOCTYPE html> <!-- index.html --> <html> <head> <script src="{% static 'a.js' %}"></script> <script src="{% static 'b.js' %}"></script> </head> <body><p>Hello World!</p></body> </html> -
How to set a default value to "TimeField()" in Django Models?
The doc says below in DateField.auto_now_add: Automatically set the field to now when the object is first created. ... If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now() So to DateField() and DateTimeField(), I can set each default value as shown below: # "models.py" from datetime import date from django.utils import timezone class MyModel(models.Model): date = models.DateField(default=date.today) # Here datetime = models.DateTimeField(default=timezone.now) # Here Now, how can I set a default value to TimeField() as shown below? # "models.py" class MyModel(models.Model): # ? time = models.TimeField(default=...) -
What could be causing 'Schedule matching query does not exist' error in Django and how to solve it?
I am having a problem with my code. It returns error log schedule = Schedule.objects.get(vehicle=vehicle, day=day) File "/mnt/c/Users/davep/Desktop/a/Water_management/newenv/lib/python3.10/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/mnt/c/Users/davep/Desktop/a/Water_management/newenv/lib/python3.10/site-packages/django/db/models/query.py", line 415, in get raise self.model.DoesNotExist( database.models.Schedule.DoesNotExist: Schedule matching query does not exist. this is my query file https://www.mediafire.com/file/oh0wgkxzcmhu6b7/query.py/file sorry im newbie remove that error log -
Using FormRequest to extract data via HTTP POST
Using FormRequest to extract data via HTTP POST hey guys I will crawl the details of all the products of the site https://bitsclassic.com/fa/ with scrapy To get the url of the products, I have to sends a POST request to the web service https://bitsclassic.com/fa/Product/ProductList I did this, but it doesn't output! How do I post a request? `class BitsclassicSpider(scrapy.Spider): name = "bitsclassic" start_urls = ['https://bitsclassic.com/fa'] def parse(self, response): """ This method is the default callback function that will be executed when the spider starts crawling the website. """ category_urls = response.css('ul.children a::attr(href)').getall()[1:] for category_url in category_urls: yield scrapy.Request(category_url, callback=self.parse_category) def parse_category(self, response): """ This method is the callback function for the category requests. """ category_id = re.search(r"/(\d+)-", response.url).group(1) num_products = 1000 # Create the form data for the POST request form_data = { 'Cats': str(category_id), 'Size': str(num_products) } # Send a POST request to retrieve the product list yield FormRequest( url='https://bitsclassic.com/fa/Product/ProductList', method='POST', formdata=form_data, callback=self.parse_page ) def parse_page(self, response): """ This method is the callback function for the product page requests. """ # Extract data from the response using XPath or CSS selectors title = response.css('p[itemrolep="name"]::text').get() url = response.url categories = response.xpath('//div[@class="con-main"]//a/text()').getall() price = response.xpath('//div[@id="priceBox"]//span[@data-role="price"]/text()').get() # Process the extracted data if … -
wkhtmltopdf not working upon dockerizing my django app
I was working with my django app on my localserver and There was a view that shows me pdf using wkhtmltopdf, when I decided to dockerize my app this result is shown to me when I try to reach the pdf: In views.py: wkhtml_to_pdf = os.path.join( settings.BASE_DIR, "wkhtmltopdf.exe") def resume_pdf(request,id): # return render(request, 'frontend/index.html') options = { 'page-size': 'A4', 'page-height': "13in", 'page-width': "10in", 'margin-top': '0in', 'margin-right': '0in', 'margin-bottom': '0in', 'margin-left': '0in', 'encoding': "UTF-8", 'no-outline': None } template_path = 'frontend/thepdf.html' template = get_template(template_path) context = {"name": "Areeba Seher"} html = template.render(context) config = pdfkit.configuration(wkhtmltopdf=wkhtml_to_pdf) pdf = pdfkit.from_string(html, False, configuration=config, options=options) # Generate download response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="resume.pdf"' theEntry = entry.objects.get(id= id) context = {'entry' : theEntry, 'entrybody': markdown(theEntry.body) } # print(response.status_code) if response.status_code != 200: return HttpResponse('We had some errors <pre>' + html + '</pre>') # return response return PDFTemplateResponse(request=request, cmd_options={'disable-javascript':True}, template=template, context=context) my Dockerfile: FROM python:3.10.5 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN apt-get update \ && apt-get -y install tesseract-ocr RUN pip install --upgrade pip WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . So how can I make wkhtmltopdf work on dockerized django app? -
Field is required, when it's not defined as so
I have the following Django model class Component(models.Model): parent = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children" ) vessel = models.ForeignKey( Vessel, on_delete=models.CASCADE, related_name="components" ) name = models.CharField(max_length=100) manufacturer = models.CharField(max_length=255, null=True, blank=True) model = models.CharField(max_length=255, null=True, blank=True) type = models.CharField(max_length=255, null=True, blank=True) serial_number = models.CharField(max_length=255, null=True, blank=True) supplier = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to="component_images", blank=True, null=True) def __str__(self): return self.name and the viewset looks like this class ComponentViewSet(viewsets.ModelViewSet): serializer_class = ComponentSerializer def get_queryset(self): queryset = Component.objects.all() vessel_id = self.kwargs.get("vessel_id", None) if vessel_id is not None: queryset = queryset.filter(vessel_id=vessel_id) queryset = queryset.filter(Q(parent=None) | Q(parent__isnull=True)) return queryset def retrieve(self, request, pk=None, vessel_id=None): queryset = Component.objects.all() component = get_object_or_404(queryset, pk=pk, vessel_id=vessel_id) serializer = ComponentSerializer(component) return Response(serializer.data) def update(self, request, pk=None, vessel_id=None, partial=True): queryset = Component.objects.all() component = get_object_or_404(queryset, pk=pk, vessel_id=vessel_id) serializer = ComponentSerializer(component, data=request.data, partial=partial) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(detail=True, methods=["delete"]) def delete_component(self, request, pk=None, vessel_id=None): queryset = Component.objects.all() component = get_object_or_404(queryset, pk=pk, vessel_id=vessel_id) # Recursively delete all children of the component self._delete_children(component) # Delete the component itself component.delete() return Response(status=status.HTTP_204_NO_CONTENT) def _delete_children(self, component): children = component.children.all() for child in children: self._delete_children(child) child.delete() this is my simple react form to create a component import … -
AttributeError: 'NoneType' object has no attribute 'extraBottles'
Internal Server Error: /employee/order/79/ Traceback (most recent call last): File "/mnt/c/Users/davep/Desktop/a/Water_management/newenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/mnt/c/Users/davep/Desktop/a/Water_management/newenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/mnt/c/Users/davep/Desktop/a/Water_management/newenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 113, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/davep/Desktop/a/Water_management/employee/views.py", line 44, in view_order day.extraBottles += request.session['extraBottles'] AttributeError: 'NoneType' object has no attribute 'extraBottles' -
save as json or map to django model and then save?
So I have this data I want to save using postgreSQL and Django. The data will come from an external source in the format of json according to the following format: "$schema": "http://json-schema.org/draft-06/schema#", "type": "object", "properties": { "RESPONSE": { "type": "object", "properties": { "RESULT": { "type": "array", "items": { "properties": { "_attr_id": { "type": "string" }, "TrainStation": { "type": "array", "items": { "type": "object", "$ref": "#/definitions/TrainStation" } }, "INFO": { "type": "object", "properties": { "LASTMODIFIED": { "type": "object", "properties": { "_attr_datetime": { "type": "string", "format": "date-time" } }, "additionalProperties": false }, "LASTCHANGEID": { "type": "string" }, "EVALRESULT": { "type": "array", "items": {}, "additionalProperties": true }, My questions, what is the best way to save this data if I want to use later run operations on this. Is it to save it as jsonb or should I actually create a django model to map it and save it that way? -
HTML: Image not displaying
I have an .html file, main.html, in the following project folder /home/bugs/django_projects/mysite/home/templates/home/main.html In the same folder I have an image Bugs.jpg. Eg /home/bugs/django_projects/mysite/home/templates/home/Bugs.jpg I am trying to include the image in the webpage via: <img src="Bugs.jpg">, but the image does not display. I have tried debugging via: https://sebhastian.com/html-image-not-showing/, but I appear to be referencing the correct location of the file. The full code for main.html is below. <!DOCTYPE html> <html lang="en"> <head> <title>B. Rabbit</title> <meta charset="UTF-8"> </head> <body> <h3>Applications</h3> <ul> <li><p><a href="/polls">A Polls Application.</a></p></li> <li><p><a href="/hello">Hello World Application.</a></p></li> </ul> <img src="Bugs.jpg"> </body> </html> Any ideas why the image is not displaying at all? Edit Additional information in response to the below questions: -
Detecting AJAX call in a Django view function
I need Ajax functionality in my Django application. Therefore, a jQuery code calls a Django view function that returns data (here in a simplified form). $(document).ready(function() { // Prevent the form from being submitted normally $('#filter-form').on('submit', function (event) { event.preventDefault(); $.ajax({ url: '/filter_view/', type: 'POST', headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() }, success: function (response) { console.log(response); } }); }); }); The problem is the verification - in the Django view -, that it received an Ajax call. Previously, this could be done by 'is_ajax()', but this function is deprecated. It was replaced, then, by if request.method == 'POST' and request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': or if accept_header == 'application/json' or x_requested_with_header == 'XMLHttpRequest': That all worked. All of a sudden, it did not work anymore, because, although the headers were declared in the AJAX code, headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() } they do not arrive in the Django view. Nothing was changed in the Django middleware. The Chrome browser, used for debugging of the JQuery code, was reset. I dont have the slightest idea, why the headers settings do not get through. Any help would be appreciated. -
Django : Edit main.html to reference static webpage
I am learning Django and I am still very new to it so I don't yet understand how all the pieces fit together. I have successfully built the polls application on the tutorial website (https://docs.djangoproject.com/en/4.2/intro/tutorial01/) and a 'Hello World!' app as an additional test. I have created a main page at the root with links to these two applications. Code for this is below. <!DOCTYPE html> <html lang="en"> <head> <title>B. Rabbit</title> <meta charset="UTF-8"> </head> <body> <h3>Applications</h3> <ul> <li><p><a href="/polls">A Polls Application.</a></p></li> <li><p><a href="/hello">Hello World App.</a></p></li> <li><p></p><a href="/HWFolder/HWPage.htm">Hello World stand-alone page.</a></p></li> </ul> </body> </html> I now want to create a new folder in my project with a static webpage (just a simple html file) and add a link to my main page that will point to this static webpage. That is, rather the create an app via python manage.py startapp hello, I want to just create a raw .html file, stick it in a folder somewhere, and then point to this. But I don't know how to do this. The third list object above is my attempt, but this produces a 404 Page not found error. Below is the urls.py script for the website. I was able to get the Hello … -
I upgraded to Django 4.2.1 and django_plotly_dash is not working anymore - WrappedDash object has no attribute _generate_meta_html
django_plotly_dash docs says they now are compatible with 5x > Django > 3.2x, but after upgrading Django to 4.2.1, I can only make it work on local, but in production returns the traceback I share here below. Traceback (most recent call last): web_container | File "/usr/local/lib/python3.10/site-packages/asgiref/sync.py", line 486, in thread_handler web_container | raise exc_info[1] web_container | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 42, in inner web_container | response = await get_response(request) web_container | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 253, in _get_response_async web_container | response = await wrapped_callback( web_container | File "/usr/local/lib/python3.10/site-packages/asgiref/sync.py", line 448, in call web_container | ret = await asyncio.wait_for(future, timeout=None) web_container | File "/usr/local/lib/python3.10/asyncio/tasks.py", line 408, in wait_for web_container | return await fut web_container | File "/usr/local/lib/python3.10/site-packages/asgiref/current_thread_executor.py", line 22, in run web_container | result = self.fn(*self.args, **self.kwargs) web_container | File "/usr/local/lib/python3.10/site-packages/asgiref/sync.py", line 490, in thread_handler web_container | return func(*args, **kwargs) web_container | File "/aiterra_web_website/wallet/views.py", line 46, in walletHomepage web_container | return render(request, 'investing/wallet-homepage.html', context) web_container | File "/usr/local/lib/python3.10/site-packages/django/shortcuts.py", line 24, in render web_container | content = loader.render_to_string(template_name, context, request, using=using) web_container | File "/usr/local/lib/python3.10/site-packages/django/template/loader.py", line 62, in render_to_string web_container | return template.render(context, request) web_container | File "/usr/local/lib/python3.10/site-packages/django/template/backends/django.py", line 61, in render web_container | return self.template.render(context) web_container | File "/usr/local/lib/python3.10/site-packages/django/template/base.py", line 175, in render … -
I have error while running tests: 'django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured.'
I am writing tests for my DjangoRestFramework application and get the error while running the tests. Trying to solve it for a long period of time but unsuccessfully Full traceback: Traceback (most recent call last): File "/home/rroxxxsii/Загрузки/pycharm-2023.1.1/plugins/python/helpers/pycharm/_jb_unittest_runner.py", line 38, in <module> sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/unittest/main.py", line 101, in __init__ self.parseArgs(argv) File "/usr/lib/python3.11/unittest/main.py", line 150, in parseArgs self.createTests() File "/usr/lib/python3.11/unittest/main.py", line 161, in createTests self.test = self.testLoader.loadTestsFromNames(self.testNames, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/unittest/loader.py", line 220, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/rroxxxsii/PycharmProjects/django_rest_shop/core/account/tests/test_models.py", line 1, in <module> from rest_framework.test import APITestCase File "/home/rroxxxsii/PycharmProjects/django_rest_shop/venv/lib/python3.11/site-packages/rest_framework/test.py", line 139, in <module> class APIRequestFactory(DjangoRequestFactory): File "/home/rroxxxsii/PycharmProjects/django_rest_shop/venv/lib/python3.11/site-packages/rest_framework/test.py", line 140, in APIRequestFactory renderer_classes_list = api_settings.TEST_REQUEST_RENDERER_CLASSES ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/rroxxxsii/PycharmProjects/django_rest_shop/venv/lib/python3.11/site-packages/rest_framework/settings.py", line 218, in __getattr__ val = self.user_settings[attr] ^^^^^^^^^^^^^^^^^^ File "/home/rroxxxsii/PycharmProjects/django_rest_shop/venv/lib/python3.11/site-packages/rest_framework/settings.py", line 209, in user_settings self._user_settings = getattr(settings, 'REST_FRAMEWORK', {}) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/rroxxxsii/PycharmProjects/django_rest_shop/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/rroxxxsii/PycharmProjects/django_rest_shop/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Process finished with … -
for a clothing sales site I want to create a Filter with jquery I can't make the intersection
for a site selling clothes I want to create with jquery a Filter which allows to take the value of size and length then according to the color and size on length, but this part I cannot get the intersection $(".choose-color").on('click', function () {...} $(".choose-size").on('click', function () { var _size = $(this).attr('data-size'); $('.choose-length').hide(); $(".choose-length").removeClass('active'); $('.size' + _size).show(); $('.size' + _size).first().addClass('active'); $(".choose-size").removeClass('active'); $(this).addClass('active');} the for ('.size' + _size) I want to filter not by size, but size and color active I tried " var _color = $(".choose-color.active") ('.size' + _size'+'.color' + _color)" and 'var _color = $(".size" + _size).first().attr('data-color');' in both cases I don't have the right value more clearly the first is empty, the second takes the smaller ID for a site selling clothes I want to create with jquery a Filter which allows to take the value of size and length then according to the color and size on length -
Error while installing mysqlclient in server cpanel
I tried to install mysqlclient in venv in remote server's cpanel by pip install mysqlclient It showed me error Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/ssndebid/virtualenv/debidwar/3.10/bin/python3.10_bin -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_v9zv2th/mysqlclient_4c8a2d7ab62f440eaf9a10d1c071662f/setup.py'"'"'; __file__='"'"'/tmp/pip-install-_v9zv2th/mysqlclient_4c8a2d7ab62f440eaf9a10d1c071662f/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-q5rbsxez cwd: /tmp/pip-install-_v9zv2th/mysqlclient_4c8a2d7ab62f440eaf9a10d1c071662f/ Complete output (39 lines): mysql_config --version ['10.3.39'] mysql_config --libs ['-L/usr/lib64', '-lmariadb', '-pthread', '-ldl', '-lm', '-lpthread', '-lssl', '-lcrypto', '-lz'] mysql_config --cflags ['-I/usr/include/mysql', '-I/usr/include/mysql/..'] ext_options: library_dirs: ['/usr/lib64'] libraries: ['mariadb', 'dl', 'm', 'pthread'] extra_compile_args: ['-std=c99'] extra_link_args: ['-pthread'] include_dirs: ['/usr/include/mysql', '/usr/include/mysql/..'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('__version__', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.10 creating build/lib.linux-x86_64-3.10/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.10/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.10/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.10/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.10/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.10/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.10/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.10/MySQLdb creating build/lib.linux-x86_64-3.10/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.10/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.10/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.10/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.10/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.10/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.10/MySQLdb/constants running build_ext …