Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to run Selenium tests for a Django app using Selenium docker services in GitLab-CI
Whenever I run my Selenium tests in GitLab-CI, I get a WebDriverException from Selenium. I've tried two different set ups, both of which run fine locally using Docker, but neither of which work in CI. Using Selenium Grid in CI, when I try to set up the remote driver I get the message Error forwarding the new session Empty pool of VM for setup Capabilities {acceptInsecureCerts: true, browserName: firefox, marionette: true, moz:firefoxOptions: {args: [-headless]}} Using standalone Firefox, I seem to be able to set up the remote driver, but when I run the tests I get Reached error page: about:neterror?e=dnsNotFound&u=http%3A//runner-dzqg9xmx-project-57-concurrent-0%3A38153/news/&c=UTF-8&f=regular&d=We%20can%E2%80%99t%20connect%20to%20the%20server%20at%20runner-dzqg9xmx-project-57-concurrent-0. If anyone can point me at a working GitLab-CI configuration that uses Selenium docker images as services, or tell me what's wrong with my configurations below, I'd be grateful. Using Selenium Grid Selenium Grid would be my preferred method because it would make it easier for us to run tests in multiple browsers. base/tests/utils.py I set up my tests using this base class. class SeleniumTestCase(LiveServerTestCase): host = os.environ('HOSTNAME') @classmethod def setUpClass(cls): super().setUpClass() options = webdriver.FirefoxOptions() options.headless = True cls.browser = webdriver.Remote( 'http://selenium-hub:4444/wd/hub', webdriver.DesiredCapabilities.FIREFOX, options=options, ) .gitlab-ci.yml test: stage: test image: $CMS_IMAGE_NAME variables: HUB_HOST: selenium-hub HUB_PORT: 4444 START_XVFB: 'false' services: - … -
My worker Celery works in localhost but not in heroku
I set up the workers on my localhost (windows) and it works perfectly but on heroku it doesn't work. I'm using Django, Reddis and Celery. celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eco_gestao.settings') app = Celery('eco_gestao') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Procfile: web: gunicorn eco_gestao.wsgi --log-file - My problem i think is here-> worker: celery worker --app=eco_gestao.celery settings: CELERY_RESULT_BACKEND = 'django-db' # CELERY_BROKER_URL = 'redis://localhost:6379' REDIS_URL='redis://' BROKER_URL = os.environ.get("REDISCLOUD_URL", "django://") CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' -
an unlimited number of pictures for each list
I want to solve the problem for an unlimited number of pictures for each list. Whenever I want to put the pictures on the list, I get only one picture or type several fields for the picture.How is it class Listing(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) class Photo(models.Model): image = models.ImageField(default="default.png", blank=True, null=True, upload_to="photos/%Y/%M/%D") listing = models.ForeignKey(Listing, related_name='Photos', on_delete=models.CASCADE) -
Filtering for entities that have equal related entities
I'd like to build a queryset that finds balls with equal attributes. 2 models exist: Ball | id | name | +----+----------+ | 1 | Neptun | | 2 | Speedy | | 3 | Highway | BallAttribute | id | ball_id | key | value | +----+--------------------+-------+ | 1 | 1 | color | blue | ← | 2 | 1 | size | xxl | ← | 3 | 2 | color | blue | | 4 | 2 | size | xl | | 5 | 3 | color | blue | ← | 6 | 3 | size | xxl | ← The equal attributes are marked with a ←. So in the end, I'd like to get the balls Neptun and Highway in return (Speedy is not selected because size is different, and all attributes are required to be equal). Please keep in mind that the required attribute keys and values are not known, so solutions like these are not possible: Ball.objects.filter( balls__key="color", balls__value="blue" ).filter( balls__key="size", balls__value="xxl" ) How can I build such a queryset with Django? -
Why HTTP response returns 2 codes
This is a django project, a very simple one indeed, i got a question about the response code of the HTTP header. I am running it on localhost. # URL Patterns in the Project folder. urlpatterns = [ path('blog/', include(blog.urls)), ] # URL Patterns in the blog folder. urlpatterns = [ path('index/', blog.views.index, name='blog_index'), path('about/', blog.views.about, name='blog_about') ] Everything runs fine but the shell response is: [21/Aug/2019 21:15:54] "GET /blog/index/ HTTP/1.1" 200 144 The question is about the HTTP Header response 200 144 After playing with urllib a bit i used to think that headers send only 1 response code 200 OK For some reason django sends 2 codes 200 OK 144 Corresponds with HTTP 404. # Reference https://developer.twitter.com/en/docs/basics/response-codes.html -
Django Getting Static Files
I am exhausted to link bundle.js in my template. This is my Django DIR client │ ├── components │ │ ├── about.js │ │ ├── App.js │ │ ├── contact.js │ │ ├── form.js │ │ ├── home.js │ │ └── table.js │ ├── index.html │ ├── index.js │ ├── postReducer.js │ ├── redux │ │ ├── component │ │ │ └── postAction.js │ │ └── reducers │ │ ├── postReducer.js │ │ └── rootReducer.js │ └── style.scss ├── dist │ ├── bundle.js │ ├── index.html │ └── main.js ├── package.json ├── package-lock.json ├── README.md ├── requirements.txt My bundle.js file is inside dist folder, I loaded static in template like this : {% load static %} {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Django & React Starter</title> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> </head> <body> <script src="{% static "bundle.js" %}"></script> </body> </html> and this is my settings.py fiel STATIC_URL = os.path.join(os.path.dirname(BASE_DIR), "dist") + '/' I dont know why it is not getting my bundle.js file. can anyone help me to fix this? -
How to troubleshoot Django web app connection to Teradata?
Can anyone please help me to troubleshoot this? A new Unix server is setup as test environment for an existing production django web app/server. On the test server I can pull data using bteq, but the web app doesn't (i.e. the json data doesn't populate. Everything else looks fine). All the configuration/settings are the same as the production server. I tried below steps in the production server and it returned with data, but in the test server I got the error. python manage.py shell >>> from project_web.shared_functions import teradata_con >>> import json >>> import pandas as pd >>> sql = """select distinct rgn_num, rgn_nm from RLDMPROD.SITE_HIER;""" >>> pd.read_sql(sql, teradata_con()) Error: python: libltdl/ltdl.c:1197: try_dlopen: Assertion `filename && *filename' failed. Aborted (core dumped) -
Custom 404 and 500 pages in django with -> DEBUG = True
I want to present the sample of my website to a client and it isn't quite finished yet but it is very important for me to hide the errors and to not show my codebase which django does if a server error occurs in development mode. Like so - Django depicting what went wrong Also I cannot turn DEBUG = False as in that case the media files aren't displayed as they are currently being served locally. Which won't be served if DEBUG = False. So is there a way to serve media files locally with DEBUG = False or to display custom 404 and 500 pages with DEBUG = True. -
Django Model is not JSON serializable
Im trying to return a dictionary of Django models in JSON format. I have tried serializers, model_to_dict, json.dump and can't seem to get it working. a small snippet of the code: queryset = (my_object.objects.all()) test_dict = {} for x in queryset.iterator(): m = some_value_i_calculate test = model_to_dict( x ) test_dict[m] = x sorted_dict = dict(sorted(test_dict.items())) return json.dumps(sorted_dict, ensure_ascii=False) the dictionary I create is a {int:object, int:object, int:object, ....} I want this to be returned as the response. I keep getting issues such as "TypeError: Object of type object is not JSON serializable" -
Why does Django run server hang when using docker-compose up?
When I run docker-compose up, Django starts to load. It goes thru the about four steps. After it does a system check and identifies (0 issues), it stops at displaying the current date and time. This is the point where it just hangs. Nothing else happens. C:\Users********\Desktop\code\hello>docker-compose up Creating hello_web_1 ... done Attaching to hello_web_1 web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | System check identified no issues (0 silenced). web_1 | August 21, 2019 - 17:33:11 When I do docker-compose down, the system exits Gracefully(lol). Then I run docker-compose logs and it shows the correct info: C:\Users********\Desktop\code\hello>docker-compose logs Attaching to hello_web_1 web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | System check identified no issues (0 silenced). web_1 | August 21, 2019 - 17:36:44 web_1 | Django version 2.2.3, using settings 'hello_project.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | System check identified no issues (0 silenced). web_1 | August 21, 2019 - 17:55:22 web_1 | Django version 2.2.3, using settings 'hello_project.settings' web_1 | Starting … -
creating navigation based on models with foreign keys
I'm having trouble finding a solution, or even where to look for a solution to this, and am a beginner with Django. I'd like to create a dynamic navigation for a project I'm working on. from django.db import models from tinymce import models as tinymce_models class League(models.Model): name = models.CharField(max_length=50) description = tinymce_models.HTMLField() crest = models.ImageField(upload_to='league-crests/', default=0) def __str__(self): return self.name class Club(models.Model): name = models.CharField(max_length=50) description = tinymce_models.HTMLField() crest = models.ImageField(upload_to='club-crests/', default=0) league = models.ForeignKey(League, on_delete=models.CASCADE, default=0) def __str__(self): return self.name Basically I'd like a top level nav called "Leagues" with a dropdown list of all leagues saved in the database. For each league i'd like a second level dropdown with the clubs in each league. I've been googling around but haven't found anything pointing me in the right direction. -
Looking for an API for user authentication for Django
Is there any ready to use applications/API available for user authentication in Django? I am looking for one that has not only username, email and password but takes other fields(say, date of birth, website, image) too during user registration process. -
Django routing - The empty path didn't match any of these
Very basic question and I was surprised I wasn't able to find an answer. I'm just starting looking at django and did an out-of-box intallation. Created a project and created an app. The default content of urls.py is very simple: urlpatterns = [ path('admin/', admin.site.urls), ] And if I open the django site home page, I get the content with a rocket picture. However, like I said, I have created another app in the project, let's say called 'bboard'. And I have created a simple 'hello world' function in bboard/views.py def index(request): return HttpResponse('Hello world') to enable it for access through browser, I have modified the original urls.py file in the following way: from bboard.views import index urlpatterns = [ path('admin/', admin.site.urls), path('bboard/', index), ] This way I can access localhost:port/admin and localhost:port/bboard URLs, but if I try to open the home page with localhost:port now, I get Page not found error. Using the URLconf defined in samplesite.urls, Django tried these URL patterns, in this order: admin/ bboard/ The empty path didn't match any of these. if I comment out the second item in urlpatterns list, everything works. So why does the additional pattern impact this and what needs to … -
Django: How to fix NoReverseMatch for PasswordChangeDoneView?
i trying do use and understand the Django authentication system. So far everything works. I can register as a new user, login, logout, dashboard except the PasswordChangeDoneView or my success View did not work. Thats the error message after i changed my password. ...//127.0.0.1:8000/account/change_password/ NoReverseMatch at /account/change_password/ Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/account/change_password/ Django Version: 2.2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Exception Location: E:\coding\proj\farm_env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: E:\coding\proj\farm_env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['E:\\coding\\proj\\farm', 'E:\\coding\\proj\\farm_env\\Scripts\\python37.zip', 'E:\\coding\\proj\\farm_env\\DLLs', 'E:\\coding\\proj\\farm_env\\lib', 'E:\\coding\\proj\\farm_env\\Scripts', 'c:\\python app\\python37-32\\Lib', 'c:\\python app\\python37-32\\DLLs', 'E:\\coding\\proj\\farm_env', 'E:\\coding\\proj\\farm_env\\lib\\site-packages'] Server time: Wed, 21 Aug 2019 16:57:21 +0000 account / urls.py (its my main app) from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name='account' urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='account/logout.html'), name='logout'), path('change_password/', auth_views.PasswordChangeView.as_view(template_name='account/password_change.html'), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='account/password_change_done.html'), name='password_change_done'), path('register/', views.register, name='register'), path('dashboard/', views.dashboard, name='dashboard') ] This is my password change site with a link to password_change_done account / templates / account / password_change.html {% extends 'base.html' %} {% load static %} {% block custom_css %} <link … -
How to show objects from models by ForeignKey
I'm trying to show objects from Section models to home page.What do I need to do? I have tags(mechanism) on site which working absolutely identical. But Section objects don't showing models.py tags = models.ManyToManyField('Tag', blank=True,related_name='audio') section = models.ForeignKey('Section', blank=True,related_name='audio', on_delete=models.CASCADE, null=True) views.py def tag(request,slug): tags = Tag.objects.get(slug=slug) template = 'home/tags.html' return render(request, template, {'tags': tags}) def main(request): tags = Section.objects.all() template = 'home/home-page.html' return render(request, template, {'tags': tags}) html-file {% for content in tags.audio.all %} <img id="book__img" src="/media/{{content.img}}" alt=""> <p class="text__for__book">{{content.title}}</p> {% endfor %} Html tag file(tag.html) show all good. But when i'm trying to do it on main page it don't work -
Django tutorial part 3 - bad link or directory structure
I'm doing the tutorial at: https://docs.djangoproject.com/en/2.2/intro/tutorial03/ It says to make a templates directory under the polls application (which is under 'mysite'), such that I have a tree that looks like this: mysite settings.py urls.py wsgi.py polls migrations templates polls index.html views.py models.py admin.py apps.py tests.py urls.py manage.py In the template they want me to write: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available</p> {% endif %} The page loads, but if I click the link it wants to take me to 'localhost:8000/polls/polls/1' and that does not exist. There are one too many '/polls' Question is, was the template directory supposed to go one level higher, under mysite? or should be not have '/polls' in the hyperlink? Despite their little explanation, I do not understand why we'd want to have 'polls/templates/polls'. It seems to me that we can tell it is polls if it is under polls already. -
Nginx Serve React build and proxy_pass Django Rest api server
domain.conf looks like this I am proxy passing the Django API server using Nginx. Nginx uses letsencrypt SSL certificates and is currently listening on port 80 and 443. Nginx perfectly serves the react build files while accessing the Django API using Axios in react app results in 502 bad gateway. Axios is trying to access "/api/v1/" as baseURL. server { listen 80; listen [::]:80; location /.well-known/acme-challenge/ { root /var/www/certbot; } return 301 https://example.com$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # redirects www to non-www. wasn't work for me without this server block return 301 https://example.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name example.com www.example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location / { root /var/www/frontend; try_files $uri $uri/ /index.html; } location /api/ { proxy_pass http://localhost:8000; proxy_redirect default; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } part of docker-compose.yml looks like this backend: build: context: . dockerfile: dockerFiles/backend/DockerFile tty: true ports: - "8000:8000" expose: - 8000 volumes: - ./backend:/backend env_file: - backend/.env depends_on: - db frontend: image: node:latest command: sh start.sh working_dir: /frontend tty: true volumes: … -
Django Webpack Loader Breaking Vue Router Links
Short Version When I visit localhost my django/vue app renders fine. But when I click into a link, rather than being brought to localhost/about I'm brought to http://localhost/http:/0.0.0.0:8080/about because of my webpack and vue.config.js settings. Details I have an application running (in docker-compose) Django on the backend and Vue on the frontend. The app uses django-webpack-loader and webpack-bundle-tracker to render the application in Django. # Django settings.py WEBPACK_LOADER = { "DEFAULT": { "CACHE": DEBUG, "BUNDLE_DIR_NAME": "/bundles/", "STATS_FILE": os.path.join(FRONTEND_DIR, "webpack-stats.json"), } } # Django urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path from django.views.generic import TemplateView urlpatterns = [ path("admin/", admin.site.urls), re_path("^.*$", TemplateView.as_view(template_name="application.html"), name="app"), ] if settings.DEBUG: urlpatterns = ( urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ) <!-- Template --> {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="/favicon.ico"> <title>My Website</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons"> </head> <body> <noscript> <strong>We're sorry but this application doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"> <app></app> </div>{% render_bundle 'app' %}<!-- built files will be auto injected --> </body> </html> // vue.config.js const BundleTracker … -
Django Tempus Dominus TimePicker Format
When I submit a form after picking a time using the django-tempus-dominus TimePicker widget, I receive no error, but the form is not saved to the database, and does not show up in the admin page. I receive a visual browser indication that something is incorrect with my TimeFields. I can successfully create a new form from the admin page, and only see the issue when submitting from my form page. I'm not sure whether this is an issue with the 'format' of the TimePicker widget in my forms.py, an issue with my TIME_INPUT_FORMATS in my settings.py, or something else. If I use a DateTimeField with a DateTimePicker widget for start_time and end_time, and change the 'format' in my widget to 'YYYY/MM/DD hh:mm: A', instead of using a TimeField with a TimePicker widget, the form works correctly, and when submitted, can be viewed from the admin page. In my settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Kentucky/Monticello' DATETIME_INPUT_FORMATS = ['%Y/%m/%d %I:%M %p', ] DATE_INPUT_FORMATS = ['%Y/%m/%d', ] TIME_INPUT_FORMATS = ['%I:%M %p', ] USE_I18N = True USE_L10N = False USE_TZ = True In my models.py: start_time = models.TimeField( verbose_name="Start Time", help_text="Time the issue first occurred.") In my forms.py: from django import forms … -
Getting Django channel access in Celery task
I have a Django app that's using channels to monitor a WebSocket to kick off backend tasks in Celery. It currently sleeps for a given amount and then returns true. The problem is I don't know how to get access to the WebSocket from within the celery task so I can notify the UI once it's done. celery==4.3.0 channels==2.2.0 Django==2.2.4 django-celery-results==1.1.2 djangorestframework==3.10.2 my tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task import time @shared_task def gotosleep(timeInSecs): time.sleep(timeInSecs) return True My consumer.py from channels.generic.websocket import WebsocketConsumer import json from access.tasks import gotosleep class AccessConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] if message.isnumeric() == True: print("------------------------------------------------------") print(message) gotosleep.delay(int(message)) self.send(text_data=json.dumps({ 'message': 'We are dealing with your request' })) else: self.send(text_data=json.dumps({ 'message': 'Give me a number' })) Any Ideas? Many Thanks -
How to call a Python script in a Django server from JavaScript?
Salut! I have a HTML running properly in a Django server, also I have a function in a Python file which send an e-mail. I would like to execute this function when an submit input is clicked. So, how can I call this function using JavaScript? I've read about using AJAX, but I think that this could be code easily. Am I wrong? -
How I can show http 404 with djangofilterbackend?
django rest framework is showing http 202 ok when I set a wrong value and I want to show http 404 on the api django rest framework, when set a wrong value in djangofilterbackend but I don't know how to implement it. my views.py: from rest_framework import viewsets from .models import Producto from .serializers import ProductoSerializer from django_filters.rest_framework import DjangoFilterBackend class ProductoViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = ['Codigo_Producto'] queryset = Producto.objects.all() serializer_class = ProductoSerializer my serializers.py: from .models import Producto from rest_framework import serializers, viewsets class ProductoSerializer(serializers.ModelSerializer): Nombre_Producto = serializers.SerializerMethodField class Meta: model = Producto fields = [ 'id', 'Nombre_Producto', 'Codigo_Producto', 'Precio_sugerido', 'stock', ] def get_Producto_name(self,obj:Producto): return obj.Producto.get_full_name() urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework import routers from GestionadorApp.views import ProductoViewSet # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register('Producto', ProductoViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('api/', include(router.urls)), path('admin/', admin.site.urls), ] -
Is there a way to get around 'NoneType' object has no attribute 'DoesNotExist'
I am trying to render the same page "billing" but with different variables depending on if the user have an active subscription or not. The problem is that I get 'NoneType' object has no attribute 'DoesNotExist' when I try to make an exception. I have tried to use if membership is False: return redirect without success. @login_required(login_url="/login") def billing(request): membership = False cancel_at_period_end = False user = request.user pay = payment.objects.filter(user=user).last() if request.method == 'POST': stripe.api_key = settings.STRIPE_SECRET_KEY #attempting cancelling subscription subscription = stripe.Subscription.retrieve(pay.stripe_subscription_id) subscription.cancel_at_period_end = True pay.cancel_at_period_end = True cancel_at_period_end = True pay.paid = False subscription.save() pay.save() messages.success( request, "Thankyou, for using our services Your membership will run to the end of your billing cycle.") else: try: if pay.paid: membership = True if pay.cancel_at_period_end: cancel_at_period_end = True except pay.DoesNotExist: membership = False return render(request, 'billing.html', {'membership': membership, 'pay': pay, 'cancel_at_period_end': cancel_at_period_end}) Traceback: File "/Users/iamsuccessful/totdapp-2/totdapp/views.py" in billing 94. if pay.paid: During handling of the above exception ('NoneType' object has no attribute 'paid'), another exception occurred: File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, … -
query database via foreignkey
I'm querying database: def get_queryset(self): queryset = {'test_suites': TestSuite.objects.filter(user__id=self.request.user.id), 'username': self.request.user)} return queryset from this model field: class TestSuite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... ... User here is the auth User model from Django. I'm trying to filter data from TestSuite by its user's id. Keep getting error: Cannot resolve keyword 'user' into field -
How to identify the source of a NoReverseMatch error in Django?
I am learning the django framework and want to create a webstore where User's who are designated as 'artists' can post to the webstore. To avoid confusion thcWebsite is the PROJECT NAME. thcStore is an APP in the project! I am receiving the following error when trying to load localhost:8000/thcStore/ NoReverseMatch at /thcStore/ Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['thcStore/(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] Request Method: GET Request URL: http://localhost:8000/thcStore/ Django Version: 2.2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['thcStore/(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] Exception Location: C:\Users\TAHAAR~1\Envs\MYPROJ~1\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 the following is the error Traceback Environment: Request Method: GET Request URL: http://localhost:8000/thcStore/ Django Version: 2.2.2 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'cart.apps.CartConfig', 'orders.apps.OrdersConfig', 'accounts', 'payment.apps.PaymentConfig', 'thcStore'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Taha Arif\Desktop\Web Development\Personal Website\django_THC\thcWebsite\templates\base.html, error at line 51 Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['thcStore/(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] 41 : <div class="dropdown-menu" aria-labelledby="navbarDropdown"> 42 : <a class="dropdown-item" href="{% url 'accounts:user_profile' user.display_name %}">Profile</a> 43 : <a class="dropdown-item" href="#">Settings</a> 44 : <a class="dropdown-item" href="{% url 'accounts:thanks' %}">Logout</a> 45 : </div> 46 : {% …