Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get js plugin data into django model
I am trying to use this js plugin https://www.jqueryscript.net/time-clock/appointment-week-view-scheduler.html#google_vignette I added into my project and im able to see it and play with it, but im not able to get the data. How could i retrieve the data from the js and save it into a django model? I am trying but im not able to use get function: $('#example').scheduler('val'); -
Django Problem with a form and making queries
I'm making an lms website. It has classes. Teachers can create new classes and students can add those classes with entering their id and password (if the class has any password). Classes have custom ids and password made by their teachers. The teacher side of the code works fine so I omitted it. But there's a problem in the student part. I have already made a class which requires a password. I enter its id and password in the form and when I submit, it renders the form with the 'message' which has the value: "Invalid id and/or password.". while the password and id match. What is the problem here? <p style="color: red;">{{message}}</p> {% if user.is_teacher %} <form action="{% url 'new_class' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" type="text" name="class-name" placeholder="Class Name" maxlength="64" required> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" name="class-type" id="class-type"> <label class="form-check-label" for="class-type"> Private </label> </div> <div class="form-group"> <input class="form-control" type="password" name="class-password" id="class-password" placeholder="Password" style="display: none;" maxlength="16"> </div> <input class="btn btn-primary" type="submit" value="Create"> </form> {% else %} <form action="{% url 'new_class' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" type="text" name="class-id" placeholder="Class ID" maxlength="4" required> </div> <div class="form-group"> <p><sub>Leave the password field empty if the … -
Django won't connect to Docker PostgreSQL
Created Dockerized PostgreSQL with the following settings: version: "3.8" services: db: image: postgres restart: always ports: - 5432:5432 environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres This is my settings.py file: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", "PORT": "5432", } } Initialized the container with docker-compose up, image is created and following logs are printed out: db_1 | 2022-06-01 11:45:10.788 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2022-06-01 11:45:10.788 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2022-06-01 11:45:10.791 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2022-06-01 11:45:10.795 UTC [60] LOG: database system was shut down at 2022-06-01 11:45:10 UTC db_1 | 2022-06-01 11:45:10.799 UTC [1] LOG: database system is ready to accept connections However, when I try to load my data fixtures to Docker Postre image with migrate & loaddata commands, the following error occurs: psycopg2.OperationalError: could not translate host name "db" to address: Unknown host I am able to connect my local PostgreSQL where I previously hosted the app, but Django won't see Docker container for some reason. My system: Python 3.9.0, Django 3.2.8, psycopg2-binary 2.9.2 Any help?? -
Paginate detailview django
i need to paginate my category_detail page,but this view doesnt have list_objects.I have class for DetailView,where i need to add Paginator.Or maybe i can do it only in html template,and thats all? class Category(models.Model): name = models.CharField(_('Name'), max_length=200) slug = models.SlugField(_('Slug'), unique=True) PARAMS = Choices( ('following', 'following'), ('price_to', 'price_to'), ('price_from', 'price_from'), ) def count_of_products(self): return self.pk.count() def __str__(self): return self.slug def get_absolute_url(self, **kwargs): return reverse('products:category_detail', kwargs={'category_slug': self.slug}) this is my views.py class CategoryListView(ActiveTabMixin, ListView): model = Category active_tab = 'category_list' template_name = 'products/category_list.html' def get_ordered_grade_info(self): return [] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['grade_info'] = self.get_ordered_grade_info() return context class CategoryDetailView(DetailView): model = Category slug_url_kwarg = 'category_slug' PARAM_FOLLOWING = 'following' PARAM_PRICE_FROM = 'price_from' PARAM_PRICE_TO = 'price_to' slug_field = 'slug' In my opinion,i need to do paginate def in CategoryDetailView, isnt it? template {% extends "base.html" %} {% block content %} <h2>{{ category.name }}</h2> <div class="list-group"> {% for product in category.products.all %} <a href="{{ product.get_absolute_url }}" class="list-group-item"> <h4 class="list-group-item-heading">{{ product.name }}</h4> <p class="list-group-item-text">{{ product.price }}$</p> <p class="list-group-item-text">Likes {{ product.likes.count }}</p> <p> <img class='img-article' src="{{product.image.url}}"> </p> </a> {% endfor %} </div> {% endblock content %} -
Returning the table using django
I wrote a function that generates an array of strings and an array of integers in views.py. List=["car", "dog", "cat"] Array = [1,4,7] How can I return these values in a form of table on web page using Django? Is it possible to iterate these arrays in template? -
AWS The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy
I have started a django app on an EC2 instance and I have added my static files(css, js, etc) onto a S3 bucket. After many hours last night I managed to get the static inages to load onto the pages when i viewed the EC2 public address Happy days. But now i keep getting this error: I keep getting this error when i view inspect a web page "The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead" And none of my static images are loading. I can't find anything online related to this exact error message, there are some variants which lead to dead ends. does anyone know what is going on? Whats weird is if i run my django app on my personal pc, then the error does not show when i inspect BUT the static images also do not load. When i run the django app on the ec2 instance, then I get the error message with the static images still not loading. So i dont think the … -
hi, which one is better and why, multiple imports from the same model or declare variables in Django?
I was reading Django documentation and what's new in django v4.* and this made me think what way in more code optimised 1 or 2? thanks ------1------ from django.db import models from django.db.models import UniqueConstraint from django.db.models.functions import Lower ------2------ from django.db import models unique_constraint = models.UniqueConstraint lower = models.functions.Lower -
DRF + Djongo: How to access and work with ID from legacy database?
I set up a Django REST Framework (DRF) in combination with djongo, since I'm having a legacy database in MongoDB/Mongo express. Everything runs through a docker container, but I don't think that this is the issue. My model looks like this: from django.db import models ## Event class Event(models.Model): ID = models.AutoField(primary_key=True) date = models.DateField(default=None) name = models.CharField(default=None, max_length=500) locality = models.CharField(default=None, max_length=500) class Meta: ordering = ['ID'] db_table = 'event' Next, my serializer is as follows: from rest_framework import serializers from .models import Event class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields= "__all__" And the view looks like this: from rest_framework import generics, status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import * from .models import * ## Events @api_view(['GET', 'POST']) def event_list(request): if request.method == 'GET': events = Event.objects.all().order_by('ID') event_serializer = EventSerializer(events, many=True) return Response(event_serializer.data) elif request.method == 'POST': event_serializer = EventSerializer(data=request.data) if event_serializer.is_valid(): event_serializer.save() return Response(event_serializer.data, status=status.HTTP_201_CREATED) return Response(event_serializer.errors, status=status.HTTP_400_BAD_REQUEST) As soon as I'm trying to post with import requests endpoint = "http://localhost:8080/event/" get_response = requests.post(endpoint, {"date":"2022-06-01", "name":"Max Musterfrau", "locality":"North America"} ) I'm getting back the error message TypeError: int() argument must be a string, a bytes-like object or a real number, not 'ObjectId' … -
IndexError at /detectWithWebcam list index out of range
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/detectWithWebcam Django Version: 2.2 Python Version: 3.9.7 Installed Applications: ['main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters'] Installed 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'] Traceback: File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\FacialRecognitionForPolice-master\main\views.py" in detectWithWebcam 303.encodings[i]=face_recognition.face_encodings(images[i])[0] Exception Type: IndexError at /detectWithWebcam Exception Value: list index out of range -
How to use JWT token in the case of Social authentication. (Django)
Normally JWT flow is when enter Username and password it return a JWT token. using the token we can authenticate APIs. But when we use social authentication how it will happen..? When we use social authentication, for example google, we clicks on login with google >> it give access >> redirect with authorisation code >> it gives open id details like email, first name, last name. If any one have any idea please share. Im using python django. -
duplicate entries is too slow
We have a database with 100.000 artists. But some artists are duplicates. We wan't to run the script below to compare every artist with every artists and make a list with possible duplicates. But this leads to 10 billion comparisons. Any ideas how to make this smarter / faster. artistquery = Artist.objects.filter(mainartist__rank__pos__lt=999, created_at__gt=latestcheckdate).order_by('name').distinct() from difflib import SequenceMatcher for artist in artistquery: checkedartistlist.append(artist.id) ref_artistquery = Artist.objects.all().exclude(id__in=checkedartistlist) for ref_artist in ref_artistquery: similarity = SequenceMatcher(None, artist.name, ref_artist.name).ratio() if similarity > 0.90: SimilarArtist.objects.get_or_create(artist1=artist, artist2=ref_artist) -
django.db.utils.ProgrammingError: cannot cast type integer to date
Hello guys i have some problem with PostgreSQL when i deploy from docker. Error: django.db.utils.ProgrammingError: cannot cast type integer to date [2022-06-01 09:06:04] LINE 1: ...a_playlist" ALTER COLUMN "year" TYPE date USING "year"::date It's my migration file : class Migration(migrations.Migration): dependencies = [ ('multimedia', '0004_track_track'), ] operations = [ migrations.AlterField( model_name='playlist', name='year', field=models.DateField(blank=True, null=True), ), migrations.AlterField( model_name='track', name='year', field=models.DateField(blank=True, null=True), ), ] How can i fix that problem ? Thank you! -
How can i get submit data to my django views from my html and javascript
I recently added a tag-input feature to my form using Javascript but I am unable to get the data from the tag-input I get an integrityError when I submit the form because I can't seem to get the tag-input data. I have also tried an ajax submit function but it also wasn't working I am trying to get the values as JSON so that I can print a list of features later on. views.py garage = request.POST['garage'] telephone = request.POST.get('telephone', False) features = request.GET.get('features') html <label>Property Features: </label> <div class="tag-wrapper"> <div class="tag-content"> <p>Press enter or add a comma after each tag</p> <ul name="features-ul"><input type="text" spellcheck="false" name="features"> </ul> </div> <div class="tag-details"> <p><span>16</span> tags are remaining</p> <button>Clear All Tags</button> </div> </div> </div> javascript const ul = document.querySelector("ul[name=features-ul]"), input = document.querySelector("input[name=features]"), tagNumb = document.querySelector(".tag-details span"); let maxTags = 16, tags = ["coding"]; var features = {"input[name=features]" : tags} countTags(); createTag(); function countTags(){ input.focus(); tagNumb.innerText = maxTags - tags.length; } function createTag(){ ul.querySelectorAll("li").forEach(li => li.remove()); tags.slice().reverse().forEach(tag =>{ let liTag = `<li>${tag} <i class="uit uit-multiply" onclick="remove(this, '${tag}')"></i></li>`; ul.insertAdjacentHTML("afterbegin", liTag); }); countTags(); } function remove(element, tag){ let index = tags.indexOf(tag); tags = [...tags.slice(0, index), ...tags.slice(index + 1)]; element.parentElement.remove(); countTags(); } function addTag(e){ if(e.key == "Enter"){ let … -
Django filter case insensitive
I wrote this Django viewset that allows users to filter and query data from django_filters import rest_framework as filters from rest_framework import viewsets from API.models import Record from API.serializers import RecordSerializer class CountViewSet(viewsets.ReadOnlyModelViewSet): """List of all traffic count Counts""" queryset = Record.objects.all().select_related("count") serializer_class = RecordSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ( "road", "date", "count_method", "count_method__basic_count_method", "count_method__detailed_count_method", "location", "road__direction", "road__category", "road__junc_start", "road__junc_end", "road__road__name", "date__year", "location__count_point_ref", "road__category__name", "road__junc_start__name", "road__junc_end__name", "road__direction__name", ) And I would like to make it case insensitive and allow searches that contain partially a string so that user can query without knowing the correct “road name” for example: curl -X GET /count/?road__category__name=TA" -H "accept: application/json -
Can't pass parameters in Django, giving MultiValueDictKeyError
I have gone through answers of this type of question but they don't seem relevant for my problem. I have a class defined as follows: class TrainModel(APIView): permission_classes = (IsAuthenticated,) def post(self, request, *args): print("I am here") params = json.loads(request.POST["params"]) print(params) #setup_instance.apply_async((params,), queue="local") fit_model(params, "") model_name = "{}-{}-{}-{}".format( params["match_slug"], params["match_id"], params["model_type"], params["version"]) response = { "success": True, "message": "Model is being trained please wait", "data": {"model_name": model_name} } return JsonResponse(response) It also requires other inputs: params["meta"]["xgb"] params["combined"] And I pass them as follows: import requests import json headers = {'Authorization': 'Token $TOKEN', 'content-type': 'application/json'} url = 'http://somesite.com/train/' params = { "match_id": 14142, "model_type": "xgb", "version": "v2", "match_slug": "csk-vs-kkr-26-mar-2022", "meta": { "xgb": { "alpha": 15, "max_depth": 4, "objective": "reg:linear", "n_estimators": 53, "random_state": 0, "learning_rate": 0.1, "colsample_bytree": 0.4 }, "catboost": { "cat_cols": [ "batting order_lag_1", "venue", "against", "role", "bowlType" ], "eval_metric": "RMSE", "random_seed": 42, "logging_level": "Silent", "loss_function": "RMSE" } }, "image_id": "SOME_ID", "combined": 0 } resp = requests.post(url, params=params, headers=headers) print(resp) I try the same in Postman by putting all these parameters in "Body" (using "raw") but get: Exception Type: MultiValueDictKeyError Exception Value: 'params' Need help. Thanks. -
Django: Sending passwordreset mail using Django-mailjet Package
Please Someone should kindly provide a link to a github repo which has the implementation of Django-Mailjet for sending mails from the app such as passwordreset, mails for new users etc I have gone through the documentation of the django-mailjet package but it's not sufficient for me. Thank you -
Signin with google using django-allauth without using django-admin pannel
here i am using python 3.7 and Django 3.0 where i want to sign in with google to my website and don't want to use the default django admin app. I've acquired the required Google client id and secret, now I'm not able to understand how to configure the django-allauth here is my settings.py file SITE_ID = 1 INSTALLED_APPS = [ ... ... 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] LOGIN_URL = reverse_lazy('core_login') LOGOUT_URL = reverse_lazy('core_logout') LOGIN_REDIRECT_URL = reverse_lazy('login_success') LOGIN_ERROR_URL = reverse_lazy('core_login_error') SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, "APP": { 'client_id': 'xxxxx', 'secret_key': '*****', } } } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', 'subscription.authentication.SubscriptionBackend', ) Here i am able to select my email later i am getting this issue Here is the reference image what i am getting error image Please help me so that how can login into my website without using admin panel -
What should i do to stick the footer to be always at the bottom of the page?
I followed this tutorial to create a footer. And i created a footer like this(without any content in body): body{ min-height: 100vh; display: flex; flex-direction: column; } footer{ margin-top: auto; background-color: greenyellow; } .card { max-width: 400px; margin: 0auto; text-align: center; font-family: arial; border-style: solid; border-width: 6px; position: relative; top: 611px; margin-bottom: 33px; margin-right: 33px; float: left; } .card img{ height: 400px; width: 400px; vertical-align: middle; } .price {background-color: #f44336; font-size:22px; border-radius: 3px; position: absolute; bottom: 0px; right: 0px; padding: 3px; } .card button { border: none; color: white; background-color: #000; position: relative ; cursor: pointer; width: 100%; height: 100px; font-size: 44px; align-items: center; } .card button:hover { opacity: .5; background-color: #330; } #id{ background-color: palevioletred; color: white; margin: 0; font-size: 17px; } .number{ width: 50px; height: 50px; background-color: #330; color: yellow; border-radius: 50%; position: absolute; top: -22px; right: -22px; justify-content: center; align-items: center; display: flex; font-size: 22px; } @media (max-width: 1864px){ .card{ max-width: 300px; } .price{ font-size:20px; } .card img{ height: 300px; width: 300px; } {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> <h1>header</h1> </head> <body style="background-color: #36454F;"> <footer class="footer"> <h3 >hello</h3> </foote> </body> </html> i added some contents to the body of … -
Updating chart.js with ajax ,conditionnal error
i'm trying to auto-update my chart js graph trough ajax , but my if statement always return the wrong awnser on the first iter , any idea why ? thank again. , tell me if you need anything more. var datanp = JSON.parse("{{data|escapejs}}"); var label = JSON.parse("{{label|escapejs}}"); console.log('checkin',datanp) console.log('follow up',label) const data = { labels: label, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(0, 99, 132)', borderColor: 'rgb(0, 99, 132)', data: datanp, }] }; const config = { type: 'line', data: data, options: {} }; const myChart = new Chart( document.getElementById('myChart'), config ); setInterval(addData, 10000); //setting the loop with time interval function addData() { $.ajax({ method: 'get', url: "/hello-world/", success: function(response) { let labels = String(response.labels); let datas = response.datas; console.log('check', String(label.slice(-1))); console.log('in', labels); myChart.data.labels.slice(-2)[1]); if (labels == String(label.slice(-1))) { console.log('same content'); } else { console.log('updating content', labels, 'to', String(label.slice(-1))); myChart.data.datasets[0].data.push(datas); myChart.data.labels.push(labels); myChart.update(); }; myChart.update(); } } }); } the values returned by all the variable are correct , everything is running except the if who is always wrong on the first iter . It give the correct awnser afterward but the first issue create a duplicate of the last value . def hello_world_view(request): _,data=connect_influx(listed={"mesure": ["U", [0, 10], "mesure"]},database='test') labels=dumps(data.timestamp.astype(str).values.tolist()[-1]) … -
SwiperJs slides not showing on Django template
So,I am trying to show images in slider in my small blog. In my index page I am looping through all my blogs. And If I have images, I am looping through images in Swiper js slider. I think I have done everything appropriately. But no image or slider is showing in the screen. No error in the console. Here is my models class Blog(models.Model): title = models.CharField(max_length=200, null=True, blank=True) body = models.TextField(null=True, blank=True) created = models.DateTimeField() class ImageUrl(models.Model): blog = models.ForeignKey(Blog, related_name="image_urls", on_delete=models.CASCADE) url = models.URLField(max_length=1000) Here is my template {% for blog in page_obj %} <div class="mx-3 block content"> {% if not blog.image_urls.count == 0 %} <div class="swiper mySwiper{{blog.id}}"> <div class="swiper-wrapper"> {% for image in blog.image_urls.all %} <div class="swiper-slide"> <div class="swiper-zoom-container"> <img data-src="{{image.url}}" class="swiper-lazy" /> </div> <div class="swiper-lazy-preloader"></div> </div> {% endfor %} </div> <div class="swiper-pagination"></div> </div> {% endif %} </div> {% endfor %} Css .swiper { width: 100%; height: 100%; } .swiper-slide { text-align: center; font-size: 18px; background: #000; } .swiper-slide img { width: auto; height: auto; max-width: 100%; max-height: 100%; -ms-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); transform: translate(-50%, -50%); position: absolute; left: 50%; top: 50%; } <script> {% for blog in page_obj %} {% … -
Django Choice Queries with annotate
I am stucked in django annotate query. here is certain Model I have been working. class Claim(model.Model) CLAIMS_STATUS_CHOICES = ( (2, PROCESSING), (1, ACCEPTED), (0, REJECTED) ) status = models.CharField(max_length=10,choice=CLAIMS_STATUS_CHOICES) problem is I don't want to annotate processing choice but I just want to get individual status count of accepted and rejected. Here is what I tried. claim = Claim.objects.filter(Q(status=1) | Q(status=0)) total_status_count = claim.count() status_counts = Claim.objects.filter(Q(status=1) |Q(status=0)).annotate(count=Count('status')).values('count', 'status') but I am getting multiple rejected and accepted queries this is what I got as op [ { "total_claims": 3, "status_count": [ { "status": "1", "count": 1 }, { "status": "0", "count": 1 }, { "status": "1", "count": 1 } ] } ] what I wanted [ { "total_claims": 3, "status_count": [ { "status": "1", "count": 2 }, { "status": "0", "count": 1 } ] } ] Any help regarding this? -
Session data is not getting updated - decoding the session key
Need help with a Django related doubt. I've been trying to develop an ecommerce webapp using Django. When I try to get the session data after clicking on 'Add to Basket' it shows the response from the 'init' method and not the 'add' method. This is the button: <button type="button" id="add-button" value="{{product.id}}" class="btn btn-secondary btn-sm">Add to Basket</button> Ajax Script: <script> $(document).on('click', '#add-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_add" %}', data: { productid: $('#add-button').val(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) </script> View.py file: from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.http import JsonResponse from store.models import Product from .basket import Basket def basket_summary(request): return render(request, 'store/basket/summary.html') def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product = get_object_or_404(Product, id=product_id) basket.add(product=product) response = JsonResponse({'test':'data'}) return response urls.py file: from django.urls import path from . import views app_name = 'basket' urlpatterns = [ path('', views.basket_summary, name='basket_summary'), path('add/', views.basket_add, name='basket_add'), ] Basket Class: class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('skey') if 'skey' not in request.session: basket = self.session['skey'] = {} self.basket = basket def add(self, product): product_id = … -
Django - No video supported format and MIME type found
When I run python manage.py runserver the videos on a webpage work. I deployed the web with apache2 and instead of the videos I see No video with supported format and MIME type found. Did I omit something when deploying the web? When I deployed it the first time it worked, but now it is not working. Here is my /etc/apache2/sites-available/001-default.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerName video.xyz.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files … -
Getting ValueError: Field 'id' expected a number but got 'favicon.ico'
I am follwing this YT tutorial https://www.youtube.com/watch?v=A_j5TAhY3sw, on 4:23:18,when he enters all the details he is able to submit ,but I get the following error: ValueError: Field 'id' expected a number but got 'favicon.ico'. (On my VScode console) Request Method: POST (On my Browser) Request URL: Django Version: 4.0.4 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: postions_postion.invoice_id Exception Location: D:\Python\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Its working fine using the Django admin. This is the views.py file class AddPostionsFormView(FormView): form_class = PositionForm template_name = 'invoices/detail.html' def get_success_url(self): return self.request.path This is the model.py for positions: from django.db import models from invoices.models import Invoice # Create your models here. class Postion(models.Model):#models.Models to inherit from django.db.models.Model invoice = models.ForeignKey(Invoice,on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True,help_text="optional info") amount=models.FloatField(help_text="in US $") created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Invoice : {self.invoice.number},postion title={self.title}" This is the sqlite ddb: id title description amount created invoice_id 1 cleaning the kitchen 30 2022-05-25 07:56:38.750572 1 2 Tarnslating test clip 100 2022-05-28 05:26:46.370414 1 3 Test Test des 300 2022-06-01 06:53:08.567545 10 4 Good test des 222 2022-06-01 07:08:36.972521 10 This is the mega link for uptill where I have completed the course: https://mega.nz/folder/EUoVhQbT#iN16PXAOcMv9Qr55MlUSIA -
Django Table.render_foo methods with Boundcolumn
I'm confused, please tell me how to put the value of another Term_Implementation field in Table.render_foo methods? It follows from the documentation that I have to use Boundcolumn for this, but I couldn't find a concrete example to implement this. Table.render_foo methods BoundColumns class EvensList(IncidentsTable, tables.Table): class Meta: model = AkpEvents sequence = ('Term_Implementation', 'Status') Term_Implementation = tables.DateColumn(empty_values=(),) Status = tables.Column(empty_values=(),) def render_Status(self, value, column, columns): if value == 'Выполнено': column.attrs = {'td': {'class': 'table-success'}} elif value == 'В работе': column.attrs = {'td': {'class': 'table-warning'}} elif columns['Term_Implementation'] <= date.today(): column.attrs = {'td': {'class': 'table-danger'}} else: column.attrs = {'td': {'class': ''}} return value