Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Pass Id Here (error put() missing 1 required positional argument: 'request') In form template djagno
urls.py from django.urls import path from . import views app_name = "poll" urlpatterns = [ path('', views.index, name="index"), # listing the polls path('<int:id>/edit/', views.put, name='poll_edit'), ] views.py def put(self, request, id): # print("catching error ") error before this line question = get_object_or_404(Question, id=id) poll_form = PollForm(request.POST, instance=question) choice_forms = [ChoiceForm(request.POST, prefix=str( choice.id), instance=choice) for choice in question.choice_set.all()] if poll_form.is_valid() and all([cf.is_valid() for cf in choice_form]): new_poll = poll_form.save(commit=False) new_poll.created_by = request.user new_poll.save() for cf in choice_form: new_choice = cf.save(commit=False) new_choice.question = new_poll new_choice.save() return redirect('poll:index') context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, 'polls/edit_poll.html', context) edit_poll.html {% extends 'base.html' %} {% block content %} <form method="PUT" > {% csrf_token %} <table class="table table-bordered table-light"> {{poll_form.as_table}} {% for form in choice_forms %} {{form.as_table}} {% endfor %} </table> <button type="submit" class="btn btn-warning float-right">Update</button> </form> {% endblock content %} this is error line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /polls/9/edit/ Exception Value: put() missing 1 required positional argument: 'request' I know that I am not passing argument in html but i dont know how to pass id argument in html please help me any single line of code something like default (context passing by djagno) -
Why can't I use custom slugs for Parent and Children in Django Rest Framework?
I'm trying to use custom slugs for Parent and Child models. Models: # models.py class Parent(models.Model): slug = models.SlugField() class Child(models.Model): parent = models.ForeignKey(Parent) order = models.IntegerField() slug = models.SlugField() class Meta: ordering = ['order', 'pk'] def save(self, *args, **kwargs): self.slug = f"{parent.slug}/{self.order}" super(Text, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("app:child-detail", kwargs={"slug": self.slug}) The Child model will use its order and the Parent's slug in its slug. I can get everything working with the default <int:pk> in the URLs but when I try to swap it to <slug:slug>, I get this error on both List and Detail views: Could not resolve URL for hyperlinked relationship using view name "app:child-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. When I try to call get_absolute_url() on a Child object (where the order is '1' and the parent's slug is 'parent-slug'), I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'child-detail' with keyword arguments '{'slug': 'parent-slug/1'}' not found. 2 pattern(s) tried: ['api/v1/child/(?P[-a-zA-Z0-9_]+)(?P\.[a-z0-9]+/?)$', 'api/v1/child/(?P[-a-zA-Z0-9_]+)$'] URLs: # project urls.py urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/", include("app.urls", namespace="app")), path("api-auth/", include("rest_framework.urls")), # login for Browserable API ] # app urls.py from django.urls import path, include from … -
django: runserver static files not found
I've read some posts on similar topics but none of them are exactly the same. I've a django app (django 2.2.2, python 3.6.12) that works with no problems when served with uwsgi (along with nginx), but has problems of finding static files when served with runserver (python manage.py runserver 0:8000) with error messages like the following: WARNING Not Found: /static/admin/css/base.css WARNING Not Found: /static/admin/js/core.js I have the following settings: BASE_PATH = '/data/webapps/myapp' STATIC_ROOT = os.path.join(BASE_PATH, '_site/static') and in BASE_PATH, I have the following folders which contain all files the system complained about not being found: _site/static/admin/css _site/static/admin/js I even duplicated the two folders _site/static/admin/css and _site/static/admin/js as static/admin/css and static/admin/js respectively in BASE_PATH, but with no effect. static/admin/css static/admin/js Here I want to emphasize that it works with no problems when served with uwsgi with the following command: uwsgi --ini uwsgi.ini and uwsgi.ini contains the following lines: [uwsgi] chdir = %d enable-threads = true max-requests = 5000 file = /data/webapps/myapp/myapp/conf/wsgi.py socket = uwsgi.sock chmod = 666 chmod-socket = 666 uid = myapp gid = myapp and wsgi.py has the following codes: """ WSGI config for mybic project. It exposes the WSGI callable as a module-level variable named ``application``. For more … -
Receiving unregistered task of type Error
Im getting the error [2021-03-27 18:36:43,996: ERROR/MainProcess] Received unregistered task of type 'orders.tasks.order_created'. The message has been ignored and discarded. Here all the associated system files. performancerealm.com |---orders | | __init__.py | |-tasks.py | |-views.py | |---speedrealm | |- __init__.py | |- celery.py | |- settings.py | |---manage.py |--- # other apps orders.py from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): pass speedrealm.init.py from .celery import app as celery_app __all__=("celery_app",) speedrealm/celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'speedrealm.settings') app = Celery('speedrealm') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() speedrealm.settings.py CELERYD_NODES="w1" CELERY_BIN="/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin" CELERY_APP="speedrealm" CELERYD_CHIR="/home/bulofants/performancerealm.com" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_USER="bulofants" CELERYD_GROUP="bulofants" CELERYD_LOG_LEVEL="INFO" CELERY_CREATE_DIRS=1 CELERY_IMPORTS = [ 'orders.tasks' ] CELERY_TIMEZONE='US/Eastern' This error only occurs with celery multi start w1 -A speedrealm -l DEBUG. My goal is that the task is going to run in the back grtound. I've tired running in different dirs (top-=level and app_dir), and I have also tried commenting/uncommenting CELERY_IMPORTS. Im not sure if this is needed but here is the conf.d also. /etc/systemd/system/celery.service [Unit] Description=Celery Service After=network.target [Service] Type=forking User=bulofants EnvironmentFile=/etc/default/celeryd/celeryconfig.py WorkingDirectory=/home/bulofants/sites/performancerealm.com ExecStart=/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin/celery multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS} ExecStop=/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin/celery ${CELERY_BIN} multi stopwait ${CELERYD_NODES} --pidfile=${CELERYD_PID_FILE} ExecReload=/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin/celery ${CELERY_BIN} multi … -
Venv stops working as supposed after opening a branch in git
I had a project set up within VS-Code together with a venv (setup via "python -m venv venv") in it. Everything was working fine: Git worked and my venv did also do its job, e.g. opening python via the terminal while the venv was active would open the right python interpreter within the venv and thus find the correct libraries. I decided to open a new branch via the git command : "git checkout -b eel_replacement" and wanted to install Django afterwards via "pip install django"(while my venv was active). Installation succeded and I wanted to verify that by opening the python interpreter and trying "import django"(I also tried "import Django"), which did not work, resulting in the error: Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'django' If I type in pip list, then this is the output: pip list output There are 2 things that really got me confused right here: It does show all packages, not only the ones I installed within my venv. This normally indicates that my venv is not active! Nonetheless you can see it still shows the "(venv)" line before my command prompt, which normally indicates that … -
check password always returns false django
I work with django and store user passwords as hashed values created with make_password. When I run check_password, I always get a false return and I am out of ideas how to solve this. Any help would be much appreciated. My user registration looks like this: def user_reg_view(request): form = UserForm(request.POST or None) if form.is_valid(): password = hashers.make_password(form.cleaned_data.get('password')) fname = form.cleaned_data.get('first_name') lname = form.cleaned_data.get('last_name') email = form.cleaned_data.get('email') company_id = form.cleaned_data.get('company') User.objects.create_user( email = email, password=password, first_name = fname, last_name = lname, username = email, company_id = company_id) form = UserForm() var = {'form': form} return render(request, 'user_registry.html', var) And my login function part that fails looks like so (assume the user exists and password entered is always the same): def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') user = User.objects.get(username=username) password = form.cleaned_data.get('password') encoded_password = user.password print(hashers.make_password(password) == user.password) #returns false print(hashers.check_password(password=password, encoded=hashers.make_password(password), setter=None)) #returns true print(hashers.check_password(password=password, encoded=encoded_password)) # returns false I do not get how the first print differs from the second, of course the password hash generated differs each time for the same string but shouldn't check_password be able to process that? In case the error might be in the register form values passed, … -
POST a list of jsons in Django
i am beginner at the Django and have a problem. I make a REST API? and I want take as POST a list of JSON, like this POST /orders { "data": [ { "order_id": 1, "weight": 0.23, "region": 12, "delivery_hours": ["09:00-18:00"] }, { "order_id": 2, "weight": 15, "region": 1, "delivery_hours": ["09:00-18:00"] }, { "order_id": 3, "weight": 0.01, "region": 22, "delivery_hours": ["09:00-12:00", "16:00-21:30"] } ] } My serializers.py from rest_framework import serializers from rest_framework.decorators import api_view from .models import Courier, Order class CourierSerializer(serializers.ModelSerializer): class Meta: model = Courier fields = '__all__' class CourierCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = Courier fields = ('courier_id', 'courier_type', 'regions', 'working_hours',) def create(self, validated_data): return Courier.objects.create(**validated_data) def update(self, instance, validated_data): instance.courier_id = validated_data.get('courier_id', instance.courier_id) instance.courier_type = validated_data.get('courier_type', instance.courier_id) instance.regions = validated_data.get('regions', instance.courier_id) instance.working_hours = validated_data.get('working_hours', instance.courier_id) instance.save() return instance class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' def create(self, validated_data): return Order.objects.create(**validated_data) def update(self, instance, validated_data): instance.order_id = validated_data.get('order_id', instance.order_id) instance.weight = validated_data.get('weight', instance.weight) instance.region = validated_data.get('region', instance.region) instance.delivery_hours = validated_data.get('delivery_hours', instance.delivery_hours) instance.save() return instance @api_view(['POST']) def enroll(request): serializer = CourierCreateUpdateSerializer(data=request.data) serializer.is_valid(raise_exception=True) And my views.py from rest_framework.generics import get_object_or_404, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, \ ListCreateAPIView from Courierapp.serializer import CourierSerializer, CourierCreateUpdateSerializer, OrderSerializer from Courierapp.models import Courier, Order class … -
How to return relative to request django
In my django project, I built a little like-button. The problem is, that I had it only when I take a detailed view on a post, and now want to put it on the home page, where multiple posts are shown. The problem the Like Function of the button returns to the detailed page, but I want to make the return dependent from the url where the like came from, so that I can just scroll ahead on the home page or what ever page am on, without being returned to another page. So here is my views.py Like function: def PostLike(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) return HttpResponseRedirect(reverse('post-detail', args=[str(pk)])) So in a nutshell: how could I change my Like function so that I am returned to the page I liked from? -
Ошибка базы данных django + Mongo DB через djongo [closed]
I am making a site in django. I used djongo to work with the library. File settings.py from pathlib import Path import urllib # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1u5ekr9oub%dtl)ew_!d)@&40447(#ktw71n=tde!m=iw1z!3(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testapp', 'import_export', 'rest_framework', 'corsheaders', 'users' ] 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', 'corsheaders.middleware.CorsMiddleware' ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://localhost:8000', 'http://localhost:8080', ] ROOT_URLCONF = 'server.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'server.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'django_mongodb', } } # DATABASES = { # "default": { # 'ENGINE': 'djongo', # "name": 'api', # "host": 'mongo', # "port": 27017 # }, # } # DATABASE = { # 'default': { # 'ENGINE': 'djongo', # 'NAME': 'your-database-name', # 'CLIENT': … -
How do I use product image in html background url of a div?. Django
enter image description here Hello dear friends, I don't know how I can display a product-image inside my template. The image needs to go inside a background-url of a div, using static isn't a option, cause then its not coming form models. Please give me a awnser if you know how to do this? see image for more info -
Avoid querying related tables in Django
The model: class RegistrationSlot(models.Model): event = models.ForeignKey(verbose_name="Event", to=Event, related_name="registrations", on_delete=CASCADE) hole = models.ForeignKey(verbose_name="Hole", to=Hole, null=True, blank=True, on_delete=DO_NOTHING) registration = models.ForeignKey(verbose_name="Registration", to=Registration, blank=True, null=True, on_delete=SET_NULL, related_name="slots") player = models.ForeignKey(verbose_name="Player", to=Player, blank=True, null=True, on_delete=DO_NOTHING) starting_order = models.IntegerField(verbose_name="Starting order", default=0) slot = models.IntegerField(verbose_name="Slot number", default=0) status = models.CharField(verbose_name="Status", choices=STATUS_CHOICES, max_length=1, default="A") class Meta: ordering = ("hole", "slot") constraints = [ UniqueConstraint(fields=["event", "player"], name="unique_player_registration") ] objects = RegistrationSlotManager() In the manager I declare that I always want the player: class RegistrationSlotManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related("player") The primary access pattern for this data is to query by an event id, so the view filter looks like this: def get_queryset(self): queryset = RegistrationSlot.objects.all() event_id = self.request.query_params.get("event_id", None) if event_id is not None: queryset = queryset.filter(event=event_id) return queryset And what my UI wants is very simple. The serialized json object does not include related objects other than the player: { "id": 5798, "event": 344, "hole": 1, "registration": 9996, "starting_order": 0, "slot": 0, "status": "R", "player": { "id": 353, "first_name": "John", "last_name": "Dough" } } So while trying to optimize my api, this query should be one of the fastest, but it's not. The Django ORM is generating 1000+ queries that I do not want. The register_registrationslot query … -
Migrations Applied Locally but not in production
I have a django app in docker. The local setup is identical to the production one. However, the migrations are applied in the local setup but not in production. Local Setup Dockerfile . . . # copy entrypoint.sh COPY ./entrypoint.sh /web/entrypoint.sh # copy project COPY . /web/ # run entrypoint.sh ENTRYPOINT ["/web/entrypoint.sh"] entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input echo "Apply database migrations" python manage.py makemigrations echo "Migrating" python manage.py migrate echo "Build static files" python manage.py collectstatic --no-input exec "$@" Production Dockerfile.prod . . . # copy project COPY . /web/ # run entrypoint.sh ENTRYPOINT ["/web/entrypoint.prod.sh"] entrypoint.prod.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi echo "Apply database migrations" python manage.py makemigrations echo "Migrating" python manage.py migrate echo "Build static files" python manage.py collectstatic --no-input --clear exec "$@" Now, if I run ./manage.py showmigrations for local, I get accounts [X] 0001_initial [X] 0002_userprofile [X] 0003_userprofile_gender [X] 0004_userprofile_country [X] 0005_user_otp_mobile [X] 0006_user_mobile_veified [X] 0007_auto_20200506_0716 [X] 0008_auto_20201004_0642 [X] 0009_auto_20201021_1054 … -
How to handle nullable field with SubFactory of factoryboy in django?
I want to make nullable store attribute of StoreFactory. If I give store name, I want to that it return existing store object. but, It raised error. How can I get EventFactory instance with existing store object? # events/models.py SELL_DIRECT = "SD" ORDER_PRODUCT = "OP" SEND_PRODUCT = "SP" SETTLE_SALE = "SS" LEAVE_STORE = "LS" DEFECT_PRODUCT_IN_STORE = "DS" DEFECT_PRODUCT_IN_HOME = "DH" EVENT_TYPE_CHOICES = ( (SELL_DIRECT, "개인판매"), (ORDER_PRODUCT, "제품발주"), (SEND_PRODUCT, "입점처 입고"), (SETTLE_SALE, "판매내역정산"), (LEAVE_STORE, "입점처 퇴점"), (DEFECT_PRODUCT_IN_STORE, "불량:입점처"), (DEFECT_PRODUCT_IN_HOME, "불량:집"), ) EVENT_TYPES_ABOUT_STORE = set( [SEND_PRODUCT, SETTLE_SALE, LEAVE_STORE, DEFECT_PRODUCT_IN_STORE] ) class Store(TimestampedModel): """ 입점처 """ name = models.CharField(_("이름"), max_length=50, unique=True) description = models.TextField(_("설명")) class Event(TimestampedModel): """ 재고 변화 내역 """ event_type = models.CharField( _("재고 변화 타입"), choices=EVENT_TYPE_CHOICES, max_length=2 ) store = models.ForeignKey( "Store", verbose_name=_("입점처"), on_delete=models.CASCADE, blank=True, null=True, ) description = models.TextField(_("설명")) # events/factories.py import factory from events.models import ( EVENT_TYPES_ABOUT_STORE, EVENT_TYPE_CHOICES, ) class StoreFactory(factory.django.DjangoModelFactory): class Meta: model = "events.Store" django_get_or_create = ("name",) name = factory.Sequence(lambda n: f"store_{n}") description = factory.Sequence(lambda n: f"description_{n}") class EventFactory(factory.django.DjangoModelFactory): class Meta: model = "events.Event" event_type = factory.Faker( "random_element", elements=[choice[0] for choice in EVENT_TYPE_CHOICES] ) description = factory.Sequence(lambda n: f"event_{n}") @factory.lazy_attribute def store(self): if self.event_type in EVENT_TYPES_ABOUT_STORE: return StoreFactory() return None In [20]: Store.objects.last() Out[20]: <Store: store_10> In … -
Django pagination with no primary key
I have this function in views.py that will display all categories in a research management system following several tutorials: def CategoryView(request): cat_menu=Category.objects.all(); return render(request, 'Category.html',{'cat_menu':cat_menu}) When a user clicks on a category, they will get all the research papers that are under this category Views.py def ResearchCategoryView(request,cats): category_research=ResearchesList.objects.filter(research_category=cats.replace('_',' ')) return render(request,'Researches-Guest.html',{'cats':cats.title().replace('_',' '),'category_research':category_research,}) I would like to add a paginator to ResearchCategoryView, except I can't link to the same url as the category is not a primary key in the research table. Is there a way to do this without having to rewrite ResearchCategoryView? urls.py path('',views.GuestHome,name="GuestHome"), path('FeedBackForm',views.Form2,name="FeedBackForm"), path('FeedBackRecieved',views.ThankYou,name="ThankYou"), path('Category/',CategoryView,name='Categorys'), path('Category/<str:cats>',ResearchCategoryView,name='researchcategory'), path('Category/cats',ResearchCategoryView,name='researchcategory2'), path('Research/<int:pk>',AbstractView.as_view(),name='abstract'), path('search_research', views.search_research, name='search_research'), ** models.py inspected from mySQL** class ResearchesList(models.Model): research_id = models.AutoField(primary_key=True) title = models.TextField() auther = models.TextField() auther1 = models.TextField(blank=True, null=True) auther2 = models.TextField(blank=True, null=True) auther3 = models.TextField(blank=True, null=True) auther4 = models.TextField(blank=True, null=True) auther5 = models.TextField(blank=True, null=True) auther6 = models.TextField(blank=True, null=True) abstract = models.TextField() publish_date = models.DateField() start_date = models.DateField() finish_date = models.DateField() research_url = models.TextField() journal_name = models.CharField(max_length=100) research_category = models.CharField(max_length=70) data_type = models.CharField(max_length=45, blank=True, null=True) data_source = models.TextField(blank=True, null=True) geo_area = models.CharField(max_length=45, blank=True, null=True) is_collected_via_socialmedia = models.CharField(max_length=45, blank=True, null=True) collecation_start_date = models.DateField(blank=True, null=True) finishing_colleaction_date = models.DateField(blank=True, null=True) date_of_the_data = models.DateField(blank=True, null=True) sample_size = models.IntegerField(blank=True, null=True) … -
How to run a .py file when clicked the html button using django
i create a gui-app using python and the file named gui.py and also create a simple website using django. now in my website there is a button named 'open the gui-app'. now whenever someone click the button, the gui-app i mean the gui.py file will run. how to do this. here is the html code: <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Hello, world!</title> </head> <body><h1>Hello, world!</h1> <button type="button" class="btn btn-primary">Open the gui-app </button> //using bootstrap </body> </html>``` -
Can't connect to Websocket on Django with Heroku
I'm trying to deploy my Django app to Heroku. The thing is, when I try to test the Websocket I implemented, it doesn't connect. (Btw, I'm using the Postgres service that Heroku gives to storage my data). This is what I get when I try to test it: It's from a website called https://hoppscotch.io/realtime/ Here's the config of my Procfile: web: gunicorn kuropoly.wsgi. The routing.py part is configured like this: from django.conf.urls import url from apps.websocket.consumers import KuropolyConsumer websocket_urlpatterns = [ url(r'^wss/play/(?P<idRoom>\w+)/$', KuropolyConsumer.as_asgi()), ] And, as it says there on the code, I'm using ASGI, here's the config for that: asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import apps.websocket.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kuropoly.settings') # application = get_asgi_application() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( apps.websocket.routing.websocket_urlpatterns ) ), }) On my settings.py I have this: ASGI_APPLICATION = "kuropoly.asgi.application" CHANNEL_LAYERS = { 'default': { ## Via In-memory channel layer "BACKEND": "channels.layers.InMemoryChannelLayer" }, } # Activate Django-Heroku. import django_heroku django_heroku.settings(locals()) import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) I've tried changing my Procfile but that didn't work, I don't know if it's because of the fact that I'm using gunicorn (and I used that following the Heroku … -
how to have an integer along with ManytoMany field in django
So I am trying to finish up a recipe app, however storing my ingredients volume is a bit hard. eg: 3 - eggs, 1 butter, etc I did my models like this: class IngredientList(models.Model): name = models.CharField(max_length=100) recipes = models.ManyToManyField('RecipeList', through='ShoppingList') def __str__(self): return self.name class RecipeList(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField( 'IngredientList', through='ShoppingList') instructions = models.TextField(max_length=400) amount_made = models.IntegerField() def __str__(self): return self.name class ShoppingList(models.Model): ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE) recipe = models.ForeignKey(RecipeList, on_delete=models.CASCADE) amount_needed = models.IntegerField(default=1) if this is correct, how do I go forward with my views.py and outputing in my template? from django.shortcuts import render from .models import IngredientList, RecipeList, ShoppingList def index(request): recipe = RecipeList.objects.all() context = {'recipe': recipe} return render(request, 'recipe/home.html', context) and {% for i in recipe %} <div class="card col-sm-3 m-2 p-2"> <img class="card-img-top img-fluid" src="https://www.seriouseats.com/recipes/images/2014/09/20140919-easy-italian-american-red-sauce-vicky-wasik-19-1500x1125.jpg "> <div class="card-body"> <h4>{{ i.name}} <span class="badge badge-info">{{i.cuisine}}</span></h4> <p class="card-text">Ingredients: {% for k in i.ingredients.all %} {{k}}, {% endfor %}</p> <p class="card-text">Instructions: {{i.instructions}}</p> <p class="card-text">This makes {{ i.amount}} meals</p> </div> </div> {% endfor %} but this only outputs the name of the ingredient, but i want to add the amount when saving the ingredients needed for recipe -
how to annotate each object with random value
I want to have items with random annotations. I tried this: items = Item.objects.all()).annotate(random_value=Value(randint(1,6)),output_field=PositiveIntegerField())) And it is random, but THE SAME for EVERY Item in QuerySet. But I want to have DIFFERENT value for EACH Item... Any ideas? -
Matching query does not exist issue Django
I am trying to create a web app that has a Like button option for the Post. Everything works fine but when I click on the Like button it shows DoesNotExist error. This is the model part of the code: class Like(models.Model): user = models.ForeignKey(Yatru, on_delete=models.CASCADE) location = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.location}-{self.value}" This is the views: def like_unlike(request): user = request.user if request.method == 'POST': location_id = request.POST.get('location_id') location_obj = Post.objects.get(id=location_id) profile = Yatru.objects.get(user=user) if profile in location_obj.liked.all(): location_obj.liked.remove(profile) else: location_obj.liked.add(profile) like, created = Like.objects.get_or_create(user=profile, location_id=location_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' location_obj.save() like.save() return redirect('posts:post_views') When I try to load the page it shows this error: -
django.db.utils.OperationalError: fe_sendauth: no password supplied when migrating django app
I'm a beginner with Django working on an open source project, which has been very challenging since it only gives build instructions for Mac, and not Linux. So, on my Ubuntu server, I've managed to install all the packages and fix a few initial bugs, but now, when I do python manage.py migrate, I'm stuck with this error: django.db.utils.OperationalError: fe_sendauth: no password supplied I'm totally stuck here: I'm having a tough time understanding the error message, and other solutions aren't much help. Other solutions indicate that you have to change the DATABASES setting in the settings.py, but the setting has no PASSWORD attribute and it's only linked to sqlite: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'] = dj_database_url.config() The error doesn't trace back to any specific lines of code so I'm guessing its more related to psycopg2 or django than the code itself, but I'm not sure how to go about fixing it. I'm using Python 2.7.17 and Ubuntu 18.04.5. Here's the full error message: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line … -
Django: "extends" not working in template
I followed the latest Django documentation, using the {% extends %} keyword the same way they do in their example but I can't get it to work. What am I doing wrong? base.html: the content block defined in transaction_detail.html below works: <div class="row"> <div class="col-md-8"> {% if messages %} {% endif %} {% block content %}{% endblock %} <!--This block defined in transaction_detail.html is displaying correctly --> </div> ... transaction_detail.html: Note that the test block is contained within the content block. Is that allowed? {% extends 'blog/base.html' %} {% block content %} <!-- This block displays correctly --> <div class="content-section"> <!-- Chat --> {% block test %} <!-- This block does not display at all --> {% endblock %} <div> ... room.html: {% extends 'blog/transaction_detail.html' %} {% block test %} <div class="messages"> <ul id="chat-log"> </ul> <div class="message-input"> <div class="wrap"> <input id="chat-message-input" type="text" placeholder="Write your message..." /> <button id="chat-message-submit" class="submit"> <i class="fa fa-paper-plane" aria-hidden="true"></i> </button> </div> </div> </div> {% endblock %} settings.py (TEMPLATES variable only): I have all apps listed in INSTALLED_APPS TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #DIRS: a list of directories where the engine should look for template source files, in search order. 'DIRS': [os.path.join(BASE_DIR, ''), # root directory … -
Is there a way to maintain structure of nested serializer output across different levels?
I've included a simple example below which will help illustrate the question I'm trying to ask. May have typos/errors since I'm not running the code. Suppose we have models Singer, Album and Track. A singer can have multiple albums and an album multiple tracks (just a series of one to many relationships). ### Models ### class Singer(Model): singer_name = models.CharField(max_length=20) class Album(Model): singer_id = models.ForeignKey(Singer) album_name = models.CharField(max_length=20) class Track(Model): album_id = models.ForeignKey(Album) track_name = models.ChairField(max_length=20) ### Serializers ### class TrackSerializer(ModelSerializer): class Meta: model = Track fields = ['track_name'] class AlbumSerializer(ModelSerializer): tracks = TrackSerializer(read_only=True,many=True) class Meta: model = Singer fields = ['album_name','tracks'] class SingerSerializer(ModelSerializer): albums = AlbumSerializer(read_only=True,many=True) class Meta: model = Singer fields = ['singer_name','albums'] If we have a simple view that requires a singer's name for input, the Singer Serializer would output the following. ### SingerSerializer Output ### { "singer_name":"Singer A", "albums": [ { "album_name":"Album 1", "tracks": [ {"track_name":"Track 1"}, {"track_name":"Track 2"} ] }, { "album_name":"Album 2", "tracks": [ {"track_name":"Track 3"}, {"track_name":"Track 4"} ] } ] } Now suppose in a separate view, I would like people to be able to input an album name (let's say Album 1 in this case). I'd like the output to maintain the … -
ImportError: Couldn't import Django. Working in virtual environment
Hello! As the image shows, I activate the env where I already installed Django. After that, I try to run python3 manage.py runserver and an error message appears, saying Django couldn't be imported. I'm working on Windows 10. I followed the steps given by Delicia Brummitt here but couldn't get it working. What am I doing wrong? Thanks in advance. -
Django Display Live Data without page Refresh
I have developed django application, which basically do tracer route on Cisco devices at a time multiple devices , everything is working fine, but output is displaying after getting output from all devices, I want output to be displayed once we got output from first device, and after getting second that output to be displayed in web page and it go one, please help how to accomplish. How to use ajax here if we have to use -
Mostrar un dataframe en una tabla de un template de Django
Estoy construyendo una tabla con información obtenida de varios dataframe en Django, consigo mostrar correctamente aquellas que conozco el nombre de la columna pero tengo un dataframe que las columnas son dinámicas en función de los días que tiene el mes y esas no consigo mostrarlas. El DataFrame lo creo así vector_notas2=[] sqlconsulta2="SELECT NOTAS,DAY(FECHA) FROM HISTORICOS WHERE MONTH(FECHA)=" + str(mes) + " AND YEAR(FECHA)=" + str(ano) +" AND NOMBRE='" + nombre + "' ORDER BY FECHA" cur2.execute(sqlconsulta2) for notas2,fecha in cur2.fetchall(): vector_notas2.append(round(notas2)) df[nombre]=vector_notas2 El nombre de las columnas está en función de los clientes que tienen datos 5 2758.0 1215.0 ... 0.0 0.0 6 3538.0 1712.0 ... 2.0 2.0 7 2885.0 1774.0 ... 11.0 1.0 8 2459.0 1573.0 ... 7.0 1.0 9 2425.0 1668.0 ... 1.0 0.0 10 2879.0 1987.0 ... 2.0 0.0 11 2614.0 1059.0 ... 0.0 0.0 12 3152.0 1519.0 ... 0.0 0.0 13 2660.0 1609.0 ... 0.0 1.0 14 2464.0 1565.0 ... 5.0 0.0 15 2786.0 1959.0 ... 1.0 2.0 16 1054.0 1040.0 ... 8.0 0.0 17 2987.0 1034.0 ... 0.0 0.0 18 3146.0 1489.0 ... 1.0 0.0 19 2691.0 1697.0 ... 4.0 0.0 20 2329.0 1653.0 ... 7.0 2.0 21 2455.0 2159.0 ... 3.0 0.0 22 …