Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Python CSV import for Django Heroku App not functioning properly
I'm currently getting this error when I try uploading my CSV file into my Django Heroku CRM app, the app is also using Herokus Postgres DB: Unable to upload file. ValidationError(['“” value has an invalid date format. It must be in YYYY-MM-DD format.']) & Unable to upload file. ValidationError(['“1995-03-28” value has an invalid date format. It must be in YYYY-MM-DD format.']) Here is the codeblock that I am currently using: - views.py class LeadImportView(LoginRequiredMixin, FormView): form_class = LeadImportForm template_name = 'import_leads.html' success_url = '/dashboard/leads/' def form_valid(self, form): df = pd.read_csv(io.StringIO(csv_file.read().decode('utf-8'))) for index, row in df.iterrows(): lead = Lead() ... dob = row['DOB'] if str(dob).strip() == 'nan' or str(dob).strip() == "": try: lead.dob = None except ValidationError: lead.dob = None else: lead.dob = dob ... lead.save() messages.success(self.request, 'Leads successfully imported.') # return redirect('leads:lead-list') return super().form_valid(form) - forms.py class LeadForm(forms.Form): ... dob = forms.DateField() ... - models.py class Lead(models.Model): ... dob = models.DateField(max_length=10, blank=True, null=True) ... As you can see, if the CSV dob value is blank, then it should equal a None value in the DB. However, no matter if the DOB is filled appropriately or empty, the code still errors out. Any insight helps. Also, I would prefer the date … -
'PeopleViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method
** Models.py ** ''' from django.db import models class Person(models.Model): color = models.ForeignKey(Color, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) age = models.IntegerField() def __str__(self): return self.name ''' ** views.py ** ''' from rest_framework import viewsets from .models import * from .serializers import * class PeopleViewSet(viewsets.ModelViewSet): serializer_class = PersonSerializer quaryset = Person.objects.all() ** serializers.py ** ''' from rest_framework import serializers from .models import * class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' ''' ** urls.py ** ''' from django.urls import path, include from app import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('person', views.PeopleViewSet, basename='person') urlpatterns = router.urls urlpatterns = [ path('', include(router.urls)), ] ''' I'm getting this error 'PeopleViewSet' should either include a queryset attribute, or override the get_queryset() method. What is my mistake? -
Is it possible to redirect users to OTP function before accessing password reset form in Django views.py?
Suppose I have 2 Functions in my views.py I just want user's first attempt first the function (OTP function) and then go to the second form ( password change form ) even after they type URL for PassChangeForm in browser url , they directly redirect to OTP function 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 want user to first attempt OTP enter the form and then after go for the password reset form path('PassChangeForm/',views.PassChangeForm, name="PassChangeForm" ), Even they PassChangeForm type in Browser url they get automatically redirected on OTP form -
why can't i run my django project using python manage.py runserver?
I'm trying to run a django file that is given to me to work on, but the moment i run python manage.py runserver it show an error as stated below: C:\Python39\python.exe: can't open file 'C:\Users\tayry\Todo-List-With-Django-master\manage.py': [Errno 2] No such file or directory anyone know how to fix this issue? -
Template does not exist error been trying to solve for two hours
TemplateDoesNotExist at /login/ users/login.html Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 4.2.1 Exception Type: TemplateDoesNotExist Exception Value: users/login.html Exception Location: C:\Users\a\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Users\a\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.3 Python Path: ['C:\Users\a\Desktop\ecommerce', 'C:\Users\a\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\a\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\a\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\a\AppData\Local\Programs\Python\Python311', 'C:\Users\a\AppData\Local\Programs\Python\Python311\Lib\site-packages'] views.py from django.shortcuts import render , redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse from . forms import UserRegistrationForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,f'Your account has been created!') return redirect('login') else: form = UserRegistrationForm() return render(request,'users/register.html',{'form':form}) @login_required def profile(request): return render(request,'users/profile.html') urls.py from django.contrib import admin from django.urls import path,include from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), path('', include('eshop.urls')), ] -
Django rest_framework serializer dynamic depth
I am using a ModelSerializer to serialize a model. How do I have depth = 1 when retrieving a single instance, and depth = 0 when retrieving a list. from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'organizaton'] depth = 1 # <--- How to change this to 0 for the list?