Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'django model' object is not subscriptable
I get this error when I try to do a query set on the Django model 'AppUser' object is not subscriptable despite it is working normally in a print statement but the error only appears when I put it in an IF statement here is my code : def to_representation(self, instance): data = super().to_representation(instance) print("reached here") #print normaly print(AppUser.objects.filter(mobile=instance['mobile']).count() > 0) #print normally (False) if AppUser.objects.filter(mobile=instance['mobile']).count() > 0: # Raises an Exception if instance.playerprofile_set.all().count() > 0: player_profile = instance.playerprofile_set.all()[0] data['player_profile'] = PlayerProfileSerializer( player_profile).data for item in Team.objects.all(): if player_profile in item.players.all(): data['team'] = TeamSerializer(item).data if item.cap.id == player_profile.id: data['team'] = TeamSerializer(item).data # data["team"] = instance. return data -
Django Test assertTemplateUsed() failed: AssertionError: No templates used to render the response
I have an About page and written a test against it. The template renders well in the browser while the assertTemplatedUsed failed even the template name, url name and status code (returns 200) are all correct. Which part went wrong? Thank you! The error below: System check identified no issues (0 silenced). ...F...... ====================================================================== FAIL: test_aboutpage_template (pages.tests.AboutPageTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/code/pages/tests.py", line 54, in test_aboutpage_template self.assertTemplateUsed(self.response, 'about.html') File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 655, in assertTemplateUsed self.fail(msg_prefix + "No templates used to render the response") AssertionError: No templates used to render the response ---------------------------------------------------------------------- Ran 10 tests in 0.070s FAILED (failures=1) My test.py: class AboutPageTests(SimpleTestCase): def setUp(self): url = reverse('about') self.response = self.client.get(url) def test_aboutpage_status_code(self): self.assertEqual(self.response.status_code, 200) def test_aboutpage_template(self): self.assertTemplateUsed(self.response, 'about.html') -
How to get the Primary key of annotate Count in django
Hi stackoverflow community, my question is about django annotate. Basically what I am trying to do is to find duplicated value with same values from two different fields in two different tables. This is my models.py class Order(models.Model): id_order = models.AutoField(primary_key=True) class OrderDelivery(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) delivery_address = models.TextField() class OrderPickup(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) pickup_date = models.DateField(blank=True, null=True) This is my current code: dup_job = Order.objects.filter( orderpickup__pickup_date__range=(start_date, end_date) ).values( 'orderdelivery__delivery_address', 'orderpickup__pickup_date', ).annotate( duplicated=Count('orderdelivery__delivery_address') ).filter( duplicated__gt=1 ) Based on what I have, I am getting result like this (delivery_address is omitted for privacy purpose): {'orderdelivery__delivery_address': '118A', 'orderpickup__pickup_date': datetime.date(2022, 3, 9), 'duplicated': 2} {'orderdelivery__delivery_address': '11', 'orderpickup__pickup_date': datetime.date(2022, 3, 2), 'duplicated': 6} {'orderdelivery__delivery_address': '11 ', 'orderpickup__pickup_date': datetime.date(2022, 3, 3), 'duplicated': 5} {'orderdelivery__delivery_address': '21', 'orderpickup__pickup_date': datetime.date(2022, 3, 10), 'duplicated': 3} {'orderdelivery__delivery_address': '642', 'orderpickup__pickup_date': datetime.date(2022, 3, 7), 'duplicated': 2} {'orderdelivery__delivery_address': '642', 'orderpickup__pickup_date': datetime.date(2022, 3, 8), 'duplicated': 2} {'orderdelivery__delivery_address': 'N/A,5', 'orderpickup__pickup_date': datetime.date(2022, 3, 8), 'duplicated': 19} Is there a way to get the id_order of those 'duplicated'? I have tried include id_order in .values() but the output will not be accurate as the annotation is grouping by the id_order instead of delivery_address. Thank you in advance -
How to start cron through Dockerfile entrypoint
I'm trying to run cron job through Docker entrypoint file. Dockerfile: FROM python:3.8-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update -y && apt-get install -y build-essential postgresql python-scipy python-numpy python-pandas cron libgdal-dev && apt-get clean && rm -rf /var/lib/apt/lists/* COPY ./django-entrypoint.sh . RUN mkdir /industrialareas WORKDIR /industrialareas COPY ./project . COPY ./requirements.txt . RUN chmod 755 /django-entrypoint.sh RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 CMD ["/django-entrypoint.sh"] django-entrypoint.sh: #!/bin/bash # Django python /industrialareas/manage.py collectstatic --noinput python /industrialareas/manage.py migrate python /industrialareas/manage.py runserver 0.0.0.0:8000 # Cron service cron restart service cron status python /industrialareas/manage.py crontab add python /industrialareas/manage.py crontab show exec "$@" But only works Django commands because i check it service cron status and is stopped and python manage.py crontab show and method not added. If i run script manually works well ./django-entrypoint.sh. The cron job is executed and i can see the output on log file. Anybody could help me please ? Thanks in advance. -
joining Django models
please help me out. I want to have the results from this sql query: select Information.id from Information inner join Search on Information.id=Search.article_id where Search.search_id = 'fish'; my models.py class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) search_id = models.CharField(max_length=100) article_id = models.CharField(max_length=100) def __str__(self): return self.id how can i get these results? I don't like to work with foreign keys -
Django ORM duplicated LEFT OUTER JOIN in SQL when annotate
Problem When I add an annotation based on the reverse field, then a double "LEFT OUTER JOIN" appears in the SQL result. As a result, the sum annotation is considered incorrect (duplicated depending on the number of back annotations) How to make sum annotation correct? Django 4.0.3 Python 3.10 Result SQL SELECT "frontend_book"."id", "frontend_book"."title", "frontend_book"."author_id", COALESCE( SUM("frontend_sell"."price"), 0 ) AS "total_profit_author", COALESCE( SUM(T4."price"), 0 ) AS "total_profit_resolver" FROM "frontend_book" INNER JOIN "frontend_human" ON ( "frontend_book"."author_id" = "frontend_human"."id" ) LEFT OUTER JOIN "frontend_sell" ON ( "frontend_human"."id" = "frontend_sell"."author_id" ) LEFT OUTER JOIN "frontend_sell" T4 ON ( <----- HERE "frontend_human"."id" = T4."resolver_id" ) GROUP BY "frontend_book"."id" Models class Human(models.Model): name = models.CharField( 'Name', max_length=200, blank=True, ) class Book(models.Model): title = models.CharField( 'Title', max_length=200, blank=True, ) author = models.ForeignKey( Human, verbose_name='author', related_name='books', on_delete=models.CASCADE, ) class Sell(models.Model): author = models.ForeignKey( Human, verbose_name='Author', related_name='author_sells', on_delete=models.CASCADE, ) resolver = models.ForeignKey( Human, verbose_name='Resolver', related_name='resolver_sells', on_delete=models.CASCADE, ) price = models.FloatField( 'Price', default=0, blank=True ) Views from rest_framework.response import Response from rest_framework.views import APIView from backend.api.frontend.models import Book from django.db.models import Sum, FloatField from .serializers import BookSerializer class TestView(APIView): def get(self, request): qs = Book.objects.all() qs = qs.annotate( total_profit_author = Sum( 'author__author_sells__price', output_field=FloatField(), default=0, ), total_profit_resolver = Sum( 'author__resolver_sells__price', … -
How to deploy django app on IIS error 403.14
I have a problem with deployment my Django application on IIS. my wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'BETA.settings') application = get_wsgi_application() in my settings.py I have DEBUG = True ALLOWED_HOSTS = [some ip] WSGI_APPLICATION = 'BETA.wsgi.application' my __init__.py is empty in root derictory web.config looks like: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <defaultDocument> <files> <clear /> <add value="login.html" /> </files> </defaultDocument> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor = 'C:\Program Files\Python310\python.exe"|"C:\Program Files\Python310\lib\site-packages\wfastcgi.py' resourceType="Unspecified" </configuration> requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="BETA.wsgi.application"> <add key="PYTHONPATH" value="D:\Applications\HRtool\dev\wwwroot\BETA"> <add key="DJANGO_SETTINGS_MODULE" value="BETA.settings"> </appSettings> in static web.config is next: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <clear/> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" /> </handlers> </system.webServer> </configuration> But when I start my app on ISS i have another problem: I am trying to enable Directory Browsing, but it doesn't help. In advance settings in Pool I have .Net 4.5. How to fix it ? -
How to create Azure Virtual machine with VM Extension using the python SDK
I want to create an Azure virtual machine with the VM extension(Custom script extension) using the python SDK. Basically, I want a python program that will create the VM with VM extension using the Azure SDK management libraries, I am able to use the Azure SDK management libraries in a Python script to create a resource group that contains a Linux virtual machine. https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-example-virtual-machines?tabs=cmd But I need my Virtual machine with VM extension in it. -
How do I test a DRF view that updates data on every request?
I'm using Django Rest Framework. I have a model Listing, which has an attribute view_count. Every time data is retrieved from listing_detail_view, view_count is updated using the update method and an F expression. Everything is working as expected, but the test for the view is failing as view_count in the response is always 1 count more. // views.py @api_view(['GET']) def listing_detail_view(request, pk): listing = Listing.objects.filter(pk=pk) serializer = ListingSerializer(listing[0]) listing.update(view_count=F('view_count') + 1) return Response(serializer.data) Note: I'm filtering instead of getting because from my understanding the update method is only available for a QuerySet. // test_views.py def setUp(self): self.listing = Listing.objects.create(id=1) def test_listing_detail_view(self): response = client.get(reverse('listing-detail', kwargs={'pk': self.listing.pk})) listing = Listing.objects.get(pk=self.listing.pk) serializer = ListingSerializer(listing) self.assertEqual(response.data, serializer.data) Here's the AssertionError: {'id': '1', 'view_count': '0'} != {'id': '1', 'view_count': '1'} How do I go about testing this view and its view_count update functionality? -
Django TypeError at /signup/ 'in <string>' requires string as left operand, not list
I have a signup form that verifies if the email field contains gmail and gives an error if not. forms.py def clean_email(self): submitted_data = self.cleaned_data['email'] if '@gmail.com' not in submitted_data: raise forms.ValidationError('You must register using a pathfinder23 address') views.py class SignUpView(View, SuccessMessageMixin): form_class = SignUpForm template_name = 'user/register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Starlab Account' message = render_to_string('user/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('confirm_registration') return render(request, self.template_name, {'form': form}) I want to add few other 'trusted emails' so the form will allow users to register for instance: @yahoo.com, @outlook.com but I cannot add a list or tuple because I get an error: TypeError at /signup/ 'in <string>' requires string as left operand, not tuple Question How can I create a list of trusted email domains and instead '@gmail.com' put list of email domains? -
Django Queryset - Foreign Key Relationship
I am trying to make a query set where I get all menu names from the table based on the group. class Menu(models.Model): name = models.CharField(max_length=50, blank=False, null=False) link = models.CharField(max_length=50, blank=True, null=True) parent = models.ForeignKey(to='menu', blank=True, null=True, related_name="sub_menu", on_delete=models.CASCADE) class MenuGroup(models.Model): menu = models.ForeignKey(to='menu.Menu', on_delete=models.CASCADE, blank=True, null=True, related_name="menu", related_query_name="menus") group = models.ForeignKey(to=Group, on_delete=models.CASCADE, blank=True, null=True, related_name="menu_group", related_query_name="menu_groups") -
Django Date time Seting
I'm new to Django and I wanted to create a project where I can set date and time for a model form i.e., as an admin I will set a date and time to accept / collect data including files too and once the date and time exceeds the form get disabled automatically and cannot be altered. I got to know about validations but am confused. Any guidance will do. -
django form changed_data method: why checked radio button always in changed_data even if not changed?
I want to check when field has been changed when submitting of form with Django. There are tow form attributed that can be used: has_changed (return True if at least one field has been changed) and changed_data (that return list of changed field). But for a reason I can not understand, when a radio button field is checked, has_changed will always return True, even if not changed (and filed is in changed_data list) In the example belwo, inc_dat field (date field) behavior is correct but not inc_oui_age which is a radio button models.py class Inclusion(models.Model): """ A class to create a Inclusion instance. """ _safedelete_policy = SOFT_DELETE_CASCADE # insert model fields ide = models.AutoField(primary_key=True) pat = models.ForeignKey('Patient',on_delete = models.CASCADE, related_name='inclusion_patient', db_column='pat') inc_dat = models.DateField('Date de la visite', null=True, blank=True) inc_oui_age = models.IntegerField('18 ans ≤ âge ≤ 45 ans OU âge ≥ 55 ans', null=True, blank=True) ... forms.py class InclusionForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.IDE = kwargs.pop("ide", None) self.PATIENT = kwargs.pop("patient", None) self.USER = kwargs.pop("user", None) super(InclusionForm,self).__init__(*args, **kwargs) self.fields['inc_dat'] = forms.DateField(label = 'Date de la visite',widget=forms.TextInput(attrs={'autocomplete': 'off'}),required=False, disabled=DISABLED) self.fields['inc_oui_age'] = forms.TypedChoiceField(label = '18 ans ≤ âge ≤ 45 ans OU âge ≥ 55 ans',widget=forms.RadioSelect(attrs={'disabled': DISABLED}),required=False,choices=[i for i in Thesaurus.options_list(1,'fr') if i … -
Django Elastic Beanstalk - No module named 'turtle'
After running eb deploy & opening up my elastic beanstalk django website I get a module error of No module named 'turtle'. It all run perfect locally and I have PythonTurtle installed & in my requirements.txt. Is there a missing pip I haven't accounted for in my requirements.txt? I've run pip3 freeze > requirements.txt many times with the same result. How can I get past this error? appdirs==1.4.4 asgiref==3.3.4 astroid==2.4.2 attrs==21.2.0 autopep8==1.5.7 awsebcli==3.20.2 bcrypt==3.2.0 blessed==1.18.1 botocore==1.21.65 bugsnag==4.2.0 cached-property==1.5.2 cement==2.8.2 certifi==2021.5.30 cffi==1.14.6 chardet==4.0.0 colorama==0.4.3 cryptography==3.4.7 distlib==0.3.1 dj-places==4.0.0 Django==3.1.6 django-crispy-forms==1.11.0 django-filter==21.1 django-mathfilters==1.0.0 djangorestframework==3.12.4 djangorestframework-simplejwt==5.0.0 docker==4.4.4 docker-compose==1.25.5 dockerpty==0.4.1 docopt==0.6.2 filelock==3.0.12 future==0.16.0 idna==2.10 importlib-metadata==4.8.2 isort==5.7.0 jmespath==0.10.0 jsonschema==3.2.0 lazy-object-proxy==1.4.3 Markdown==3.3 mccabe==0.6.1 paramiko==2.7.2 pathspec==0.5.9 psycopg2-binary==2.8.6 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.3.0 pylint==2.6.0 PyNaCl==1.4.0 pyrsistent==0.18.0 python-dateutil==2.8.1 PythonTurtle==0.3.2 pytz==2021.1 PyYAML==5.4.1 requests==2.25.1 s3transfer==0.5.0 selenium==3.141.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.1 termcolor==1.1.0 texttable==1.6.3 toml==0.10.2 tqdm==4.62.3 urllib3==1.26.7 virtualenv==20.4.2 wcwidth==0.1.9 websocket-client==0.59.0 wrapt==1.12.1 zipp==3.6.0 -
deploying https://github.com/codervivek/deep_player on my localhost [closed]
following error pops up for django: [Errno 11001] getaddrinfo failed Request Method: POST Request URL: http://127.0.0.1:8000/upload/ Django Version: 3.2.12 Exception Type: gaierror Exception Value: [Errno 11001] getaddrinfo failed Exception Location: C:\Program Files\Python37\lib\socket.py, line 752, in getaddrinfo Python Executable: C:\Program Files\Python37\python.exe Python Version: 3.7.9 Python Path: ['C:\Users\User_Name\OneDrive\Interview\Academics\University\Under_Graduation\BE\SEMESTER_8\BE_PROJECT\deep_player', 'C:\Program Files\Python37\python37.zip', 'C:\Program Files\Python37\DLLs', 'C:\Program Files\Python37\lib', 'C:\Program Files\Python37', 'C:\Users\Ayush Adhikari\AppData\Roaming\Python\Python37\site-packages', 'C:\Program Files\Python37\lib\site-packages'] Server time: Tue, 08 Mar 2022 16:14:22 +0000 -
How to exclude field conditionaly?
I need to exclude id_from_integration if Company.integration_enabled == False. My resource and model: class Company(models.Model): integration_enabled = models.BooleanField() class Report(models.Model): company = models.ForeignKey(Company) class ReportResource(resources.ModelResource): ... class Meta: model = Report fields = ('name', 'id_from_integration', ...) -
Cannot force Postgresql to accept SSL connections only
Here's my current config: postgresql.conf: ssl = on ssl_cert_file = '/etc/postgresql/12/main/fullchain.pem' ssl_key_file = '/etc/postgresql/12/main/privkey.pem' pg_hba.conf: local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. local replication all peer host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5 # IPv4 remote connections: hostssl all all 0.0.0.0/0 md5 # IPv6 remote connections: hostssl all all ::/0 md5 Still, my Django application is able to migrate database changes with and without 'OPTIONS': {'sslmode': 'require'} and that is not what I want. I want Postgresql to reject non-ssl connections and I don't know what I'm missing here. P.S: Certificate is valid and created by certbot. -
How to create retro load file in django
def create_workflow_status_node_merchant_financing_135_handler(apps, _schema_editor): workflow = Workflow.objects.get(name=WorkflowConst.MERCHANT_FINANCING_WORKFLOW) WorkflowStatusNode.objects.get_or_create( status_node=135, handler=MerchantFinancing135Handler.__name__, workflow=workflow ) class Migration(migrations.Migration): dependencies = [] operations = [ migrations.RunPython(create_workflow_status_node_merchant_financing_135_handler, migrations.RunPython.noop), ] like this how to create a retroload file in django .for adding data in to database -
Adding Like Functionality to an image
New to Django any help will be appreciated. Thank you. I am trying to add a likes feature to my photos app like Instagram and even show the number of like at the moment I am getting a 'Page not found error'. I sure my logic is not working too models.py Photo Model class Photo(models.Model): img = models.ImageField(upload_to='images') caption = models.CharField(max_length=250, default='Caption here') date_posted = models.DateTimeField(default=timezone.now) owner = models.ForeignKey(User, on_delete=models.CASCADE) Likes Model class Like(models.Model): like = models.IntegerField() image = models.ForeignKey(Photo, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, default=20) Like Button in a form PS. I was using I was using class based views here hence the use of 'object' <form action="{ url 'like-photo' object.id }" method="POST"> {% csrf_token %} <button class="btn btn-primary" type="submit" name="img_id" value="{{ object.id }}">Like</button> </form> views.py I want to be redirected to photo-detail view def LikeView(request, pk): photo = get_object_or_404(Photo, id=request.POST.get('img_id')) photo.like.add(request.user) return HttpResponseRedirect(reverse('photo-detail', args=[str(pk)])) urls.py urlpatterns = [ ... path('like/<int:pk>/', LikeView, name='like-photo'), ] -
hi three i have been in trouble whnever i try to do "docker-compose build" ,,,
actually i was trying to make image by docker so i executed "docker-compose build" on terminal but i failed,, here's my failed informations, if you want to know more about other impormations, let me know it, i will add it as soon as possible! #11 70.18 warning: build_py: byte-compiling is disabled, skipping. #11 70.18 #11 70.18 running build_ext #11 70.18 building '_cffi_backend' extension #11 70.18 creating build/temp.linux-x86_64-3.9 #11 70.18 creating build/temp.linux-x86_64-3.9/c #11 70.18 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -D USE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/local/include/python3.9 -c c/_cffi_backend.c -o build/temp.linux-x86_64-3.9/c/_cffi_backend.o #11 70.18 c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory #11 70.18 15 | #include <ffi.h> #11 70.18 | ^~~~~~~ #11 70.18 compilation terminated. #11 70.18 error: command '/usr/bin/gcc' failed with exit code 1 #11 70.18 [end of output] #11 70.18 #11 70.18 note: This error originates from a subprocess, and is likely not a problem with pip. #11 70.19 error: legacy-install-failure #11 70.19 #11 70.19 × Encountered error while trying to install package. #11 70.19 ╰─> cffi #11 70.19 #11 70.19 note: This is an issue with the package mentioned above, not pip. #11 70.19 hint: See above for output from the failure. ------ failed … -
How to rewrite django admin login view?
This is my custom login view where user can only login if their email verified. I also added two step verification in my login view. is there any way where I can implement this view in django admin login ? def login_view(request): username = None password = None two_factor = None if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') otp = request.POST.get('auth_code') user = authenticate(request, username=username, password=password) User = get_user_model() if user is not None and user.is_active: user_mail = user.userprofile.filter( user=user, email_confirmed=True) two_factor = user.userprofile.filter( user=user, two_factor=True) for i in two_factor: ....my two factor code if user_mail and two_factor: if secret_code == otp: login(request, user) -
I have ran the DJango project in my local machine windows 10 getting the below errors
Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "env\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "env\lib\site-packages\django\core\management_init_.py", line 345, in execute settings.INSTALLED_APPS File "env\lib\site-packages\django\conf_init_.py", line 83, in getattr self.setup(name) File "env\lib\site-packages\django\conf_init.py", line 70, in _setup self.wrapped = Settings(settings_module)enter code here File "env\lib\site-packages\django\conf_init.py", line 177, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 850, in exec_module File "", line 228, in _call_with_frames_removed File "settings\django.py", line 5, in from base.settings.django import * -
I am getting Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I am building an e-com site using the Django framework. to make it more efficient I am using javascript here and there. So the problem occurs at the checkout page and specifically if a user is logged in. On my site, a user can shop even if he is not logged in as a guest user. so if a guest user is going to the checkout page he can submit the process and make payment without running into any issues. But when a user is logged in the checkout page returns the error on load! even before writing anything into the form. I am attaching the checkout page code here for you guys to give it a good look. I have tried to debug it as well as run into the built-in code snippets here. It works fine without any issues {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="Form-control" type="text" name="name" placeholder="Name"> </div> <div class="form-field"> <input required class="Form-control" type="email" name="email" placeholder="Email"> </div> </div> <div id="shipping-info"> <hr> <p>shipping-info</p> <hr> <div class="form-field"> <input required class="Form-control" type="text" name="address" placeholder="Street"> </div> <div class="form-field"> <input … -
Django what function is called at the moment the queryset is evaluated?
I want to override the behavior (add a small step) before the queryset is evaluated. For write/read querys like update, get, I can just override the update/get method. However, I wonder what function is triggered when you do list(queryset), or len(queryset). What funciton is triggered here, and how should I override this? -
wagtail 'NoneType' object has no attribute 'model'
I have install a fresh wagtail when I try to create a page I'm getting error : 'NoneType' object has no attribute 'model' My class is : class CategoryPage(Page): description_meta = models.CharField(max_length=500, null=True, blank=True) template = models.CharField(max_length=500, null=True, blank=True, default='_nixaTemplate/category/default.html') image = models.ImageField(_("Image"), upload_to="img/category/", blank=True, null=True) display = models.BooleanField(_("Display Post"), default=False ) content_panels = Page.content_panels + [ FieldRowPanel([ FieldPanel("description_meta", classname="col-12 col12"), FieldPanel("template", classname="col-12 col12"), ImageChooserPanel("image", classname="full"), ]), ] when I try to create Category Page I get that message