Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Active Django user after successful PayPal payment
I am attempting to implement a PayPal gateway after user sign-up for a webapp. Once the user registration form is submitted, a signal sets the user to inactive (on purpose). I want to set the user to active after a successful PayPal payment; however, Im having trouble identifying how to get the user id to the receiver to activate the user account since the PayPal button has a separate landing page (and the user isn't authenticated at this point). Is it possible to pass the newly created user instance from the registration page as context to the payment-process page? Any help would be greatly appreciated. Code below: VIEWS def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect("process-payment") else: # create empty form for user to fill in form = RegisterForm() return render(request, "register/register.html", {"form": form}) def payment_done(request): return redirect('login') def process_payment(request): host = request.get_host() paypal_dict = { "cmd": "_xclick-subscriptions", 'business': settings.PAYPAL_RECEIVER_EMAIL, "a3": "1.75", # monthly price "p3": "1", # duration of each unit (depends on unit) "t3": "M", # duration unit ("M for Month") "src": "1", # make payments recur "sra": "1", # reattempt payment on payment error "no_note": "1", # remove extra notes (optional) … -
I made simple student work automation with pycharm python with buttons. I need to open this project with django, but I can't install django
I have a simple button student work automation project that I made with pycharm python. This is my school homework. I need to make a django connection and open it in django, I couldn't manage it, I did it all over again, I can't manage the url definitions, can anyone help me please I installed django with my research, made some progress and got this error '' The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs '' but now i deleted django, i went back to the beginning, can anyone install django from the beginning please -
How can I specify OneToMany relationship in Django models?
I am using Django for fetching data from the join of three tables. Table1, Table2, and Table3 all have a column name cols. I want to join all three tables and have to define the models for that. I can use models.ForeignKey but as per the documentation: The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True. But the field cols in Table3 is not unique, there can be duplicate values for the field. Then how can I do the OneToMany relationship for these tables? I could use ManyToMany but then it violates the relationship between Table1 and Table2 as they have unique values for the column. -
Amazon S3 Bucket static files not accessible from my Heroku-hosted Django app
Django app hosted on Heroku. All static files are in an AWS S3 bucket with "Block all public access: Off", ACL set to "allow list/read" across the board, and the "access: public" tag is displayed under permissions. Launching Django app from Heroku dashboard is met with Bad request 400 error. Launching with debug=True shows more: "SuspiciousOperation at / Attempted access to '/img/faviconB-32x32.png' denied." Removing the link tag for that exact resource in my index.html is no improvement, same error occurs for any remaining static files. I can access any item in the bucket with its object url without issue, for example: https://heroku-brainteasers-app-tmurphy.s3.us-east-2.amazonaws.com/static/img/brainteaserslogo.jpg my django settings.py: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'heroku-brainteasers-app-tmurphy' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_DEFAULT_ACL = None # Use S3 bucket's setting AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_STORAGE = 'mydjangosite.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'mydjangosite.storage_backends.PublicMediaStorage' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/' MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/" STATICFILES_DIRS = [ BASE_DIR / 'static', ] If I remove all the static file 's from my html, taking the bucket out of the loop entirely, the app loads and I see the home page. It seems like the django settings are failing to request the resources properly from my bucket, … -
Check if an id is in another model's field, and get the connected values
Given these two models: class Event(models.Model): title = models.CharField(max_length=200) class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE,null=True, blank=True) event = models.ForeignKey('Event', on_delete=models.CASCADE) class Venue(models.Model): venue_name = models.CharField(max_length=50) How can I filter only the venues that appear in a dateEvent? And how can I get the Event details linked to a specific venue? Right now I attempted this, which returns noniterable and non exists error: venues = list(Venue.objects.filter(dateevent__venue.icontains=id).values('venue_name', 'dateevent__event.id') -
AttributeError at /news/nasafning-rni-bilindi/ 'list' object has no attribute 'comment'
AttributeError at /news/nasafning-rni-bilindi/ 'list' object has no attribute 'comment' Request Method: GET Request URL: http://127.0.0.1:8000/news/nasafning-rni-bilindi/ Django Version: 4.2.1 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'comment' Exception Location: C:\Users\Victus\faculty_news\news\views.py, line 91, in detail Raised during: news.views.detail Python Executable: C:\Users\Victus.virtualenvs\faculty_news-HS6Ih4-T\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\Victus\faculty_news', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310', 'C:\Users\Victus\.virtualenvs\faculty_news-HS6Ih4-T', 'C:\Users\Victus\.virtualenvs\faculty_news-HS6Ih4-T\lib\site-packages'] Server time: Sat, 27 May 2023 21:35:47 +0500 Traceback Switch to copy-and-paste view C:\Users\Victus.virtualenvs\faculty_news-HS6Ih4-T\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars C:\Users\Victus.virtualenvs\faculty_news-HS6Ih4-T\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars C:\Users\Victus\faculty_news\news\views.py, line 91, in detail comments = news.comment.filter(active=True) nothing nothing nothing -
Django - "" appearing under <body> tag and adding space to page
I noticed this when i was getting spacing above the navbar, after Inspecting the page i found a random "" under tag which is causing to add a space on the page. This doesnt show up if i stick all the html in one file (home.html) and runserver. However, when i start using extends or includes with my base.html, "" pops up. Any ideas on possible fixes? I am using Visual Studio Community 2022 - Version 17.5.2 Inspect Page <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Test</title> </head> Byte Order Mark - it might have something to do with utf-8 with BOM? ive tried copy/pasting in notepad and saving as.. utf-8 without BOM and then pasting back into the html file but it didnt work I used: $(document).ready(function () { let html = document.querySelector("html"); let cleanHTML = html.innerHTML.replace(/[\u200B-\u200D\uFEFF]/gim, ''); html.innerHTML = cleanHTML; }) seems to be removing the problem but i would like to find the root cause of why this is happening instead of pasting code in every project