Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to display id page on to my home page
I'm trying to display id page http://127.0.0.1:8000/1/ on to my home page but I can't get it to work, I tried {{ posts.photos.id.slideshow }} but I can't display it on the home page home.html, is there anyway to display the the post image id page on to my homepage? views.py def SlidesShowView(request): posts = Slideshow.objects.all() return render(request, 'slideshow.html', {'posts':posts}) def ShowCaseView(request, id): post = get_object_or_404(Slideshow, id=id) photos = Showcase.objects.filter(post=post) return render(request, 'showcase.html', { 'post':post, 'photos':photos }) models.py class Slideshow(models.Model): title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(blank=True) def __str__(self): return self.title class Showcase(models.Model): post = models.ForeignKey(Slideshow, default=None, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True, upload_to="showcase/images/") def __str__(self): return self.post.title urls.py from django.contrib import admin from django.urls import path from . import views from .views import HomeView, ArticleDetailView, AddPostView, EditPostView, DeletePostView, AddCategoryView, CategoryView, CategoryListView, LikeView, AddCommentView, SlidesShowView, ShowCaseView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ #path('', views.home, name="home"), path('', HomeView.as_view(), name="home"), path('article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'), path('add_post/', AddPostView.as_view(), name='add_post'), path('add_category/', AddCategoryView.as_view(), name='add_category'), path('article/edit/<int:pk>', EditPostView.as_view(), name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'), path('category/<str:cats>/', CategoryView, name='category'), #path('<str:cats>/', CategoryView ,name='category'), path('category-list/', CategoryListView, name='category-list'), path('like/<int:pk>', LikeView, name='like_post'), path('article/<int:pk>/comment', AddCommentView.as_view(), name='add_comment'), path('search_index', views.search_index, name='search-index'), path('', views.SlidesShowView, name='slideshow'), path('<int:id>/', views.ShowCaseView, name='showcase') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)**strong text** -
Django channels error : TypeError: __call__() missing 1 required positional argument: 'send'
I am working on Django channels and Async application and I am totally new into it. I started seeing tutorials for that . When I ran django server , it works fine but when I load the page or try to connect with websocket king client for testing the server , it show the error -> WebSocket HANDSHAKING /ws/game/roomname [127.0.0.1:51190] Exception inside application: __call__() missing 1 required positional argument: 'send' Traceback (most recent call last): File "C:\Users\user\anaconda3\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\user\anaconda3\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\user\anaconda3\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\user\anaconda3\lib\site-packages\asgiref\compatibility.py", line 34, in new_application return await instance(receive, send) TypeError: __call__() missing 1 required positional argument: 'send' WebSocket DISCONNECT /ws/game/roomname [127.0.0.1:51190] I am new into it and I am unable to solve the problem . Kindly help . My project asgi.py import os from channels.routing import ProtocolTypeRouter , … -
Que significa STATICFILES_ROOT? en si estoy trabajando en python y django
Si me podrian ayudar con lo que es, para que sirve y sus caracteriticas pero mas me interesa lo que es. -
I need help! insert qrcode in Django
I’m not good at Django. I asked the django community to help me with a problem. I want to create a form to upload a pdf file to the database , then take that file out to add qr code at the top of the first page . Then save it in databse . I have sketched my idea. If Django can’t solve it, please give me a solution. I’m writing a functional website in django. Pleenter image description herease help don’t reject me -
DRF: How do you create multiple "detail" views for a model?
I have a django model that has multiple fields that need to be used as a key, and also has some detail views. For example, my endpoints currently look like this, using detail=True to get the second set: my.api/things/{id_1} (GET, POST, DELETE) my.api/things/{id_1}/whatever (GET, POST) That's all great, but I have to get to something that looks like this instead: my.api/things/{id_1} (GET, POST, DELETE) my.api/things/{id_1}/whatever (GET, POST) my.api/things/other_id/{id_2} (GET, POST, DELETE) my.api/things/other_id/{id_2}/whatever (GET, POST) If it helps, the set of detail endpoints (ie. whatever) is identical, and there's no difference in functionality between the two. I just need to be able to access the database through either field. I'm new to django so I'm sorry if this is a simple question. Any help would be appreciated! -
Trying to follow a turorial code and I'm having path error
I'm a beginner trying django for the first time trying to map my urls together, but after following the necessary steps the django installation page keeps on showing on my browser. for my project app from django import path from django.urls import path from . import views urlpatterns = [ path('',views.index ) ] for my parent app from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] for my project views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('good sir') -
Django UpdateView creates duplicated formsets
I'm having problems when updating the entries of my products, discounts and inventory in the database, the inventories and discounts have the product id as a foreign key and I have defined two inline formsets to enter all the data in one single form ProductMeta=forms.inlineformset_factory(Product,Inventory,InventoryForm,extra=0,can_delete=False) DiscountMeta=forms.inlineformset_factory(Product,ProductDiscount,DiscountForm,extra=0,can_delete=False) Something strange happens, both formsets work normally when creating using extra=1 in the formsets, but in the UpdateView I must use extra=0, otherwise the inventory and discount forms get duplicated, and both forms disappear from the creation view views.py class UpdateProduct(UpdateView): model=Product form_class =ProductForm template_name = 'new_product.html' title = "UPDATE PRODUCT" def get_context_data(self, **kwargs): context = super(UpdateProduct, self).get_context_data(**kwargs) if self.request.method == 'POST': context['product_meta_formset'] = ProductMeta(self.request.POST,instance=self.object) context['discount_meta_formset'] = DiscountMeta(self.request.POST,instance=self.object) else: context['product_meta_formset'] = ProductMeta(instance=self.object) context['discount_meta_formset'] = DiscountMeta(instance=self.object) return context def form_valid(self, form): context=self.get_context_data() productMeta=context['product_meta_formset'] discountMeta=context['discount_meta_formset'] if productMeta.is_valid() and discountMeta.is_valid(): self.object=form.save() productMeta.instance=self.object productMeta.save() discountMeta.instance=self.object discountMeta.save() if not productMeta.is_valid(): print("productMeta invalid") if not discountMeta.is_valid() : print("discountMeta invalid") return redirect(reverse("products:listProducts")) For some reason Django considers that my productMeta and discountMeta are invalid since both prints are executed and obviously the changes are not saved in the database, for now I fix the inlineformset extra=0 problem using other inlineformsets, but I would like to know how to solve the invalid … -
(Hidden field id) Select a valid choice. That choice is not one of the available choices. (Django)
I'm receiving this error when I try to submit two formsets. After I fill the form and click the save button, it gives the error: (Hidden field id) Select a valid choice. That choice is not one of the available choices. I'm trying to create dynamic form so that the user can add new sections and also new lectures inside the section when they click "Add" button. The adding new form function works well, I just have problem saving it to the database. Views.py def addMaterials(request, pk): course = Course.objects.get(id=pk) sections = CourseSection.objects.filter(course_id=pk) materials = CourseMaterial.objects.filter(section__in=sections) SectionFormSet = modelformset_factory(CourseSection, form=SectionForm, extra=0) sectionformset = SectionFormSet(request.POST or None, queryset=sections) MaterialFormSet = modelformset_factory(CourseMaterial, form=MaterialForm, extra=0) materialformset = MaterialFormSet(request.POST or None, queryset=materials) context = { 'course': course, 'sectionformset': sectionformset, 'materialformset': materialformset, } if request.method == "POST": if all([sectionformset.is_valid() and materialformset.is_valid()]): for sectionform in sectionformset: section = sectionform.save(commit=False) section.course_id = course.id section.save() for materialform in materialformset: material = materialform.save(commit=False) print(material) material.section_id = section #section.id or section.pk also doesn't work material.save() return('success') return render(request, 'courses/add_materials.html', context) Forms.py class SectionForm(forms.ModelForm): class Meta: model = CourseSection fields = ['section_name', ] exclude = ('course_id', ) class MaterialForm(forms.ModelForm): class Meta: model = CourseMaterial fields = ['lecture_name', 'contents'] The second formset … -
Rebuilding a PyQt5 Desktop App for the web? with Python/Django
I have created a PyQt5 Desktop App but I've decided I want it as a webpage instead. So, to do this I think I'm going to completely remake the app using Django/python. My app is essentially 1 page of around 100 buttons that output midi notes when clicked. I would like to see exactly the same layout of buttons and CSS on a webpage as I currently do on my Desktop App and need to have the buttons call functions, just as they do on the desktop app. Essentially I need to translate my PyQt5 Desktop app to a Webpage and need help understanding how to start, thanks. -
aws codestar deploy daphne django
I need deploy my proyect with dpahne in aws codestar but, i can't do it, i do this in file install_dependencies # Set up a virtual environment python3.8 -m venv environment source environment/bin/activate # Install awscli and python dev libraries python3.8 -m pip install -r requirements.txt daphne -u /tmp/daphne.sock my_project.asgi:application but not works, do this in supervisor.conf environment/bin/daphne my_project.asgi:application --port 8000 --websocket_timeout -1 --bind 0.0.0.0 -v2 codestar use ami aws linux and i can't install like apt because yum is so restricted and somone know if i'm bad o know how do it, thanks. -
ORM vs Raw Queries (For big project)
I am working on a project which I want to eventually launch to the public. In past, I have Used Django which uses ORM to use databases as python models. But I also know that they add extra overhead in terms of latency and query optimization. But now I am using FastAPI as my restapi server, PSQL as DB and I have to use 3rd party ORM such as SqlAlchemy (which is really complex). I am thinking of two choices Start with ORM initially, and later move to raw queries if there is a performance issue or high demand of users. Start with raw SQL initially using psycopg2 library. If I go with this, I have to manage everything such as connection pooling, queries, and if conn breaks reconnect it etc. Is there any python famous lib that can do that on top of psyopg2. I wanted to know if there is increase in app consumers how to tackle database queries. How do the big companies like facebook, amazon, Instagram do this? I am sure they are not using ORMs. -
django Model object.all() for ModelChoiceField and ModelMultipleChoiceField
I have a TransactionCategory model and I want to use it to display both ModelMultipleChoiceField and ModelChoiceField in django form. model.py class TransactionCategory(models.Model): """ Transaction Category database model """ txn_category = models.CharField("Transaction Category", max_length=50, null=True, default=None, blank=True) def __str__(self): """ Transaction Category Returns: transaction category : str """ return f"{self.pk} ({self.txn_category})" class Meta: verbose_name = "Transaction Category" db_table = "txn_category" forms.py queryset fills the MultipleChoiceField control using "id" as value and "txn_category" as text perfectly. class TxnCategoryDetailModelForm(forms.ModelForm): txn_description = forms.ModelMultipleChoiceField(label="Transaction Description", queryset=CreditCardTxnDescription.objects.all().order_by("description"), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = TransactionCategory fields = ["txn_category"] Doesn't work well with ModelChoiceField (dropdown), the queryset populates the id correctly but text shows "id (txn_category)" e.g. "1 (food)" class TxnDescriptionTagsModelForm(forms.ModelForm): description = forms.CharField(widget=forms.TextInput(attrs={"autofocus": "autofocus"}), strip=False) txn_category = forms.ModelChoiceField(queryset=TransactionCategory.objects.all().order_by('txn_category')) tags = TagWidget() class Meta: model = CreditCardTxnDescription fields = ["description", "description_comment", "txn_category", "tags"] How can I use TransactionCategory model for both ModelMultipleChoiceField and ModelChoiceField and have them displayed properly? -
The best way for calculated fields in Django
I'm starting to create my first web application in Django. I'm dealing with backEnd part first. In my data structure I need to calculate some fields like average rating of employee's salary for each model object (company, department ..). I found some ways to calculate and display calculated field in API. Add a property into model and override querySet for better performance. Calculate and add extra field in serializers and display it for API. Use build-in computedfields.models I can not decide which way is best for calculating fields, what are pros and cons of each way. Thanks for some advice. -
Best way to create an 'online virtual piano' webpage?
I want to create a basic online midi piano webpage. I know Python very well but not JavaScript yet. What is the best way to do this? Is Django or Flask relevant here? Essentially I just want a super basic midi piano on a webpage and am just looking for a point in the right direction, thanks. Context: I have made a PyQT5 Desktop App but have now decided I want it as a webpage so I need to completely remake it. I've never done any web development. I need Midi and not audio files. -
json.dumps serialized query set into unusable format in Django with WebSockets (Channels)
I read everything I could found about serializing QuerySets in Django but still can not find any working solution for transferring the existing WSGI function into a ASGI WebSocket Consumer. My view function looked like this: ... context = { "registered": user_is_player, "object": game, "player": player, "players": game.player_set.all(), "players_cards": players_cards, "card_deck": game.globalcarddeck_set.all(), "prio_deck": game.prioritydeck_set.all(), "table": game.table_set.all(), "cards": game.card_set.all(), } return render(request=request, template_name=template_name, context=context) and was working fine, but the query results sadly seam not to be transferable via synchronous web socket. Within my class GameConsumer(WebsocketConsumer) I figured that I can transfer a single result with with model_to_dict (after sadly loosing a few fields) but same does not apply to QuerySets. Those can be only serialized with the serialize function like: serialize("json", game_instance.player_set.all()). ... game_instance = Game.objects.get(slug=self.game_name) game_json = model_to_dict( game_instance, fields=["name", "slug", "round_number", "active", "started"] ) context = { "registered": user_is_player, "game": game_json, "player": player, "message": message, "players": serialize("json", game_instance.player_set.all()), "players_cards": serialize("json", players_cards), "card_deck": serialize("json", game_instance.globalcarddeck_set.all()), "prio_deck": serialize("json", game_instance.prioritydeck_set.all()), "table": serialize("json", game_instance.table_set.all()), "cards": serialize("json", game_instance.card_set.all()), } self.send(text_data=json.dumps({"context": context})) At the end everything needs to be dumped with json.dumps, otherwise one would end up with the exception: self.sendMessage(content.encode("utf8"), binary) AttributeError: 'dict' object has no attribute 'encode' This seam to be the … -
Cannot Containerise (Docker) Django App - Pillow Install Error in Container but works OK in localhost
I have a Django App built on my localhost with postgreSQL DB backend. I want now to containerise this App. In my local app, I'm using Django, Pillow and Psycopg2. Here is my Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD python3 manage.py runserver 0.0.0.0:80 Here is an extract of my requirements.txt file: Django==4.0.3 psycopg2-binary==2.9.3 Pillow==8.4.0 The above versions (in the requirements.txt file) are taken from the versions I'm already using and the app is working flawlessly on my localhost:8000 But when I build the dockerfile, here's the error: [+] Building 20.4s (8/9) => [internal] load build definition from Dockerfile 0.1s => => transferring dockerfile: 37B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.9-alpine 1.5s => [internal] load build context 2.0s => => transferring context: 902.95kB 1.8s => [1/5] FROM docker.io/library/python:3.9-alpine@sha256:2b876321cf313033a9cd2c70f9e7ca99d627c3b74e4850349a0793676947a8cf 0.0s => CACHED [2/5] WORKDIR /app 0.0s => CACHED [3/5] COPY requirements.txt . 0.0s => ERROR [4/5] RUN pip install -r requirements.txt 16.8s ------ > [4/5] RUN pip install -r requirements.txt: #8 6.241 Collecting Django==4.0.3 #8 6.360 Downloading Django-4.0.3-py3-none-any.whl (8.0 MB) #8 7.261 Collecting psycopg2-binary==2.9.3 #8 7.281 … -
Error installing Python Plugin: ModuleNotFoundError: No module named <module>
I'm trying to build a Python Plugin for Saleor using Poetry and I'm having issues installing the plugin on Saleor. I run poetry add ../social_auth to install the plugin on saleor and it succeeds but when I try to run Saleor I get this Error: No module named 'social_auth' File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 930, in _bootstrap self._bootstrap_inner() But I checked, the module is in settings.INSTALLED_APPS, settings.PLUGINS and listed on pip list... Here's the plugin structure: ├── __init__.py ├── poetry.lock ├── pyproject.toml └── social_auth ├── __init__.py └── plugin.py 1 directory, 5 files the pyproject.toml file: [tool.poetry] name = "social-auth" version = "0.1.0" description = "Social auth for saleor" authors = ["Wellington Zenon <wellington.zenon@gmail.com>"] packages = [ … -
use two models in a single view that you can save and edit in django
lovers of zero and one. How can I make a view have two forms with two different models but saving one form doesn't affect the other? try to use a modelform use it in a single view. but I would like to know how to solve it or the best practice for these cases. -
Django App works on PyCharm by not VS-code (File manage.py line 17 error)
I have a Django App that works well in PyCharm. All modules etc work. I need, however, to open the code in Visual Studio Code. However, when I execute a: python manage.py runserver command in visual studio code, I get the following error: File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax I've scoured the resources - but I can't find any solution. I've re-installed python Django using PIP.. - still no luck. Yes, I've reactivated the VENV - it just so happens it is stuck in activated state - but im ok with that. Any ideas ? Thanks -
More than two custom params to generate Token in Django RF
I'm a frontend mobile developer, i have a Flutter project 100% white labeled, now i'm studying the backend and developing it with Django RF. I'll use the same database for all generated builds of my app, so to prevent the user to login with the same account in two differents builds, i need to generate a Token with more than 2 parameters (email/password + a third one). What's the best practice in this case? I'm using the 'rest_framework.authentication.TokenAuthentication'. -
How to call field from Serializers.py to views.py
I am learning it. So there is a field called password in serializers.py I want to call that field in views.py. The password field is randomly generated. I want to get this field. How do I achieve this? -
mobile app from website is a good option?
I am developing a website and I have plans to convert to a mobile app. The technologies used to build the website are: Frontend: HTML, CSS, JavaScript Backend: Python (Django) DataBase: SQLite I wonder if converting from site to mobile app is a good option? -
How do I run a function in the background so that it doesnt stop the other pages django
I have a script which is starting a download of a sound file when the user clicks a button on the website, but when one user starts the download the whole backend stops and waits for it to finish before any other user can use the website. songList = await self.getSongs() await self.downloadSongs(songList) async def downloadSongs(self, songList): dirList = os.listdir("Directory") await self.channel_layer.group_send( self.room_group_name, { 'type': 'loadingGameGroup', }) downloadThread = threading.Thread(target=self.download, args=(songList, dirList)) downloadThread.start() downloadThread.join() def download(self, songList, dirList): for song in songList: try: self.downloadSong(song, dirList) except: self.downloaded = False return def downloadSong(self, song, dirList): songId = song["song_id"] if songId + ".mp3" in dirList: return video_url = "https://www.youtube.com/watch?v="+ songId video_info = youtube_dl.YoutubeDL().extract_info( url = video_url,download=False ) filename = "Directory" + songId + ".mp3" options={ 'format':'bestaudio/best', 'keepvideo':False, 'outtmpl':filename, } with youtube_dl.YoutubeDL(options) as ydl: ydl.download([video_info['webpage_url']]) How do I make it so it downloads the songs, waits for one group of songs to finish so I then can send a websocket message back to the client so that one can proceed. While the other groups doesnt have to wait for it to finish to do something -
Django {{data|escapejs}} from a js static file
I use {{data|escapejs}} django banner to import some data in my the javascript of my page. Simple example : <script> console.log({{data|escapejs}}) </script> But it doesn't work if I place this line in a .js static file <script src = "{% static 'mycode.js' %}> In mycode.js : console.log({{data|escapejs}}) How to make it work ? -
Cant include navbar.html in other modules
I'm quite a beginner in web development I've encountered some problems using Django this is my projects modules code. {% include 'navbar.html' %} <h1>projects template</h1> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> {% endblock content %} and this is my navbar.html: <h1>Logo</h1> <hr> when I run this, it is expected to return something like this: enter image description here but it instead outputs this: enter image description here as you can see it doesn't wrap the navbar text correctly. I would really appreciate it if someone helps me with this issue.