Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Invalid field name(s) given in select_related" when searching one-to-many relationship
my apologies as I am new to Django and this seems like a "Django 101" type problem, but I just can't seem to get it to work. I have a Django model for "Services" which has a related model for "Keywords" via a one-to-many relationship. I'm simply trying to return the related keywords when I query the services, but when I run the view, I keep getting the error: Invalid field name(s) given in select_related: 'keyword'. Choices are: (none) My models are as follows: from uuid import uuid4 from django.db import models from django.utils.text import slugify from blog.models import Tag, Category class Service(models.Model): id_service = models.UUIDField(primary_key=True, default=uuid4, editable=False) created_ts = models.DateTimeField(auto_now_add=True) updated_ts = models.DateTimeField(auto_now=True) service_name = models.CharField( db_index=True, max_length=50, blank=False, null=False ) slug = models.CharField(max_length=50, unique=True) font_awesome_icon = models.CharField(blank=True, null=True, max_length=30) service_image = models.ImageField( blank=True, null=True, upload_to="images/services", max_length=None ) service_page_image = models.ImageField( blank=True, null=True, upload_to="images/services", max_length=None ) service_description = models.TextField(blank=False, null=False) service_description_brief = models.CharField( max_length=200, blank=False, null=False ) rank = models.IntegerField() def save(self, *args, **kwargs): self.slug = slugify(self.service_name) super(Service, self).save(*args, **kwargs) def __str__(self): return self.service_name class ServiceKeyword(models.Model): id_servicekeywords = models.UUIDField( primary_key=True, default=uuid4, editable=False ) created_ts = models.DateTimeField(auto_now_add=True) updated_ts = models.DateTimeField(auto_now=True) keyword = models.CharField(max_length=60, blank=False, null=False) service = models.ForeignKey(Service, on_delete=models.CASCADE) def … -
react + django deploy in heroku and image isn't coming through
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'build/static') STATICFILE_DIRS = [os.path.join( BASE_DIR, 'build/static')] STATICFILES_STORGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media/images") WHITENOISE_ROOT = os.path.join(BASE_DIR, "media") -
Django REST API - Is it possible to create one routers.py per app?
Hello I've setup a Django project that includes a REST api, so far this is the project structure: django │ ├───apps │ ├───store │ | admin.py │ | apps.py │ | models.py │ | serializers.py │ | tests.py │ | urls.py │ | views.py │ | viewsets.py │ | __init__.py │ ├───accounts │ admin.py │ apps.py │ models.py │ serializers.py │ tests.py │ urls.py │ views.py │ viewsets.py │ __init__.py ├───main asgi.py router.py settings.py urls.py wsgi.py __init__.py Inside main/urls.py I have something like this (which is setting up the API url endpoint by including the routers.py): from django.contrib import admin from django.urls import path, include from .router import router urlpatterns = [ # Default urls path('admin/', admin.site.urls), path('api/', include(router.urls)), path('', include('apps.store.urls')), ] Inside the main/routers.py I am registering all my viewsets for all the project: from rest_framework import routers from apps.store.viewsets import ItemViewSet, PurchaseViewSet, ReceiptViewSet from apps.accounts.viewsets import ProfileViewSet, TransactionViewSet router = routers() router.register('items', ItemViewSet) router.register('purchases', PurchaseViewSet) router.register('receipts', ReceiptViewSet) router.register('profiles', ProfileViewSet) router.register('transactions', TransactionViewSet) Everything works well but my issue is that in this routers.py I will have to register all the ViewSets for the whole project, I'm guessing this doesn't help with modularity and can make this file big and … -
How to create a link in a Django model that points to another model?
Hello I have 2 models: class Classroom(models.Model): name = models.CharField(max_length=255) description = models.TextField() price = models.FloatField() def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) age = models.IntegerField() classroom = <---- How to link to classroom here def __str__(self): return str(self.name) + " - " + str(self.surname) How do I create a link so I can store which classroom each student belongs to? Many thanks! -
how to get the lastest modified file in folder python django
i have this code, first i get the image from a input and then i create a copy in folder in this case 'tareas', then i need to print the name of that image, i can create the copy successfully but i can't get the name of the copy. if request.method == "POST": uploaded_file = request.FILES['imagen'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) caminodelarchivo = "C:/Users/Usuario/Documents/Django/Proyecto/imagenes/tareas" files = glob.glob(caminodelarchivo) ultimoarchivo = max(files, key=os.path.getctime) print ("El nombre es: ", ultimoarchivo) -
django receives wrong parameters
I developed a test project using Django. It works well locally, but when I deploy to the build server, the parameters I receive are wrong. I have an APP in this project. He receives a URL as a parameter and processes it. However, when I print the incoming parameters on the server, I find that a missing "/" causes the APP to fail to process the URL. For example, I type "https://v.douyin.com/GSW2Ab/" in the browser, and the server prints "https: /v.douyin.com/GSW2Ab/". My Django project is deployed with Nginx + uwsgi. Is this a problem with nginx? client input server views.py -
How and where to deploy a Python/Django app
So I am self-learning Django and Python in anticipation for future projects at my workplace. What are the typical platforms / servers (both free and licensed) that businesses usually use to deploy apps written in Python? I have been using R Shiny and I have deployed my Shiny apps on Shinyapp.io (free) and RSConnect (licensed). What are the equivalents to these two on Python/Django side? -
Pygame for mobile development
It is possible to create or develope mobile games using pygame if not what python framework should I use. One more thing should I need to learn 2 to 4 framework of python or any Programming language. -
Django installation dependency errors after rolling back to Python 3.7.6
I'm working my way through the tutorials in William S. Vincent's Django for Beginners. Everything worked fine until Chapter 4 (the Message Board app), when like a nOOb I ran into the known bug that causes Django's web server to crash when attempting to serve /admin/ using Python 3.7.* in pipenv. So, I upgraded Python to 3.8.2, and it still didn't work. So I foolishly deleted 3.8.2 and rolled back to 3.7.6, and now I can't install Django at all with pipenv due to a variety of pipenv.exceptions.ResolutionFailure statements. I've reinstalled Python 3.7.6 AND 3.8.2, pip3, pipenv and Django (through Anaconda as well as outside of it), but I'm still getting the same litany of errors that won't let Django be installed in my virtual environment. Using pipenv lock --pre --clear doesn't fix it. The telling line is "ERROR: No matching distribution found for django-3-0" Does anyone have any idea how to resolve this or what packages I need to uninstall/reinstall? Thanks much! :) -
How to add Javascript into Django?
I recently got my static files working for my project directory. I wrote a separate file with a javascript function called my function. I have a in html that calls a function in my javascript, but chrome is returning a function is not defined error. Does anyone know how to resolve this? {% load static %} {% block content%} <h1 id="change" onclick="myFunction()"> hi! </h1> {% endblock %} function myFunction(){ var count = 0; console.log(count); } Chrome Error (index):55 Uncaught ReferenceError: myFunction is not defined at HTMLHeadingElement.onclick ((index):55) -
static error when giving the command "python manage.py collectstatic"
When I give the command "python manage.py collectstatic" it gives the following problem "0 static files copied to '/home/leonard368a/leonard368a.pythonanywhere.com/static', 119 unmodified." does anyone have any way to solve this? -
django how to save html with img tag to database
I am a fresh graduate and currently writing my personal blog and want to do all the features by myself. I have a post.html that dynamically displays a specified post content based on the post_id. This template will load the data (html format) that I save in the database. In the database, I save the post content as html. When I load the post content, I use {{ post.post_content | safe }} in the template.html. It works fine with text. I can get it display as I wanted. However, I fail to get the img display. The img tag in my html looks like this: <a href="{% static 'assets/img/blog/post1.png'%}" class="image-popup"> <img src="{% static 'assets/img/blog/post1.png'%}" alt="Post Image"> </a> Django fail to get the image url so the image cannot be displayed. May I ask are there solutions for me to do this? Except asking me to put the actual/direct image url to the field. Thank you for your help. -
Django forms how to display related data in an inner form
I am struggling with Django forms. I have the following model.py: class Property(models.Model): address=models.ForeignKey("Address", on_delete=models.CASCADE) portfolio = models.ForeignKey("portfolios.Portfolio", on_delete=models.CASCADE) class Meta: verbose_name_plural = "Properties" class PropertyImage(models.Model): property = models.ForeignKey("Property", on_delete=models.CASCADE) image = models.ImageField(upload_to = property_image_upload_to) def __str__(self): return self.image.url class PropertyDocument(models.Model): property = models.ForeignKey("Property", on_delete=models.CASCADE) document = models.FileField() class Address(models.Model): line1 = models.CharField(max_length=100) line2 = models.CharField(max_length=100, null=True, blank=True) line3 = models.CharField(max_length=100, null=True, blank=True) post_code = models.CharField(max_length=7) town = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100) When adding/updating a property, I want the form to show the form for related objects like the address, documents/images instead of the select list's that appear in forms - I want to be able to add/edit the related data. My view.py file class PropertyCreate(CreateView): model = Property fields = "__all__" success_url = reverse_lazy('Property_list') class PropertyUpdate(UpdateView): model = Property fields = "__all__" success_url = reverse_lazy('Property_list') urls.py from . import views app_name = 'properties' urlpatterns = [ path('<int:portfolio_id>/<int:pk>/edit', views.PropertyUpdate.as_view(), name='property_edit'), path('<int:portfolio_id>/create', views.PropertyCreate.as_view(), name='property_new'), ] I've read about inlineformset_factories and inlineformset's etc, but is this the best choice for my scenario? If so, I can't figure out how to show the portfolio, address form, -
TinyMCE codesample feature (plugin) does not work with django
I'm using TinyMCE with django and all the features work only the codesimple feature i mean it works inside the tinyMCE editor but when the web page renders it does not work i am using the latest version of TinyMCE and a bootstrap template settings.py: TINYMCE_JS_URL = os.path.join(STATIC_URL, "tinymce/js/tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tinymce/js/tinymce") TINYMCE_DEFAULT_CONFIG = { 'height' : 300, 'plugins': "image,imagetools,media,codesample,link,code", 'cleanup_on_startup': True, 'menubar': True, 'toolbar': "styleselect |undo redo | bold italic | alignleft aligncenter alignright | link image media codesample code", 'image_caption': True, 'image_advtab': True, 'custom_undo_redo_levels': 10, 'file_browser_callback' : "myFileBrowser" } path: static_in_env css font img js tinyMce js tinyMCE -
Do fixtures work with response.context in Django unit tests?
It's my first time writing tests for Django. So far I've used a fixture which contains test data and checked that my database model methods generate the correct outputs. So far so good. I'm now trying to test my views by checking that my context variable contain what they should. But I get a NoneType error as below. I've tried all I can, maybe fixtures don't work with self.client.get() and response.context() ? python manage.py test journals TypeError: 'NoneType' object is not subscriptable urls.py path('ledgers/show/all', views.ledgers_show_all, name='ledgers_show_all'), Views.py @login_required def ledgers_show_all(request): coa_groups = COAGroup.objects.all() total_profit_loss = 0 for coa_group in coa_groups: coa_group.balance2 = 0 coa_group.coa_sub_groups_with_balances = [] for coa_sub_group in coa_group.coasubgroup_set.all(): coa_sub_group.ledgers_with_balances = [] coa_sub_group.balance2 = 0 coa_sub_group.display = False for ledger in coa_sub_group.ledger_set.all(): ledger.balance2 = ledger.balance if ledger.balance2 != 0 or ledger.status != '1': coa_sub_group.display = True coa_sub_group.balance2 += ledger.balance2 coa_sub_group.ledgers_with_balances.append(ledger) coa_group.balance2 += coa_sub_group.balance2 coa_group.coa_sub_groups_with_balances.append(coa_sub_group) total_profit_loss += coa_group.balance2 return render(request, 'journal/ledgers_show_all.html',{'coa_groups': coa_groups}) Tests.py class Balances(TestCase): fixtures = ['db.json', ] def test(self): response = self.client.get(reverse('journal:ledgers_show_all')) self.assertEqual( response.context['coa_groups'], 1 # Just a test value for now ) -
Automating folder creation in Django static directory
Mine is a very general question. I am planning a project for a client in django2 which will involve taking photos and uploading images to a media folder in the static directory. Every time the client starts a project lets say 'project_A' they will generate a new record that will essentially populate the models via associated forms. At some points, each record will have associated image files. I think it is better to store image files separately (perhaps as in static/media/project_A/image_one.jpg ) and save an associated file name in the database. is that the best practice? And if so is there a way to automate the creation of the folder "project_A" in the static folder when the client initiates the project? -
Error code H13 with Django App deployed on Heroku when trying to access Django page
My website and admin page work locally, but I am getting an application error:H13 when trying to access my admin page on the Heroku web page. Here is a portion of the heroku logs: [web.1]: 10.47.180.171 - - [29/Feb/2020:21:10:30 +0000] "GET /favicon.ico HTTP/1.1" 404 179 "https://quiet-woodland-94985.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36" 2020-02-29T21:18:46.170318+00:00 app[web.1]: [2020-02-29 21:18:46 +0000] [13] [INFO] Booting worker with pid: 13 2020-02-29T21:18:46.166523+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/admin/" host=quiet-woodland-94985.herokuapp.com request_id=43137702-84dc-4892-b3bf-9c0c6d155a6b fwd="174.55.195.195" dyno=web.1 connect=1ms service=67ms status=503 bytes=0 protocol=https 2020-02-29T21:18:56.996229+00:00 app[api]: Set DJANGO_ADMIN_URL config vars by user phikhant@uci.edu 2020-02-29T21:18:56.996229+00:00 app[api]: Release v22 created by user phikhant@uci.edu 2020-02-29T21:18:57.341490+00:00 heroku[web.1]: Restarting 2020-02-29T21:18:57.344662+00:00 heroku[web.1]: State changed from up to starting 2020-02-29T21:18:58.324719+00:00 app[web.1]: [2020-02-29 21:18:58 +0000] [13] [INFO] Worker exiting (pid: 13)[2020-02-29 21:18:58 +0000] [12] [INFO] Worker exiting (pid: 12) 2020-02-29T21:18:58.324729+00:00 app[web.1]: 2020-02-29T21:18:58.324730+00:00 app[web.1]: [2020-02-29 21:18:58 +0000] [4] [INFO] Handling signal: term 2020-02-29T21:18:58.420449+00:00 app[web.1]: [2020-02-29 21:18:58 +0000] [4] [INFO] Shutting down: Master 2020-02-29T21:18:58.304389+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2020-02-29T21:18:58.508719+00:00 heroku[web.1]: Process exited with status 0 2020-02-29T21:19:01.612316+00:00 heroku[web.1]: Starting process with command gunicorn TreatmentPlanning.wsgi --log-file - 2020-02-29T21:19:03.436411+00:00 app[web.1]: [2020-02-29 21:19:03 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-02-29T21:19:03.436964+00:00 app[web.1]: [2020-02-29 21:19:03 +0000] [4] [INFO] Listening … -
Passing kargs in Url Patterns
I am using the PasswordResetView of django.contrib.auth.views. I am trying to direct my path('reset-password/'...) to use my 'rest_password_email.html' template after the user has submitted an email address for password reset. I have added this as a kwargs, however django is not recognizing it and continues to direct the application to default 'password_reset_email.html'. Any suggestions on how this can be achieved? thanks. BTW: I am using namespace 'accounts'. Hence the reason for doing the above is to introduce the amended url in my template to account for the namespace. url.py from django.urls import path from . import views from django.contrib.auth.urls import urlpatterns from django.contrib.auth.views import ( LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView ) from django.urls import reverse_lazy app_name = 'accounts' urlpatterns = [ path('', views.home, name = 'home'), path('column/', views.column), path('login/', LoginView.as_view(template_name='accounts/login.html'), name = 'login'), path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name = 'logout'), path('register/', views.register, name = 'register'), path('profile/', views.view_profile, name = 'view_profile'), path('profile/edit/', views.edit_profile, name = 'edit_profile'), path('change_password/', views.change_password, name = 'change_password'), path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), kwargs={'email_template_name':'accounts/reset_password_email.html','post_reset_redirect': reverse_lazy('accounts:password_reset_done')}, name = 'password_reset'), path('reset-password/done', PasswordResetDoneView.as_view(), name = 'password_reset_done'), path('reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path('reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] reset_password_email.html {% load i18n %}{% autoescape off %} {% blocktrans %}You're receiving this email because you requested a password reset … -
Angular HttpClient get request - how to get the text data sent?
I have an Angular/Ionic app that communicates with a Django backend. I am using this.http.get() to communicate with this server (on Heroku) and the Django server should be sending the text "OK". Instead, I am either (dependent on specific usage of this.http.get()) getting an error where the statusText is the text I want, or something like Object { _isScalar: false, source: {…}, operator: {…} } My Django code is simple: def make(request, otherParams): ... return HttpResponse("OK") I know that the get() has made it to the server, because the server runs certain things when the corresponding function is called. How do I, from the Angular frontend, detect if the Django script has sent the "OK" or not? (The error is not due to any of various CORS policies, I have installed django-cors-headers) -
Django REST Framework: enforce content type
I have an API endpoint for an IoT device and I am trying to minimize the size of the HTTP request. I would like to not specify the content type in the request header and ask DRF to always use application/json. How to do that? -
Django doesn't display pictures uploaded with Django admin (ImageField) + Pillow
Site is unable to see neither pictures uploaded by Django admin + Pillow in ImageField, neither static picture, images located in folder media/products/ in app "shop": Not Found: /media/products/no_image.png{% else %}/static/img/no_image.png [29/Feb/2020 19:35:55] "GET /media/products/no_image.png%7B%%20else%20%%7D/static/img/no_image.png HTTP/1.1" 404 1929 Media/Static in settings file : STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls file : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls', namespace='shop')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) admin file in app "shop": from django.contrib import admin from .models import Category, Product @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'slug', 'price', 'available', 'created', 'updated'] list_filter = ['available', 'created', 'updated'] list_editable = ['price', 'available'] prepopulated_fields = {'slug': ('name',)} views file in app "shop" : from django.shortcuts import render, get_object_or_404 from .models import Category, Product def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) return render(request, 'shop/product/detail.html', {'product': product}) models file … -
How can I scrape this image using bs4? [closed]
Here's a screenshot containing my code and the inspect element with the image I want to get. The code I wrote doesn't work if any of you guys can help I would appreciate it. I tried to do post.find("img").get("src") but it doesn't work -
Django storages backend url pattern error when using dropbox
I am trying to use dropbox as a backend storage solution for django using django-storages, i followed the documentation but i am getting this error: 'C:/media/post_pics/profile_pic.jpeg' did not match pattern '(/(.|[\r\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' This is y models.py class Post(models.Model): title = models.CharField(max_length=64) date = models.DateField(timezone.now()) picture = models.ImageField(upload_to='post_pics') settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Dropbox media file storage DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'myToken' DROPBOX_ROOT_PATH = '/media/' -
How to make Django Nested Templates for better SRP
I'm attempting to make a base template for my website. Ideally it would look like this {% block navigationbar %}{% endblock %} {% block content %}{% endblock %} {% block footer %}{% endblock %} This way I am able to have separate navigationbar.html and footer.html files. All views I would like to show would then just put this: {% extends 'portfolio/base.html' %} {% block content %} // View Code here {% endblock %} Any way to achieve this. I have realized I can't do multiple extends and I've tried different combinations of nesting but nothing has worked for me so far. -
Django, error importing view from another app
I'm trying to import a view from one app to another in my project. When using this: from ..from ..KnownLocation.views import KnownLocationView I get the following error: ValueError: attempted relative import beyond top-level package When trying to use: from triangulationapi.KnownLocation.views import KnownLocationView It's raising the following error. ModuleNotFoundError: No module named 'triangulationapi.KnownLocation' my Project tree: ├── find_second_gdt │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── second_GDT_finding │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── __init__.py ├── KnownLocation │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── requirements.txt. └── triangulationapi ├── asgi.py ├── __init__.py ├── __pycache__ ├── settings.py ├── urls.py └── wsgi.py And, what's the diffrence between using .. and project.app.view... I thought it is the same up until now.