Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to code and to connect two models in python
I have created a "quote" app and in my next phase I would like to create a dropdown list with my "contacts". I'm only wondering what is the easiest, and best practices to create another class with the details of the contacts, or creating a new "app" to hold all the details of the contacts. -
Django Rest Framework Admin Site doesn't Load
Whenever I try to run python manage.py runserver and go to the admin site, I lose connection to the server immediately. The API Root page works fine it is just the admin page. The code is based on the Django Rest Framework Quickstart tutorial with the addition of a model, it's serializer and the respective view. All migrations have been made. (venv) ~\Back-End\iBMS>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 04, 2020 - 02:11:20 Django version 3.0.5, using settings 'iBMS.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (venv) ~\Back-End\iBMS> Here are my code files: #urls.py """iBMS URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path from rest_framework import routers … -
Django rest framework Post request
I am creating django + react app and i want to pass data by django rest framework. models.py class User(AbstractUser): def __str__(self): return self.username class Address(models.Model): username = models.ForeignKey(User,related_name='address',on_delete=models.CASCADE) street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Addresses' def __str__(self): return '%s %s %s %s' % (self.street_address, self.apartment_address, self.country, self.address_type) serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('street_address','apartment_address','country') class UserSerializer(serializers.ModelSerializer): address = serializers.StringRelatedField(many=True) class Meta: model= User fields = ('email','username','password','address')``` views.py class UserViewSet(viewsets.ModelViewSet): serializer_class=UserSerializer queryset = User.objects.all() class AddressViewSet(APIView): def get(self, request, format=None): address = Address.objects.all() serializer = AddressSerializer(address, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = AddressSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @classmethod def get_extra_actions(cls): return [] My get request looks good because it returns value but it looks like something wrong is with AddressSerializer(data=request.data) -
how to use order by on a field in which value like 10 GB and 10 TB in django queryset
limited_plans = Subscription_plan.objects.filter(plan_type__type__iexact='limited', status='1', connection_type_id='1').annotate( total=Sum(Case(When(validity_type='2', then=ExpressionWrapper(F('validity') * 30, output_field=IntegerField())), When(validity_type='1',then=ExpressionWrapper(F('validity'), output_field=IntegerField())), default=IntegerField())), fup_li=Sum(Case(When(fup_li_sign = 'GB',then=ExpressionWrapper(F('fup_li_value') * 1000, output_field=IntegerField())), When(fup_li_sign = 'TB', then=ExpressionWrapper(F('fup_li_value'), output_field=IntegerField()))), default=IntegerField()) ).extra(select={ 'fup_li_sign': "SUBSTR(fup_limit, 2)", 'fup_li_value': "CAST(substr(fup_limit, 1) AS UNSIGNED)"} ).order_by('total', 'fup_li') -
Django datefield default save format overwriting
I have a postgresql9.6 table which has a char field: 'start_date', and the format like '20200101'. And I created a Django2.0 model: class TestModel(models.Model): start_date = models.DateField('start_date') My admin.py is: class TestAdmin(admin.ModelAdmin): list_display = ('start_date',) admin.site.register(TestModel, TestAdmin) And I also modify settings.py: USE_L10N = False DATE_INPUT_FORMATS = ['%Y%m%d'] DATE_FORMATS = ['%Y%m%d'] So I get the date in web form:'20200101', but when I save the form, shows a error: 'value has an invalid date format. It must be " "in YYYY-MM-DD format.' I know the DateField save the date default use 'YYYY-MM-DD' format, but I need to change it to 'YYYYMMDD' so I can save the consistent data into pg database. So how to overwriting the DateField or Model function to change the default format? -
NoModuleFoundError:No module named learning_logs.urls
I'm learning django with the book "python crash course". After I created the urls.py in learning_logs, it always said the learning_logs.urls couldn't be found. I really don't know why! BTW, it worked yesterday, but today I ran again, and the bug came! enter image description here enter image description here enter image description here enter image description here -
How do I properly link my CommentCreateView to my post_detail view?
I have two models, Post and Comment. My Comment model contains the model Post as a foreign key, which matches each comment to a particular post. I have two views: a post_detail view where I can see a post, and a CommentCreateView to create a comment. I created a comment_new.html template that contains the CommentCreateView form, and included the comment_new.html template into my post_detail.html template. However, the actual form to post the comment in doesn't show up, only the 'Post' button does. Here is a snippet of the template and the HTML rendered. post_detail.html {% include 'comment_new.html' %} comment_new.html <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Post</button> </form> HTML Rendered: I think the problem is that the CommentCreateView does not know what Post to be linked to, but I'm not certain, so if you have any suggestions, I'm definitely open to any. My question is, I'm not sure how I can get the primary key of the post, and send the data to the CommentCreateView form so that the comment knows which post it needs to be in. Here are the relevant snippets of my code, below. Thank you! Models.py: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') … -
Style for a selectbox CSS and HTML
Somebody just helped me to remove the outline of my selectbox (from my first bootstrap-django project) Now, i wanted to ask for your help to change the border color property of the options box itself, which is blue, and i'm trying to make it yellow. Also, for some reason when the select box has the default value, its border is yellow but after you select one of the options, it becomes darker, and i would like it to be darker from the beggining. Here is my CSS: .selector{ outline:none; position:absolute; border-radius:1rem; margin-left:260px; width:500px; border-color: #C9C9C9; height:35px; font-size: 15px; text-align-last: center; color:#C9C9C9; } .selector:focus{ border-color:#FFD700; box-shadow: 0 0 8px #FFD700; } And my HTML: <div class="div1"> <label for="estado" class="label1"> Estado <select class="selector" id="estado" name="estado" onchange="functionfs()" style="border-color: #C9C9C9; "> <option style="color:black" selected="selected" value="-----">--- Ingrese un valor ---</option> <option value="Activo" style="color:black;">Activo</option> <option value="Inactivo" style="color:black;">Inactivo</option> </select> </label> </div> And my JS: <script type="text/javascript"> var selector = document.getElementById("estado"); function functionfs(valor){ selector.setAttribute("style", "color:black;"); } </script> I will also attach 2 images of the problem itself. As you can see, when i select one of the two states and click it again, it becomes darker. Thanks everyone! -
Change a set to a dictionary - Django Python
I am trying to combine these two views. This is what I have. MenuView is to combine with add_to_menu so that if the if statement returns negative, the menuview portion still runs and displays the menu on my html page. If the if the statement is positive, it still shows the menu, but also adds the entered information into the database. I can only get one or the other to work at a time. When I run this, I get an error telling me it has to be a dictionary and not a set. Views.py: class MenuView(ListView): model = Product template_name = 'mis446/edit-menu.html' context_object_name = 'show_menu' def add_to_menu(request): if request.method == 'POST': if request.POST.get('name') and request.POST.get('price') and request.POST.get('nickname'): post=Product() post.name= request.POST.get('name') post.price= request.POST.get('price') post.slug= request.POST.get('nickname') post.save() model = Product context_object_name = {'show_menu'} return render(request, 'mis446/edit-menu.html', context_object_name) else: model = Product context_object_name = {'show_menu'} return render(request,'mis446/edit-menu.html') -
Django management command not capturing command line arguments
I am trying to run a Django management command with some optional arguments. The relevant code is below. def add_arguments(self, parser): parser.add_argument('--from-date', type=str, help='Some help text') parser.add_argument('--to-date', type=str, help='Some help text') parser.add_argument('--from-type', type=str, help='Some help text') parser.add_argument('--until-type', type=str, help='Some help text') def handle(self, *args, **options): from_date = options.get('from-date') to_date = options.get('to-date') from_type = options.get('from-type') until_type = options.get('until-type') When I try to run the command in the terminal as follows, the arguments aren't being picked up. python manage.py [NAME OF COMMAND] --from-date 2020-04-02 --to-date 2020-04-03 Why is this? Thank you. -
creating a related field, when initiating user, in Django
I have a model like this: class CustomUser(AbstractUser): history = models.TextField(verbose_name="History", max_length=500,default='-') def save(self, **kwargs): super(CustomUser, self).save(**kwargs) self.apayment4thisuser.create(catagory="trial",paid=0,paymenttoken="#") So the idea is to create a default related payment model (apayment4thisuser), when a user is created. This works fine,but the problem is that it will run Save() whenever the user is updates too(obviously). However I need this to be run just once. i.e., only when user signs up and created in the database for the first time. I don't need it when an existing user is updated. What would be the best way to achieve this? Thanks, -
How to amend the default starting script for Django Console in Pycharm
The starting script defaults to the following every time I start a new project. import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) import os os.environ.setdefault("DATABASE_URL","postgres://{}:{}@{}:{}/{}".format(os.environ['POSTGRES_USER'], os.environ['POSTGRES_PASSWORD'], os.environ['POSTGRES_HOST'], os.environ['POSTGRES_PORT'], os.environ['POSTGRES_DB'])) sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS]) if 'setup' in dir(django): django.setup() import django_manage_shell; django_manage_shell.run(PROJECT_ROOT) Is there a way to change this default script? I've tried to do so under File>Default Settings, but there is only Python console listed here; Django console isn't listed. -
Getting this error: argparse.ArgumentError: argument -d/--to-date: conflicting option string: -d
I am writing a Django management command. I would like to include optional arguments. Within the Command class, I wrote: def add_arguments(self, parser): parser.add_argument('-d', '--from-date', type=str, help='Some help text') parser.add_argument('-d', '--to-date', type=str, help='Some help text') parser.add_argument('-d', '--from-type', type=str, help='Some help text') parser.add_argument('-d', '--until-type', type=str, help='Some help text') But whether I run the command with or without arguments, I get the following error: argparse.ArgumentError: argument -d/--to-date: conflicting option string: -d What am I doing wrong? Thank you. -
Selectbox border color
Right now i'm working with a select box for my first django-bootstrap project. I'm trying to style it so when you click on it its border and the options box border turns yellow, and that's working fine, but there is also a blue rectangle around my selectbox when i click on it that i don't really want. Here is my code: (Styles.css) .selector{ position:absolute; border-radius:1rem; margin-left:260px; width:500px; height:35px; font-size: 15px; text-align-last: center; color:#C9C9C9; transition-property: none; } .selector:focus{ border-color:#FFD700; box-shadow: 0 0 8px #FFD700; border-radius:1rem; overflow:hidden; } And my HTML Template: <div class="div1"> <label for="estado" class="label1"> Estado <select class="selector" id="estado" name="estado" onchange="functionfs()" style="border-color: #C9C9C9;"> <option style="color:#C9C9C9" selected="selected" value="-----">--- Ingrese un valor ---</option> <option value="Activo" style="color:black;">Activo</option> <option value="Inactivo" style="color:black;">Inactivo</option> </select> </label> </div> Attached there is an image with more details. Thanks to anyone willing to respond! Image -
How do i access the context data in the template?
context_object_name = 'item_list' template_name = 'krop_view.html' model = Item def get_queryset(self): user = self.request.user #gets current user object krop = get_object_or_404(Krop, owner=user) return Item.objects.filter(krop=krop) def get_context_data(self, **kwargs): context = super(KropListView, self).get_context_data(**kwargs) user = self.request.user context['krop'] = Krop.objects.filter(owner=user) return context A "Krop" is technically a shop with items, i can get all items for the shop owned by the current user. I want to also access data from the Krop model so I passed in the krop context data related to current user. How do I access this context data in the template? I've tried and looked up ways to get the specific variables like: {{ krop.owner }} {{ item_list.krop.owner }} ultimetley I want to access data from two different tables, but for one page. Please and thank you!!! -
How can I display pandas dataframe into django template?
I have a pandas dataframe and i want to show this dataframe into my django template. But everytime the code compile successfully without showing any table in my django web app. What am i missing here? My data frame looks like this: dataframe sample and my html looks like: <div class="row" style="margin-bottom: 20px;"> <div class="col-md-3"> </div> <div class="col-md-9"> <div class="card" style="width: auto;"> <div class="card-body"> <h3 class="h3">Total match data and Profit Mergin</h3> <br> <table class="table table-striped"> <tr> <th>Total Contest</th> <th>Total Entry Amount</th> <th>Total Seat</th> <th>Total Winning Amount</th> <th>Total Team Capacity</th> <th>Profit Mergin</th> {% for value in final_data.iterrows %} <tr> <td>{{ value.0 }}</td> <td>{{ value.1 }}</td> <td>{{ value.2 }}</td> <td>{{ value.3 }}</td> <td>{{ value.4 }}</td> <td>{{ value.5 }}</td> </tr> {% endfor %} </table> </div> </div> </div> </div> i tried final_data.itertuplus but still got the same result. What should i do now? -
AttributeError: 'list' object has no attribute 'first'
lebel_months = [] members_exps = [] for member in team.members.all(): qs = Profile.objects.expenses_per_month(member.user) clr = color_picker() member_qs = [] for exp in qs: user = get_object_or_404(User, id=exp.user_id) month = exp.month summary = exp.sum if month not in lebel_months and month is not None: lebel_months.append(month) if month is not None and summary is not None: member_qs.append({ 'user': user.username, 'clr': clr, 'month': month, 'summary': summary}) if member_qs: members_exps.append(member_qs) print(members_exps[0]) print(members_exps.first()) outputs: with [0] everything works [{'user': 'serj', 'clr': '#71CABC', 'month': datetime.datetime(2020, 3, 1, 0, 0, tzinfo=<UTC>), 'summary': 128400}, {'user': 'serj', 'clr': '#71CABC', 'month': datetime.datetime(2020, 4, 1, 0, 0, tzinfo=<UTC>), 'summary': 53500}] with first() AttributeError: 'list' object has no attribute 'first' First print statement works. Second print statement catch an error. What am I doing wrong? -
Self-referencing foreign keys are listing everything if the value is null in Django-admin Page
I have a django model as below: class Words(models.Model): bare = models.CharField(max_length=100) accented = models.CharField(max_length=100) derived_from_word = models.ForeignKey('self', models.DO_NOTHING, blank=True, null=True, related_name='derived_words', related_query_name='derived_word') There is a field derived_from_word which shows that some of the words are derived from some other word. If it is not derived from any word so the field value is NULL. What issue i am having that when i register this model in the django-admin and when i opened any of the word for editing, the derived_from_word field is listing all the words and i can not find a way for it to list only the derived word or the NULL value. Due to high load of the words the drop down list is making the page unresponsive. -
Deploying Django To Heroku gives server error (500)
please i know this question has been asked several times but with those answers i still haven't solved it.I turned debug to False in my settings.py file (but before I turned it to false, everything was working perfectly) and when I ran git push heroku master and went to my website,I got an error saying Server Error (500). please i need help. please here is my settings.py import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'KEY' DEBUG = False ALLOWED_HOSTS = ['.herokuapp.com'] INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'mysite.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', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' django_heroku.settings(locals()) here is my wsgi.py import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application)] here is my procfile web: gunicorn mysite.wsgi here is also the log 2020-04-03T23:19:17.048794+00:00 heroku[router]: at=info method=GET path="/" host=jimtec.herokuapp.com request_id=f256ae96-58b7-4b3d-8918-ebe9c5039a8f fwd="102.176.94.105" dyno=web.1 … -
How will I connect my index.html to my views.py?
I tried doing this: But my page says that TemplateDoesNotExist. What should I do? -
Type error: Profile object is not iterable
First time using a custom user model so I'm having trouble referencing the user object in views. I have tried a number of things but I'm really having difficulty grasping how to reference the user object within views with what I am trying to do. error TypeError at /mingle/ 'Profile' object is not iterable Request Method: GET Request URL: http://localhost:8000/mingle/ Django Version: 2.2.3 Exception Type: TypeError Exception Value: 'Profile' object is not iterable Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py in inner, line 257 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 Python Version: 3.7.3 Python Path: ['/Users/papichulo/Documents/DatingApp', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Server time: Sat, 4 Apr 2020 01:30:02 +0000 error is showing up here **description = Profile.objects.get(request.user).description ** **views.py, part that's giving me an error ** from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.contrib.auth import login, logout, authenticate from dating_app.forms import RegistrationForm,ProfileUpdateForm from .models import Profile from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User import os from django.core import serializers import json from django.contrib.auth import get_user_model User = get_user_model() def mingle(request): try: user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user = None print(User.username) try: description = models.Profile.objects.get(user=request.user).description except … -
heroku 404 with django on deploy from git
I am having the error 404 when i open or deploy my app on heroku on the logs it doesnt show an actual line of error, i have follow the guidelines on the heroku and still i dont get it , already done the debug and disable with the collectstatic , did the migrate and makemigrations , check wsgi according to the whitenoise recent version which is moving it from that file my settings.py import os import django_heroku import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '******' DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'buscador', 'bootstrap4', 'gunicorn', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = '*****.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], '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 = '******.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propogate': False, } }, }, 'NAME': '****', 'CLIENT': { 'host': 'mongodb+srv://*****:*****@mongodb-cluster-us-east-1-yuln1.mongodb.net/test?retryWrites=true&w=majority', } } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, … -
Django 'extends' in html file from another app cover 'original' html file
I'm using base.html from another app, and in another app, it works perfectly. But in new app, I extends it, and I could load base.html with stylesheet, but the problem is they only load base.html file. I have no idea why it happens, and just guess maybe it's because of TemplateView and ListView, cuz I haven't used it before, so I can just guess that's the only reason. But I want to use it as well. This is my code. New app is 'search', another app is 'posting'. search/templates/search/index.html {% extends "posting/base.html" %} {% block contents %} <div class='searchform'> <form action="{% url 'search:results' %}" name="se" method="GET"> <label for='search'>What are you looking for?</label> <input type="text" name='q'> <input type="submit"> </form> </div> <script src="" async defer></script> {% endblock %} search/templates/search/beerlist.html {% extends "posting/base.html" %} {% block contents %} <ul> {% for beer in beerlist %} <li><a href="/search/{{ beer.id }}">{{ beer.name }}</a></li> {% endfor %} </ul> {% endblock %} serach/views.py ... class index(TemplateView): template_name = 'search/index.html' class Results(ListView): model = Beerinfo template_name = 'search/results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Beerinfo.objects.filter( Q(name__icontains = query) | Q(label__icontains = query) ) return object_list ... search/urls.py urlpatterns = [ path('', TemplateView.as_view(template_name = "search/index.html"), name='index'), path('results', views.Results.as_view(template_name … -
Django Rest Framework, overwrite _declared_fields attribute of serializer meta class
I am trying to decorate a serializer in order to add help text, like so: def help_decorator(*args, **kwargs): def inner(cls, sources=kwargs["sources"]): for k,v in sources.items(): cls._declared_fields[k].help_text = v return cls return inner help_text_source = {"foo": "help_foo", "bar": "help_bar"} @help_decorator(sources=help_text_source) class FoobarSerializer(serializers.Serializer): foo = serializers.CharField(max_length=10) bar = serializers.IntegerField() I've put a debugger into the function, and cls._declared_fields has been modified as expected. Then, the Serializer Meta class is instantiated to return a Serializer class: serializer = FoobarSerializer() Inspecting serializer.fields["name_of_fields"], shows that none of the fields have retained the help text. -
HTML Video tag not finding file
Using Django, trying to pull a video from a model. I appear to be pulling the correct file path but the video isn't being located. Have tried adding the full system directory from hard drive rather than just the context folder, hasn't worked out for me either. Have confirmed that video is in that location. Should I be using statics for this? Or not because it's located in a model? video_output.html {% extends 'highlights/base.html' %} {% block content %} {% for video in highlights %} <video width="320" height="240" controls> <source src="/media/{{ video.highlight }}" type="video/mp4"> Your browser does not support the video tag </video> {% endfor %} {% endblock %} From views.py def video_output(request): entrydata = Video.objects.last() context = { 'highlights' : Highlight.objects.filter(sourcevideo=entrydata.video_id) } return render(request, 'highlights/video_output.html', context) Console output [04/Apr/2020 11:32:13] "GET /highlights/outputs HTTP/1.1" 200 1960 Not Found: /media/highlights/812.mp4 Not Found: /media/highlights/811.mp4 [04/Apr/2020 11:32:14] "GET /media/highlights/812.mp4 HTTP/1.1" 404 2129 [04/Apr/2020 11:32:14] "GET /media/highlights/811.mp4 HTTP/1.1" 404 2129 Not Found: /media/highlights/814.mp4 Not Found: /media/highlights/813.mp4 [04/Apr/2020 11:32:14] "GET /media/highlights/814.mp4 HTTP/1.1" 404 2129 [04/Apr/2020 11:32:14] "GET /media/highlights/813.mp4 HTTP/1.1" 404 2129 Not Found: /media/highlights/815.mp4 Not Found: /media/highlights/816.mp4 [04/Apr/2020 11:32:14] "GET /media/highlights/815.mp4 HTTP/1.1" 404 2129 [04/Apr/2020 11:32:14] "GET /media/highlights/816.mp4 HTTP/1.1" 404 2129 Not Found: /media/highlights/817.mp4 [04/Apr/2020 …