Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django Attribute Error - 'ForwardManyToOneDescriptor' object has no attribute 'courses'
I have created different models and in the Division model I am taking reference of many models and their primary key is referenced as a foreign key in Division Model. I have declared courses as a model attribute in the Batch Model. This is my models.py file class lab_load(models.Model): lab_code = models.CharField(max_length=10,null=True) subject_name = models.CharField(max_length=100,null=True) subject_abv = models.CharField(max_length=10,null=True) lab_load = models.IntegerField(null=True) semester = models.IntegerField(null=True) max_numb_students = models.CharField(max_length=65,null=True) instructors = models.ManyToManyField(Instructor) def __str__(self): return f'{self.lab_code} {self.subject_name} {self.subject_abv}' class Batch(models.Model): bat_name = models.CharField(max_length=50) courses = models.ManyToManyField(lab_load) @property def get_courses(self): return self.courses def __str__(self): return self.bat_name class Division(models.Model): division_id = models.CharField(max_length=25, primary_key=True) batch = models.ForeignKey(Batch, on_delete=models.CASCADE,blank=True, null=True) num_lab_in_week = models.IntegerField(default=0) course = models.ForeignKey(lab_load, on_delete=models.CASCADE, blank=True, null=True) lab_time = models.ForeignKey(LabTime, on_delete=models.CASCADE, blank=True, null=True) room = models.ForeignKey(LabRoom,on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE, blank=True, null=True) def set_labroom(self, labroom): division = Division.objects.get(pk = self.division_id) division.room = labroom division.save() def set_labTime(self, labTime): division = Division.objects.get(pk = self.division_id) division.lab_time = labTime division.save() def set_instructor(self, instructor): division = Division.objects.get(pk=self.division_id) division.instructor = instructor division.save() My views.py file class Data: def __init__(self): self._rooms = Room.objects.all() self._meetingTimes = MeetingTime.objects.all() self._instructors = Instructor.objects.all() self._courses = Course.objects.all() self._depts = Department.objects.all() self._labrooms = LabRoom.objects.all() self._labTimes = LabTime.objects.all() self._labcourses = lab_load.objects.all() self._bats = Batch.objects.all() def get_rooms(self): … -
Problem with audio in Django,<audio> doesn't work
I want to do audio-player in Django,but i have some problems. Here is my models.py class Music(models.Model): name = models.CharField(max_length=50) author = models.CharField(max_length=100) audio_file = models.FileField(upload_to='D:/pythonProject/music/player/templates/music/', blank=True) def __str__(self): return f"{self.author}---{self.name}" views.py def main_page(request): music_list=Music.objects.all() return render(request, 'player/main_page.html', {'music_list': music_list}) and template {% if music_list %} {% for music in music_list %} <audio controls> <source src="{{music.audio_file}}" type="audio/mpeg"> </audio> {% endfor %} {% endif %} When i started my page,i have this : main_page Also,i have "GET / HTTP/1.1" 200 169" in my terminal. Can someone help me with this? Thank!) -
Choice Field Instance Not Displaying Correct Data But Other Fields Are
I am trying to display a ModelForm with prepopulated instance data. It works fine except for the ChoiceField which always displays the first choice given in forms.py ('LP') rather than the choice provided by the instance. View: def review(request): order = Order.objects.get(user__pk=request.user.id) form = ProjectReviewForm(instance=order) context = { 'form': form, } return render(request, 'users/projectreview.html', context) Forms: class ReviewForm(forms.ModelForm): LAND = 'LP' // #INSTANCE ALWAYS SHOWS THIS RATHER THAN INSTANCE DATA DATA = 'DC' STATIC = 'SW' CHOICES = ( (LAND, 'LP'), (DATA, 'DC'), (STATIC, 'SW') ) product = forms.ChoiceField(choices=CHOICES, widget=forms.Select(attrs={'class': 'form-field w-input'}),) class Meta: model = Order fields = '__all__' template: <form method="POST" class="contact-form"> {% csrf_token %} <h2 class="form-heading-small">Please make sure everything you've submitted is correct.</h2> {{ form }} <button type="submit" data-wait="Please wait..." class="button w-button">Looks good!</button> </form> -
Static media images are not displaying in Django
I am working on an online bookstore app. I have a book details page that displays book information in a table, including the book cover image. I am having an issue where the images display correctly when I runserver, however a team member is unable to get the images to display after pulling my code from Github. **all books template:** {% extends 'bookstore/main.html' %} {% load crispy_forms_tags %} {% load static %} from .models import Product {% block content %} <div class="container"> <p> <h1 style="text-align:center;color:green;"> GeekText Complete List of Books<br> </h1> <h3 style="text-align:center;color:green;"> Click the Book Name for More Details </h3> </p> <!-- Bootstrap table class --> <div class="container"> <div class="col-md-12"> <table id="myTable" class="table table-striped tablesorter"> <thead> <tr> <th scope="col">ID #</td> <th scope="col">Book Title</td> <th scope="col">Genre</th> <th data-sorter="false" scope="col">Cover Image</td> <th scope="col">Author</td> </tr> </thead> <tbody> {% for item in items %} <tr> <td scope="row">{{ item.id }}</td> <td><a href="{% url 'book_details_with_pk' id=item.id %}">{{ item.name }}</a></td> <td>{{ item.genre }}</td> <td><img src="{% static item.image %}" width="75" height="100"/></td> <td>{{ item.author }}</td> <td><a href="{% url 'addtocart' item.id %}" class="btn btn-primary">Add To Cart</a> </tr> {% endfor %} </tbody> </table> {% endblock %} </div> </div> </div> **views.py** from django.shortcuts import render, redirect from django.db.models import Q from …