Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago live viewers counter in rtmp
I have a few livestreaming pages on my site. And i want to count users who are watching my stream at this moment. Like on twitch. How to implement it? -
Handling pages in a vue + django webpack application
I added Vue to my Django project, but since i didn't want to decouple frontend from backend, i decided to load webpack directly from Django. My setup seems to work with django webpack loader, but i'm having some doubts on how i structured the project. Here is my folder: my_site - django settings my_app - views, urls, models, templates vue_frontend - webpack and vue stuff My doubt is: should routing be handled by Django or should it be handled by Vue in a SPA? Here is what i have now: django_template2.html {% extends 'header.html' %} {% load render_bundle from webpack_loader %} {% block content %} <body> <div id="app"> <firstVueComponent /> </div> </body> {% render_bundle 'chunk-vendors' %} {% render_bundle 'main' %} {% endblock %} django_template2.html {% extends 'header.html' %} {% load render_bundle from webpack_loader %} {% block content %} <body> <div id="app"> <secondVueComponent /> </div> </body> {% render_bundle 'chunk-vendors' %} {% render_bundle 'main' %} {% endblock %} So Django handles the urls here: from django.urls import path, include from . import views urlpatterns = [ path('first_page/', views.first_page, name='first'), path('second_page/', views.second_page, name='second'), ] So here i'm not using Vue to handle routes, but i load individual Vue components of the same app … -
Is there a way we can pass context through extra_context param without subclassing TemplateView?
Take the following urls.py: path( "credits/", TemplateView.as_view(template_name="static_pages/credits.html", extra_context={"updated": "123"}), name="credits", ), In my template, when I do the following {{ updated }} nothing shows up. Do I really need to subclass the TemplateView and create my context through get_context_data()? Seems like so much work to just pass an eventual datetime object. -
how Video sitemaps and video sitemap alternatives for django
The sitemap framework Django comes with a high-level sitemap-generating framework to create sitemap XML files. Overview A sitemap is an XML file on your website that tells search-engine indexers how frequently your pages change and how “important” certain pages are in relation to other pages on your site. This information helps search engines index your site. The Django sitemap framework automates the creation of this XML file by letting you express this information in Python code. how use Django The sitemap framework for videos don't work from django.urls import path from django.conf.urls import url from . import views from django.contrib.sitemaps.views import sitemap from .sitemaps import PostSitemap sitemaps = { 'posts': PostSitemap } app_name = 'blog' urlpatterns = [ path('', views.home, name='homepage'), path('search/', views.post_search, name='post_search'), path('articles/<slug:post>/', views.post_single, name='post_single'), path('videos', views.videos, name='videos'), path('video/<slug:post>/', views.post_single, name='video_single'), # path('category/<category>/', views.CatListView.as_view(), name='category'), url(r'^a/(?P<hierarchy>.+)/$', views.show_category, name='category'), # url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name="detail"), path('bodyOrgans/<bodyOrgans>/', views.bodyOrgans.as_view(), name='bodyOrgans'), path('page/<page>/', views.page.as_view(), name='page'), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='sitemap'), path('custom-sitemap.xml', views.index, { 'sitemaps': sitemaps, 'template_name': 'custom_sitemap.html' }), ] how make output like it <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"> <url> <loc>http://www.example.com/videos/some_video_landing_page.html</loc> <video:video> <video:thumbnail_loc>http://www.example.com/thumbs/123.jpg</video:thumbnail_loc> <video:title>Grilling steaks for summer</video:title> <video:description>Alkis shows you how to get perfectly done steaks every time</video:description> <video:content_loc> http://streamserver.example.com/video123.mp4</video:content_loc> <video:player_loc> http://www.example.com/videoplayer.php?video=123</video:player_loc> <video:duration>600</video:duration> <video:expiration_date>2021-11-05T19:20:30+08:00</video:expiration_date> <video:rating>4.2</video:rating> <video:view_count>12345</video:view_count> <video:publication_date>2007-11-05T19:20:30+08:00</video:publication_date> … -
Make field of submodel unique in django
I want to make the name of a submodel unique but I can't think of a way to do it. Imagine I have the following model architecture: class Animal(models.Model): name = field.CharField(...) class Meta: abstract = False class Panther(Animal): class Meta: ... class Tiger(Animal): class Meta: .... Now, what I want is that within the scope of the subclasses, the name of should be unique. So let's say I have a Tiger called JackTheTiger and a Panther called JackyThePanther, then no other Tiger with this name should allowed to be created and no other Panther with the name JackyThePanther should be allowed to be created. But I want to be able to create a Tiger which is called JackyThePanther and a panther which is also called JackyThePanther. So the uniqueness should only be applied within the scope of the submodel. I tried 2 ways to achieve what I want, both are not optimal: I create a name field for each submodel and make it unique. But then I can't query all animals and serialize the name. It also seems like bad architecture to me I make Animal abstract. But this is no option for me since I need the database … -
"ERROR root: code for hash md5 was not found." when running virtualenv python3
I am trying to run a virtual environment in python using the following line: virtualenv -p python3 .venv However, I am receiving this error. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha1 ERROR:root:code for hash sha224 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha224 ERROR:root:code for hash sha256 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha256 ERROR:root:code for hash sha384 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor … -
Django Count with filter
iam trying to count with filter and it doesn't show any error but there is no count showing I have tried all what I know and search every where didn't find any solution : class UsersAnswersSerializer(serializers.ModelSerializer): Answers = serializers.SerializerMethodField('get_answers') def get_answers(self, obj): queryset = AnswersModel.objects.filter(Question=obj.Answer.Question.id)\ .annotate(answersCount=Count('UsersAnswer', distinct=True)) serializer = Answersserializer(instance=queryset, many=True) return serializer.data class Meta: model = UsersAnswerModel fields = ['Answer', 'APNSDevice' ,'RegistrationID','Answers'] and this is my models : class AnswersModel(models.Model): Question = models.ForeignKey(QuestionsModel, related_name='QuestionAnswer', on_delete=models.CASCADE) Answer = models.CharField(max_length=200) class UsersAnswerModel(models.Model): Answer = models.ForeignKey(AnswersModel, related_name='UsersAnswer', on_delete=models.CASCADE) RegistrationID = models.CharField(max_length=200) APNSDevice = models.CharField(max_length=200,default='no name') class QuestionsModel(models.Model): created = models.DateTimeField(auto_now_add=True) Question = models.CharField(max_length=200) what is get is { "Answer": 12, "APNSDevice": "byname", "RegistrationID": "asdasdasdasdasdasdasdasdsa", "Answers": [ { "id": 10, "Question": 4, "Answer": "Answer 1", "UsersAnswer": [ "gfgdgdfgdf", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4" ] }, { "id": 11, "Question": 4, "Answer": "Answer 2", "UsersAnswer": [ "sfgdfgdf", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4" ] } I need to make "UsersAnswer" show a count of its array -
Reverse for 'view' with keyword arguments '{'user_id': ''}' not found. 1 pattern(s) tried: ['account/(?P<user_id>[0-9]+)/$']
I wanna create a search function for searching in users when I try to run the searching page this error appear I try everything to access the user profile but I couldn't make this my views def video_search(request): form = VideoSearchForm() q = '' results = [] if 'q' in request.GET: form = VideoSearchForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] video = Video.objects.filter(title__contains=q) account = Account.objects.filter(email__icontains=q).filter(username__icontains=q).distinct() results = chain(video, account) my template <div class="col-md-4"> <a class="text-dark" href="{% url 'account:view' user_id=account.0.id %}"> <div class="card mb-4 box-shadow"> <img class="card-img-top" src="" alt=""> <div class="card-body"> <h2 style="font-size:18px;font-weight:bold">{{account.username}}</h2> <p class="card-text"></p> <div class="d-flex justify-content-between align-items-center"> <small class="text-muted"></small> </div> </div> </div> </a> </div> my urls path('<int:user_id>/', account_view, name="view"), -
Django TypeError 'ProductFeaturesValue' object is not iterable
I want to render multiple inline formsets, the first formset is being rendered but the objects of the second and third formsets are not iterable. I don't understand what I'm doing wrong here. Please help me. Here's my Model: class Product(models.Model): product_code = models.CharField(max_length=50, unique=True) product = models.CharField(max_length=100, unique=True) keywords = models.CharField(max_length=50, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) detail = models.TextField(blank=True, null=True) cost_price = models.DecimalField(max_digits=10, decimal_places=2) sale_price = models.DecimalField(max_digits=10, decimal_places=2) quantity_per_unit = models.CharField(max_length=100, blank=True, null=True) discontinue = models.BooleanField(default=False) photo = models.ImageField(upload_to = 'images/product/', default = 'images/product/None/no-img.jpg') categories = models.ManyToManyField('Category', blank=True) brand = models.ForeignKey('Brand', blank=True, null=True, on_delete=models.SET_NULL) slug = AutoSlugField(_('slug'), max_length=50, unique=True, populate_from=('product',)) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) is_deleted = models.BooleanField(default=False) class Meta: default_related_name = 'product' def __str__(self): return self.product def __str__(self): return "%s (%s)" % ( self.product, ", ".join(categories.category for categories in self.categories.all()), ) def image_tag(self): return mark_safe('<img src="{}" height="50"/>').format(self.photo.url) class Image(models.Model): def images_directory_path(instance, filename): return '/'.join(['images/product/', str(instance.product_id.id), str(uuid.uuid4().hex + ".png")]) product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='images') title = models.CharField(max_length=50, blank=True, null=True) image = models.FileField(blank=True, null=True, upload_to=images_directory_path, default = None) def __str__(self): return self.title class ProductFeaturesValue(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='featuresvalues') feature = models.ForeignKey('ProductFeatures', blank=True, … -
Django passing data from one form to another
I might be going about this all wrong but I'm trying to get a filterset passed between forms in Django and not getting anywhere fast. The objective is to filter objects in my model and then be able to send an email to each of the objects owners. The filter is working and presenting a subset of records as expected. How do I pass that subset to another view. This is an extract of what I have so far... urls.py from django.urls import path from . import views from linuxaudit.views import SystemListView, SearchResultsView from linuxaudit.filters import SystemFilter from django_filters.views import FilterView from django.urls import path urlpatterns = [ path('', views.index, name='index'), path('filter/', views.filter, name='filter'), path('contact_form/', views.contact_form, name='contact_form'), ] views.py def filter(request): system_list = Linuxaudit.objects.all().order_by('Hostname') system_filter = SystemFilter(request.GET, queryset=system_list) context = { 'filter': system_filter, 'system_list': system_list, } return render(request,'linuxaudit/filter_list.html', context) def contact_form(request): system_list = request.POST.get('system_list') system_filter = SystemFilter(request.GET, queryset=system_list) for system in system_list: print(system) return render(request, 'linuxaudit/contact_form.html', { 'system_list': system_list }) import django_filters from django_filters import DateRangeFilter, DateFilter, DateTimeFromToRangeFilter from django_filters.widgets import RangeWidget from .models import Linuxaudit from django import forms class SystemFilter(django_filters.FilterSet): Hostname = django_filters.CharFilter(lookup_expr='icontains') IPADDR = django_filters.CharFilter(lookup_expr='istartswith') ContactEmail = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Linuxaudit fields = ['Hostname', 'IPADDR', … -
How to translate API response to charts in Django
Hello im a beginner in Django and i have this project where i need to show charts for Croptocurrencies transactions and i'm struggling with it. this is my views.py : import requests import os import numpy as np import pandas as pd from pandas import Series, DataFrame from pprint import pprint from django.views.generic import TemplateView import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.blockchair.com/bitcoin/stats' 'https://api.blockchair.com/ethereum/stats' 'https://api.blockchair.com/litecoin/stats' ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() json_data2 = result[1].json() json_data3 = result[2].json() context = { "bitcoin": json_data1, "ethereum": : json_data2, "litecoin": : json_data3, } return render(request, "index.html", context) and to show the transactions on the html i just have to call: (example for bitcoin) {{ bitcoin.data.transactions }} Can you help me please on how to transalate these values to graphs/charts ? or at leasat give me the keywords to search to avoid waisting time, Thanks! -
Why practically the same path written in different forms doesn't works correct?
I am working in one django project. I am trying to show image that is saved in Django models attribute (ImageFielf), and it's path is: ../projectname/appname/static/img/imgname.png Considering that,I write in HTML code that: class="result-item-preview fadeIn animated " style="background-image:url('../../projectname/appname/static/img/1202296.jpg'), url('../static/img/default-movie.png'); But this doesen't works. It only works if it is written in usually form: class="result-item-preview fadeIn animated " style="background-image:url('../static/img/1202296.jpg'), url('../static/img/default-movie.png'); How to solve this problem ? -
Running PlayWright for python running on google cloud app engine
Hello PlayWright has the setup command playwright install that needs to be run before it can be used. How could I setup a install script on GCP,s app engine to run this command before running my Django app? -
django (no such column: id) using AbstractUser
So I am trying to migrate, and view the admin page. both makemigrations and migrate passed, yet when i go to the admin url it reads this error "django.db.utils.OperationalError: no such column: social_app_user.id" And once i create an id field, it changes to "django.db.utils.OperationalError: no such column: social_app_user.password" I was under the impression that the AbstractUser model included all the default user fields, not sure about the primary key, but regardless. Please help, thanks! Note: the 'id' field in this models.py file was added after i got the error. from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class User(AbstractUser): is_verified = models.BooleanField(default=True) id= models.AutoField(primary_key=True, null=False) REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): f"{self.username} {self.email}" return class main_feed(models.Model): content= models.CharField(unique=True, max_length=255, default='', null=False) poster = models.ForeignKey('User', related_name='author', on_delete=models.CASCADE, to_field='username') likes = models.IntegerField(default=0, null=False) favorites = models.IntegerField(default=0, null=False) date_posted = models.DateTimeField(auto_now=True) def __str__(self): f"{self.content} {self.likes} {self.poster} {self.date_posted}" return -
sqlite3.IntegrityError: FOREIGN KEY constraint failed
I have an sqlite database in my flask server with three tables as seen below: from database import db class ChordNode(db.Model): __tablename__ = 'chordnode' id = db.Column(db.Integer, primary_key=True) hashed_id = db.Column(db.String) successor = db.Column(db.String) predecessor = db.Column(db.String) is_bootstrap = db.Column(db.Boolean, default=False) storage = db.relationship("KeyValuePair") node_map = db.relationship("NodeRecord", cascade="delete") def __repr__(self): return 'Chord node {}, with successor: {}, predecessor: {}, ' \ 'bootstrap: {}'.format(self.hashed_id, self.successor, self.predecessor, self.is_bootstrap) class KeyValuePair(db.Model): __tablename__ = 'keyvaluepair' id = db.Column(db.Integer, primary_key=True) chordnode_id = db.Column(db.String, db.ForeignKey('chordnode.hashed_id'), nullable=True) hashed_id = db.Column(db.String) value = db.Column(db.String) def __repr__(self): return '<key-value pair: {}:{}, responsible Chord node: {}'.format(self.hashed_id, self.value, self.chordnode_id) class NodeRecord(db.Model): __tablename__ = 'noderecord' id = db.Column(db.Integer, primary_key=True) bootstrap_id = db.Column(db.Integer, db.ForeignKey('chordnode.id'), nullable=False) ip_port = db.Column(db.String) def __repr__(self): return 'Node record {} on boo tstrap node with id {}'.format(self.ip_port, self.bootstrap_id) When i insert into ChordNode class or Noderecord everything works fine but inserting a record into KeyValuePair produces this error: sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) FOREIGN KEY constraint failed However KeyValuePair's foreign key is exactly the same as ChordNode's corresponding. Any ideas about what else could be wrong with this and why this error occurs? -
Authentication credentials were not provided on login with username and password
I have a such misunderstanding with my django I make a login from DJANGO built in view for testing, lofin is successful But from postman or any other place i get an ERROR Authentication credentials were not provided CAN ANYBODY PLEASE EXPLAIN WHAT IS WRONG!!! If i did not provide full explanation, please inform me, and i will add This is settings.py DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "tsundoku", 'rest_framework', 'rest_framework.authtoken', 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', "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", ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] ROOT_URLCONF = "backend.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 = "backend.wsgi.application" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators 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", }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ … -
Product Images - 'cannot write mode RGBA as JPEG'
I'm trying to get started with Django Oscar and I can't get my images to load properly. Once I upload an image, I get this error - 'cannot write mode RGBA as JPEG'. The error comes from line 11: 6 {% block product %} 7 <article class="product_pod"> 8 {% block product_image %} 9 <div class="image_container"> 10 {% with image=product.primary_image %} 11 {% oscar_thumbnail image.original "x155" upscale=False as thumb %} <!-- this line throwing error --> 12 <a href="{{ product.get_absolute_url }}"> 13 <img src="{{ thumb.url }}" alt="{{ product.get_title }}" class="thumbnail"> 14 </a> 15 {% endwith %} 16 </div> 17 {% endblock %} Would this be because I don't have libjpeg properly installed? I'm running this on Windows and it's still not clear to me if I have installed libjpeg correctly. What exactly to I need to do with that package after downloading if that is my issue? Let me know if I can provide more information that would be helpful. -
pandas dataframe to django database
I need to create an SQL table from a pandas dataframe inside django. this is the code I'm using: from django.db import connection import pandas as pd # .... pf = pd.DataFrame({'name': ['Mike', 'Chris', 'Alex']}) pf.to_sql(name='customers', con=dj, if_exists='replace') But all I'm getting is this error: Traceback (most recent call last): File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1681, in execute cur.execute(*args, **kwargs) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\contextlib.py", line 88, in __exit__ next(self.gen) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\django\db\backends\utils.py", line 113, in debug_sql sql = self.db.ops.last_executed_query(self.cursor, sql, params) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\django\db\backends\sqlite3\operations.py", line 160, in last_executed_query return sql % params TypeError: not all arguments converted during string formatting The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "F:\Programming\Python\Django\sandbox\django_sandbox\polls\models.py", line 32, in go_big pf.to_sql(name='go_big', con=dj, if_exists='replace') File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\core\generic.py", line 2615, in to_sql method=method, File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 598, in to_sql method=method, File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1827, in to_sql table.create() File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 721, in create if self.exists(): File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 708, in exists return self.pd_sql.has_table(self.name, self.schema) File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1838, in has_table return len(self.execute(query, [name]).fetchall()) > 0 File "F:\Programming\Python\Django\sandbox\.venv\lib\site-packages\pandas\io\sql.py", line 1693, in execute raise ex from exc pandas.io.sql.DatabaseError: Execution failed … -
Django Model structure to fetch data from a foreign key table using a key from another table
I am new to Django and I could not find a correct answer to fetch my progress. I think it is because my model is wrong and so I am searching wrong thing. I am trying to find all the Progress status for a particular Item. My workaround is that in views.py parse through all the objects in the Progress object and if the item_id matches with the id then add it to the list and send the list to the template. But my progress list is huge like 10000 and scaling and each item has only 4 o 5 progress. so I don't know if its a good idea to parse through all the list of progress each time an item URL is clicked Models.py class Item(models.Model): name = models.CharField(max_length=256) id =models.AutoField(primary_key=True) def __str__(self): return self.name class Progress(models.Model): text=models.CharField(max_length=256) id=models.AutoField(primary_key=True) item_id=models.ForeignKey(Item,on_delete=models.CASCADE) start_date = models.DateField(default=django.utils.timezone.now) def __str__(self): return self.name and views Views.py def item(request,item): pp = Progress.objects.all() ip=get_object_or_404(Item,id=item) print(item) show=[] for each in pp: if each.item.id ==int(item): print(each.item.id) show.append(each) return render(request,'main/item.html',{'show':show,'ip':ip}) Example of Desired Output: localhost/main/item/3 Item: Launch A progress: |- Initiated |- fetched all the metadata |- informed stakeholders |- waiting for approval localhost/main/item/9 Item: Automate Bots progress: |-Bot … -
How can I count the fields of All Objects in a Database Table by date in Django?
How can I count the fields of All Objects in a Database Table by date in Django? For example: I can access the number of all records of my model named "MateryalEkle" with this code below {{materyalIstatistik}}. But I want to reach the count of all fields separately. And I want to do them by date range i.e. weekly, monthly and yearly. for example: how many "TELEFON", how many "SIM KART", how many "SD KART". and I want to filter these count by date range. for example : 01.03.2021 - 07.03.2021 or 01.01.2021 -.01.01.2022 How can I do that? Thanks for your help. models.py class MateryalEkle(models.Model): MATERYALCINSI = [ ('TELEFON', 'TELEFON'), ('SIM KART', 'SIM KART'), ('SD KART', 'SD KART'), ('USB BELLEK', 'USB BELLEK'), ] materyalMarka = models.CharField(max_length=50, verbose_name='MATERYAL MARKA', blank=True, null=True, default="-") cinsi = models.CharField(max_length=50, choices=MATERYALCINSI, verbose_name='MATERYAL CİNSİ', blank=True, null=True, default="-") gelisTarihi = models.DateTimeField(auto_now_add=True) slug = AutoSlugField(populate_from='materyalMarka', unique=True, blank=True, null=True) def __str__(self): return self.materyalMarka views.py def istatistik(request): materyalIstatistik = MateryalEkle.objects.all().count() return render(request, 'delil/istatistikler.html', {'materyalIstatistik':materyalIstatistik}) istatistikler.html `<p>materyal : {{materyalIstatistik}} </p>` -
How can I return dynamic response in my django application?
I have a dynamic Django web application. Which takes CSV files as input, basically a list of URLs. Then with the help of beautiful soup, it returns me a processed CSV file. My code and localhost Django do this job perfectly, but it sometimes takes a huge amount of time to process the data. So when I use it on Heroku or somewhere else, I get request timeouts. But on my localhost, it is not the issue. I guess I have to do something with ajax or return dynamic values to the HTML template so that my request never gets timeout? I want to show the status of processed files where after each iteration of processed files, the value is returned to the browser so that I can know how many items have been processed so far. -
No such file or directory Django in production
Django test went fine in the test environment. When I went for production and typed in my ip address in the browser I get the following error snippet from the browser. FileNotFoundError at / [Errno 2] No such file or directory: 'mainAboutUs.txt' Request Method: GET Request URL: http://139.162.136.239/ Django Version: 3.1.7 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'mainAboutUs.txt' Exception Location: /home/jianwu/HD_website/website/index/views.py, line 50, in importTextFile Python Executable: /home/jianwu/HD_website/env/bin/python Python Version: 3.8.5 Python Path: ['/home/jianwu/HD_website/website', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/jianwu/HD_website/env/lib/python3.8/site-packages'] Server time: Thu, 11 Mar 2021 19:24:51 +0000 I have verified that the mainAboutUs.txt is located in my project folder. The views.py is located in index folder. I am serving my website using apache2. (env) jianwu@django-server:~/HD_website/website$ ll total 188 drwxrwxr-x 7 jianwu www-data 4096 Mar 7 15:48 ./ drwxrwxr-x 6 jianwu jianwu 4096 Mar 7 15:44 ../ -rw-rw-r-- 1 jianwu jianwu 1968 Mar 7 15:24 'aboutUs2900 2.txt' -rw-rw-r-- 1 jianwu jianwu 1968 Mar 7 12:54 aboutUs2900.txt -rw-rw-r-- 1 jianwu jianwu 3008 Mar 7 12:54 aboutUsNytorv.txt -rw-rw-r-- 1 jianwu www-data 131072 Mar 7 12:54 db.sqlite3 -rw-r--r-- 1 jianwu jianwu 168 Mar 7 15:48 emailCred.txt drwxrwxr-x 4 jianwu jianwu 4096 Mar 11 18:42 index/ -rwxrwxr-x 1 jianwu www-data … -
Integrity error in django for null condition
I am new to django and trying to run simple application, currently I am getting data from 3rd party api and I try save that json into my db so below is my Model class. class CollisionDetails(models.Model): crossStreetName = models.CharField(max_length=30) onStreetName = models.CharField(max_length=40, default='') offStreetName = models.CharField(max_length=40, default='') numberOfPersonsInjured = models.IntegerField(default=0) def json_to_class(self, json_data, city): collision_detail = json_data #json.loads(json_data) self.crossStreetName = collision_detail.get('cross_street_name') self.onStreetName = collision_detail.get('on_street_name', 'Unspecified') self.offStreetName = collision_detail.get('off_street_name', 'Unspecified') but when I am trying to save my object it is giving me integrity error saying django.db.utils.IntegrityError: (1048, "Column 'crossStreetName' cannot be null") but I checked my db as well there is no not null condition I have kept, I am not sure why django is treating that as not null = True, is it default behavior? -
How to get RetrieveAPIView path variables in django?
I am writing django application with rest framework for the first time and I've got a problem while getting path variable value of uuid. I need to get User by id, but I suppose my url is avaliable litteraly like this users/<user_id>/ So, I wrote next code: views.py class UserRetrieverView(RetrieveAPIView): permission_classes = (AllowAny,) lookup_field = 'user_id' lookup_url_kwarg = 'user_id' # Retrieving user by id def get(self, request, **kwargs): try: user = User.objects.filter(user_id=self.kwargs.get(self.lookup_url_kwarg)).first() And connected it in urls.py like this url('users/<user_id>', UserRetrieverView.as_view()) And the thing is that when I try to get user by url kinda like this /users/d540c1f8c86f4c5ba755459c366aa97c Server gives 404 NOT FOUND error message GET /api/users/d540c1f8c86f4c5ba755459c366aa97c HTTP/1.1" 404 2554 But if I try to make my request litteraly like users/<user_id>/ there is no 404 error, so I think it tries to set available path just like it is set in urls I have searched many times to solve this, but nothing works. I would appreciate if you could help me. -
Redirect User to external site and get response
I‘ve wrote this Python package to make requests to the non-publicly Audible API. To use this package, the user has to authorize himself to Amazon. Now I’m writing a Django App to give the user a new experience when using the API. My problem is to implement the authorization part. Best solution where to redirect the user to a special Amazon login site and set some cookies on client-side which then be send to Amazon. During authorization, the user have to solve a Captcha (when init cookies doesn’t set correctly) and a 2FA prompt! After a successfully authorization the user are redirected by Amazon to a Url, which contains the needed access token. How I can get this Url with Django? Questions over Questions but no answers yet. My intention is not to write multiple views to condition race the result (successfull/Captcha/2FA/...)!