Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto Populated Fields Django
Auto populated forms Hello, My question is about populating field depending on other field. For example, I have form with 2 fields:PersonalNumber, FullName. Also I have Table in my sql database, which contains this two fields,(nealy 5mln rows) . I am wondering how can I achieve, When field(PersonalNumber) will be filled in my form, FullName has auto populated, by finding personalnumber in my database table and getting fullname from there. -
Reordering database after certain time period without harming dependencies in django
I'm wondering if is there any way to reorder whole database after a month or weeks in maintenance such that if my database has 10000+ of records and some in between records are deleted for example: records: 1,2,3,4,5,6,7,8,9 after deleting:1,2,5,8,9 after reordering:1,2,3,4,5 I'm using mysql as backend, and after reordering the dependencies between models must be retained such as ForeignKey, ManyToManyField -
how to order by date django post view
How can I order my posts from latest to oldest? I Use ordering = ['-date_posted'] for class based views. how can I do the exact thing for a function based view? this is my view function: def blog_view(request): posts = Post.objects.all() paginator = Paginator(posts, 3) page = request.GET.get('page') posts = paginator.get_page(page) common_tags = Post.tags.most_common()[:] context = { 'posts':posts, 'common_tags':common_tags, } return render(request, 'posts/blog.html', context) -
How to do render a database queryset in a Django base template?
I wish to display some queryset across all the pages in my website. From all indications, the logical thing to do is to include the tagging in the base.html. Unfortunately, the base.html is not been rendered or called by a url. So I am having tough time doing that. WHAT I HAVE DONE. 1 I made the query in a view that calls reders index.html. Passed the queryset into the context. Extended base.html in my index.html template used template tagging to call the queryset. It worked well in my local. but after deployment to heroku, it stopped displaying on my index. view.py from django.shortcuts import render, get_object_or_404 from .models import CompanyProfile, CompanyServices def index_view(request): company_services = CompanyServices.objects.all() company_profile = CompanyProfile.objects.all() context = { 'profile': company_profile, 'services': company_services, } return render(request, 'webpages/index.html', context=context) base.html snipptet <body> <!-- ======= Top Bar ======= --> <section id="topbar" class="d-none d-lg-block"> <div class="container d-flex"> <div class="contact-info mr-auto"> <i class="icofont-envelope"></i><a href="mailto:contact@example.com">{{profile.company_email}}</a> <i class="icofont-phone"></i> {{profile.company_phone1}} </div> How else can I make this work? -
IMAGE Upload in DRF, Imagefield cannot be serialized when introduce a checksum-gen method
I have an issue when try to upload image in DRF. Everything works fine with the following code. class UploadPhotoViewset( generics.CreateAPIView ): queryset = Photo.objects.all() parser_classes = (JSONParser, MultiPartParser, FormParser, FileUploadParser) serializer_class = PhotoSerializer def post(self, request, *args, **kwargs): print(request.data) img_file = request.data["image"] request.data["size"] = img_file.size request.data["title"] = img_file.name # request.data["checksum"] = self.get_file_md5(img_file) request.data["image"] = img_file print(request.data) return self.create(request, *args, **kwargs) But when I tried to generate the md5 hash for the file. Strange thing happens. class UploadPhotoViewset( generics.CreateAPIView ): queryset = Photo.objects.all() parser_classes = (JSONParser, MultiPartParser, FormParser, FileUploadParser) serializer_class = PhotoSerializer def post(self, request, *args, **kwargs): print(request.data) img_file = request.data["image"] request.data["size"] = img_file.size request.data["title"] = img_file.name # request.data["checksum"] = self.get_file_md5(img_file) request.data["image"] = img_file print(request.data) return self.create(request, *args, **kwargs) def get_file_md5(self, img): hash_md5 = hashlib.md5() for chunk in iter(lambda: img.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() The data cannot be validated. serializer.is_valid(raise_exception=True) will give { "errors": { "image": [ "Upload a valid image. The file you uploaded was either not an image or a corrupted image." ] } } Anyone knows why? -
When I delete all the item's from my query in Django the item id's don't reset
I am a complete beginner and I'm creating my first Django webpage following Tech with Tim's tutorials. I have my first SQLite 3 database entry set up, but I can't seem to figure out why even when I delete every entry from it, when I add a new one it's id is still, for example, 10. Why aren't the id's resetting back to 0 when I delete everything from the query? I'm sorry if this question is badly worded or doesn't give enough information, as I said I'm a complete beginner and I'll try to edit my question however nescessary, thank you! -
Using HackerEarth API to integrate online compiler in Django
Trying to integrate an online compiler into my django project using the HackerEarth API this is the code I get when I run the project on local Access to 127.0.0.1 was denied You don't have authorization to view this page. HTTP ERROR 403 This is my views.py @login_required @student_required #From HackerEarth API def runCode(request): if request.is_ajax(): run_url = "https://api.hackerearth.com/v3/code/run/" source = request.POST['source'] lang = request.POST['lang'] data = { 'client_secret': '***', 'async': 0, 'source': source, 'lang': lang, 'time_limit': 5, 'memory_limit': 262144, } if 'input' in request.POST: data['input'] = request.POST['input'] r = requests.post(run_url, data=data) return JsonResponse(r.json(), safe=False) else: return HttpResponseForbidden() and html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Online Code Compiler</title> <script src="{% static 'fifth/js/jquery.min.js' %}" type="text/javascript" charset="utf-8"></script> <script src="{% static 'fifth/js/bootstrap.min.js' %}" type="text/javascript" charset="utf-8"></script> <script src="{% static 'fifth/js/ace.js' %}" type="text/javascript" charset="utf-8"></script> <script src="{% static 'fifth/js/ext-statusbar.js' %}" type="text/javascript" charset="utf-8"></script> <script src="{% static 'fifth/js/ext-language_tools.js' %}" type="text/javascript" charset="utf-8"></script> <script src="{% static 'fifth/js/customjs.js' %}" type="text/javascript" charset="utf-8"></script> <link rel="stylesheet" type="text/css" href="{% static 'fifth/css/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'fifth/css/custom.css' %}" /> </head> <body> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}" /> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a style="color:#fff;"class="navbar-brand" href="#">HackerEarth</a> </div> <ul class="nav navbar-nav navbar-right"> … -
LookUpError: No installed app with label 'admin' and SyntaxError: {% extends 'base.html' %} in Django 2.0.2
I'm learning Python's Django library and working on product catalog type web page. I've revised all my code dozens of times and still, the root problem points at two error; Either SyntaxError: {% extends 'base.html' %} (this does not come always and I have revised my base.html files and accounts/templates login.html and signup.html files but there should not be syntax error). See Error2 picture to see error code This error comes only like 1-2 times out 10 python manage.py runserver. Mostly the error is LookUpError: No installed app with label 'admin' (see Error1 picture to see error code). PLEASE NOTE! I do have 'django.contrib.admin' in INSTALLED_APPS section of my settings.py file, located in 'producthunt' folder. I'm using Django 2.0.2 in my virtual environment. Tried to google both of these problems but they are not point at the root problem here. I'd appreciate very much if someone could revise my could revise my code behind this link: https://www.dropbox.com/s/lmgz9sii8ws4tkx/producthunt-project.7z?dl=0 Error1 'admin' error Error2 syntax error -
Django-dash DatePickerRange() upper limit is not being set
There seems to be an odd problem with the django-dash app we created for ploting time series data. The dashboard uses a pre-processed dataframe's data which is saved to a file to show the interactive graphs where the user can select a range from the dcc.DatePickerRange() to get the data within the specified field. However, the ending date limit for the first graphs doesn't seem to be clickable as if its part of the background, whereas the starting date works just fine. Is this a Django app problem or a plotly-dash bug? The app is fine since we've tested it separately using plotly-dash app but placing it as a django app using django-dash presents a whole new set of problems including the html.H1 tag not working in the layout section. The code for the django-dash app goes like this: import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output,State import plotly.graph_objs as go from django_plotly_dash import DjangoDash import pandas as pd import dash_table from datetime import datetime app = DjangoDash('chalao') selected_df=pd.read_pickle(r'static/selected_df.pkl') actual_df=pd.read_pickle(r'static/actual_prediction.pkl') datatable_df=actual_df datatable_df.reset_index(inplace=True) datatable_df['START_DATETIME'] = datatable_df['START_DATETIME'].astype(str) datatable_df['Transaction'] = datatable_df['Transaction'].round(decimals=-3) datatable_df['Prediction'] = datatable_df['Prediction'] + 500 datatable_df['Prediction'] = datatable_df['Prediction'].round(decimals=-3) datatable_df['START_DATETIME'] = datatable_df['START_DATETIME'].map(lambda x: x.lstrip('T00:00:00')) app.layout = html.Div([ html.H1('Stock … -
Django template if statement not updating
I have an if statement in a django template that checks if the views.count variable is bigger than 0 to display a button. Once my views.count increases my if statement doesn't update and I do not understand why, since I am updating the variable using javascript. I other section of my template I'm iterating the views and it updates correctly. {% if views.count > 0 %} <a class="btn preview__tour">{% trans 'Preview tour' %}</a> {% endif %} -
Installing Django to Windows 8.1
I have been following this tutorial (https://tutorial.djangogirls.org/en/django_installation/) to learn some python but I have become stuck at the 'Django installation' step. I have managed to create a virtual environment and the .txt file but inputting 'pip install -r requirements.txt' into the command-line I get the error 'could not find version that satisfies requirement'and'no matching distribution found'. This error occurs when I have entered versions 2.2.4 & 3.0.5 of Django into the .txt file. Have also just tried 'pip install django' and have come across the same errors. Have tried in the windows command prompt but i get an error stating pip is not recognized as an internal or external command. Any help is very much appreciated -
Django enable show_close button on admin page
How to enable show_close button on Django admin page? I tried the following but not work. class ModelAdminSite(AdminSite): def each_context(self, request): context = super().each_context(request) print(context) context['show_close'] = True return context -
I can't organize my messages by recent chat in Django
I've been trying to fix my messages in order to show the messages by most recent. I can't figure out where did I go wrong in the code. I am thinking that I can use sent_at to know the last active conversation in an active chat but I don't know where to start. Here are my codes: models.py from django.db import models from django.core.exceptions import ValidationError from django.utils import timezone from django.conf import settings AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') class Message(models.Model): """ A private direct message. """ content = models.TextField('Content') document = models.FileField(upload_to='direct_messages', blank=True, null=True) sender = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_dm', verbose_name='Sender' ) recipient = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_dm', verbose_name='Recipient' ) sent_at = models.DateTimeField('sent at', auto_now_add=True) read_at = models.DateTimeField('read at', null=True, blank=True) class Meta: ordering = ['-sent_at'] @property def unread(self): """ Returns whether the message was read or not. """ if self.read_at is not None: return True def __str__(self): return self.content def save(self, **kwargs): """ Check message sender and recipient and raise error if the are saved. Save message when the condition passes. """ if self.sender == self.recipient: raise ValidationError("You cant't send messages to yourself!") if not self.id: self.sent_at = timezone.now() super(Message, self).save(**kwargs) class ChatRoom(models.Model): """ A private char room … -
Javascript doesn't load in Django template
I want to add some javascript function in python django template but the staticfile I load doesn't load the javasctipt file . The file doesn't have ?v=2.17 but I want them to for jquery version <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox --> <link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/jquery.fancybox.css?v=2.1.7" type="text/css" media="screen" /> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/jquery.fancybox.pack.js"></script> <!-- Optionally add helpers - button, thumbnail and/or media --> <link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" /> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script> <link rel="stylesheet" href="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" /> <script type="text/javascript" src="{{ STATIC_URL }}/static/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script> <script type="text/javascript"> $(document).ready(function() { $(".fancybox").fancybox(); }); </script> This is my settings.py file and url.py file from project : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] CRISPY_TEMPLATE_PACK = 'bootstrap3' -
Returning an video URL as a "Blob Response" in Django?
I've been looking at researching a way of transporting a video as a blob object, for cross browser compatibility for playing videos uploaded ... I believe that blobs are the most reliable way of achieving this. However, I am unsure of the best way to impliment this with Django? Would it be some sort of FileResponse object, or HttpStreamResponse? ...or, as my research is suggesting...this is entirely a client side operation with the Blob() web API? -
from django.utils.encoding import python_2_unicode_compatible
i've been using django for a while without having any issues, I don't really know what I did by mistake, but now, some errors pop up when I try to run my server or to migrate or to type whatever command that comes after python manage.py. I'm using django 3.0.5 (should be the latest version), and python 3.8.2. the error actually comes from some files written by default like init.py, autoreloader.py , runserver.py ... I think it must be a certain confusion between the two versions. Any help please? Picture : https://i.stack.imgur.com/eQq52.png -
Impact migrating between multiple role models to one model IntegerField
In former times I was using three models named User (from AbstractBaseUser), Teacher and Student. A Student could create a Request and a Teacher could ask to be responsible for that Request. If Student accepted, then the Teacher would become the responsible for that Request. This is how the Request table looked like: class Request(models.Model): request_id = models.CharField(db_column='requestId', primary_key=True, max_length=36) date_created = models.DateField(db_column='dateCreated') title = models.CharField(max_length=30) request_description = models.CharField(db_column='requestDescription', max_length=280, blank=True, null=True) expiration_date = models.DateField(db_column='expirationDate', blank=True, null=True) done = models.IntegerField(blank=True, null=True) student_id = models.ForeignKey(Student, models.DO_NOTHING, db_column='studentId') teacher_id = models.ForeignKey(Teacher, models.DO_NOTHING, db_column='teacherId', blank=True, null=True) As you can see, there's student_id and teacher_id with ForeignKey to, respectively, Student and Teacher models. Now, I'm using only one model to represent User, Teacher and Student, called MyUser. In this model, got a field user_type = models.IntegerField(db_column='userType') where 0 is the MyUser with more permissions and 255 is an unspecified MyUser. What happens now to the FKs in Request? Also, how to handle the Teacher and Student through this field? -
Why do tests for Django Websockets have to be written in pytest?
All tutorials and official documents point to using pytest for testing Django's websockets. My question is why Django's unittest framework cannot be used directly and when this might change? -
Replacing M2M field with property
I'd like to replace M2M field with a property decorated funcition. Is it even possible? Like I have something along the lines of: members = models.ManyToManyField('Person', related_name='group') and would like to change that into: @property def members(self): return Person.objects.all() And accordingly add @property group to Person model? I just need to store data about members in couple of different fields but still wants members property to return all of them. Is it even feasible in django? When I tried it i'm getting FieldError: Cannot resolve keyword 'members' into field? -
Django serialization error 'dict' object has no attribute 'mymodelfield' in .values() aggregation
I am trying to do aggregation of a model (Reply) by geographic area (Hexgrid_10km2). Similar to SQL 'group by'. I am using .values(Hexgrid_10km) to do this. I am then annotating some numbers onto this. I am getting the following error in te serialization to geojson: 'dict' object has no attribute 'hexgrid_10km2' But Reply does a have field 'hexgrid_10km2'. Anybody know what is up? Many thanks! I am using djangorestframework-gis Models class Hexgrid_10km2(models.Model): lng = models.FloatField() lat = models.FloatField() polygon = models.MultiPolygonField(srid=4326) centroid = models.PointField(default=Point(0,0), srid=4326) def __str__(self): return f'lng: { self.lng } lat: {self.lat }' class Animal (models.Model): name = models.CharField(max_length=200) class Reply(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) ability = models.IntegerField(default = 0) hexgrid_10km2 = models.ForeignKey(Hexgrid_10km2, on_delete=models.CASCADE, null=True, blank=True) @property def polygon_10km2(self): return self.hexgrid_10km2.polygon Views from rest_framework.views import APIView from rest_framework.response import Response from.models import Animal, Reply, Hexgrid_10km2 from django.db.models import Avg, Sum class ReplyHeatmapAPIView(APIView): def get(self, request, pk): animal = get_object_or_404(Animal, pk=pk) final = Reply.objects.filter(animal=animal).values('hexgrid_10km2').annotate(average_ability=Avg('ability'), sum_ability=Sum('ability')) serializer = ReplyHeatmapSerializer(final, many=True) return Response(serializer.data) Serializer from rest_framework_gis.fields import GeometrySerializerMethodField from rest_framework_gis.serializers import GeoFeatureModelSerializer class ReplyHeatmapSerializer(GeoFeatureModelSerializer): """ A class to serialize hex polygons as GeoJSON compatible data """ average_ability = serializers.FloatField() sum_ability = serializers.FloatField() polygon = GeometrySerializerMethodField() def get_polygon(self, obj): return obj.hexgrid_10km2.polygon class … -
Vuejs into Django Deployment to Production Using Webpack
When I do npm run build it created a bunch of file on dist folder. So I dont know how to integrate this files to django. Iam running 2 server on my development one for backend(django) one for front end (vuejs). So I wanna run only my django server on my production. I watched so online course but they have only few files like only one bundle.js and one bundle.css. For my case there is different. -
What does "or" in function-parameters in python mean?
I just was watching a tutorial and the following pattern appeared: #some code function(Variable1 or Variable2) #more code I'm really wondering what this or means in this case. Could someone explain the purpose of orin function parameters?? Thanks for your help and stay healthy! -
Override Default Meta Setting
Due to the requirement, I would like to adjust all the default setting table name. Even though I alter the core directly in venv.lib.site-packages files then run the command below, Django migrations still cannot detect the changes. python manage.py makemigrations Below is the meta setting and the place I would like to change, I tried to place it in the project's or application's _init.py and it doesn't work from django.db.migrations.recorder import MigrationRecorder from django.contrib.sessions.models import Session from django.contrib.contenttypes.models import ContentType from django.contrib.admin.models import LogEntry from django.contrib.auth.models import Permission from django.contrib.auth.models import Group from django.contrib.auth.models import User from rest_framework.authtoken.models import Token Session._meta.db_table = "extData_django_session" MigrationRecorder.Migration._meta.db_table = "extData_django_migrations" ContentType._meta.db_table = "extData_django_content_type" LogEntry._meta.db_table = "test_django_admin_log" Permission._meta.db_table = "extData_auth_permission" Group._meta.db_table = "extData_auth_group" User._meta.db_table = "extData_auth_user" Token._meta.db_table = "extData_authtoken_token" -
Django Rest Framework , How does Modelserializer validate the user input?
I have a method in ArticleSerializer that check if the length of title property. The title property is associated with the model (Article). How does the validate_title function execute itself when calling ArticleSerializer class ? How does the validate_title function take value from title property ? #necessary module imports from .models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article exclude = ("id",) def validate_title(self, value): """ check that title is at least 30 chars long """ if len(value) < 30: raise serializers.ValidationError("type less") return value I am learning Django rest framwork in Udemy Github link : https://github.com/pymike00/The-Complete-Guide-To-DRF-and-VueJS/blob/master/03-DRF-LEVEL-ONE/newsapi/news/api/serializers.py -
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
when i run git push heroku master it says that my STATIC_ROOT is improperly configured (ERROR:raise ImproperlyConfigured("You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path".). I have set my STATIC_ROOT just as shown in a video tutuorial. settings.py import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '###############################' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get('DEBUG_VALUE') == 'True') ALLOWED_HOSTS = ['http://mypytalk.herokuapp.com/'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages' ] 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', ] ROOT_URLCONF = 'pytalk.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 = 'pytalk.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = …