Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DetailView template not showing the details
I am learning Django web framework from past few days and its pretty awesome. I am learning class based views to display the content. I have created a simple example models school(name,principal,location) and student(name,age,school(foreign key)). The foreign key in the student model has a related_name ='students' which connects with school model. I have registered the models and created the class based views (list and detail views) in views.py file. The views.py file is from django.shortcuts import render from django.views.generic import View, TemplateView, ListView, DetailView from django.http import HttpResponse from . import models # Create your views here. # create a view using the built in template view class IndexView(TemplateView): # template_name is the class object attribute of class TemplateView # Just pass in the html file that need to be displayed template_name = 'index.html' # create a list view class for school inheriting from ListView class SchoolListView(ListView): # the ListView basically takes the model name(in this case School) and converts # it to lower case and adds a _list with it and returns the whole school_list # as a context object to the html # in order to return a generic context object we add the context_object_name # class atrribute … -
How to refer back to index.html in the root directory when i'm currently in a subdirectory
This is an embarassingly noobish question but here goes.... I have a web directory structure as follows: index.html |_____/account/ |_____/random-tweet/ In my random-tweet.html here is my code: <a href="/">Home</a> Clicking on this however tries to bring me to random-tweet/index.html as the url is currently http://localhost:7000/random-tweet/ How to change the link so it brings me back to index.html in root directory?? Thanks in advance! -
Python keep the list in the ram
Whenever my script is executed, I need to select the same data from database and this takes too much. Can I keep this data in the ram, in order to not select the same data in each request. Caching to pickle and reading from it is not an option, because it also takes too much time. -
Django/DRF models, pandas and pickling
There might be a fundamental misunderstanding on my part here, but here's the general idea: I want to add FileUpload fields to a django model, but then access those files/model attributes as pandas dataframes for later processing. Moreover, I'd like it if these attributes can be cached since loading the files into pandas dataframes can be expensive (several seconds). So, should this logic instead live in the DRF ViewSets or some other notion of controllers/middleware? That is fine, but then it's not particularly obvious how I'd go about caching. But either way, I'm not really sure how to proceed here. -
Run business logic on serialized data Django rest framework
I'm building this API to get data from a user, perform some logic on it and return a generated HTML page. # model.py areas = [ ('210', '210'), ('769', '769'), ('300', '300') ] class LocationInfo(models.Model): latitude = models.FloatField(name='GDT 1 Latitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) longitude = models.FloatField(name='GDT 1 Longitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=1) gdt2_lat = models.FloatField(name='GDT 2 Latitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) gdt2_lon = models.FloatField(name='GDT 2 longitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_lat = models.FloatField(name='UAV Latitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_lon = models.FloatField(name='UAV longitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_elevation = models.FloatField(name='UAV Elevation', max_length=100, default=1) area = models.CharField( max_length=8, choices=areas, ) date_added = models.DateTimeField(default=timezone.now) class Meta: get_latest_by = ['date_added'] # serializers.py from .models import LocationInfo from rest_framework import serializers class LocationInfoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = LocationInfo fields = ( 'id', 'GDT 1 Latitude', 'GDT 1 Longitude', 'GDT 2 Latitude', 'GDT 2 longitude', … -
Apache2: No module named site with wsgi py
I have ran into an issue where my error.log says No module named site, I have done extensive research but can't seem to find the solution. When I run sudo a2ensite 000-default I receive: Site 000-default already enabled. My Syntax apachectl configtest seem to be good since I receive: Syntax OK. I have tried to remove libapache2-mod-wsgi and replace it with libapache2-mod-wsgi-py3but when running dpkg -l | grep wsgi I can see this: rc libapache2-mod-wsgi 4.5.17-1 amd64 Python WSGI adapter module for Apache ii libapache2-mod-wsgi-py3 4.5.17-1 amd64 Python 3 WSGI adapter module for Apache Any help would be tremendously apppreciated! Python version inside nenv Python 3.6.9 Python version outside Python 2.7.17 Config under sites-available/000-default.conf WSGIPythonHome /home/djangos WSGIpythonPath /home/djangos/proj WSGIScriptAlias / /home/djangos/proj/proj/wsgi.py <VirtualHost *:80> #LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so AddHandler wsgi-script .py DocumentRoot /home/djangos/proj WSGIDaemonProcess 94.254.0.98 processes=2 threads=15 display-name=%{GROUP} python-home=/home/djangos/lib/python3.6 WSGIProcessGroup 94.254.0.98 <Directory /home/djangos/proj/> AllowOverride all Require all granted Options Indexes FollowSymlinks Includes ExecCGI </Directory> <Directory /home/djangos/proj/> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /home/djangos/proj/insynsregistret/static/ <Directory /home/djangos/proj/static/> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> My apache2.conf ServerName my_server_ip:8000 DefaultRuntimeDir ${APACHE_RUN_DIR} PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 # These need to be set in /etc/apache2/envvars … -
How to connect django with mysql database proberly
First of all im tring to connect a django_project to mysql by editting my_project/settings.py file with the code below I created a database called (mydatabase) and user with full privileges called (admin) identified by (admin), then i tried to connect my django project with mydatabase by the following code below: django_project\mysettings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabase', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '5432', } } Everything was working as expected until i changed that DATABASES dictionary from the default value in file above and it resulted by the following error when i tried to run the server with py manage.py runserver Watching for file changes with StatReloader performing system checks... MySQLdb._exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0") django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0") I didn't provide the traceback for the error as it seemed unneccessary, I would provide it if needed I have both mysql client and mysql connector modules installed : mysql-connector-python 8.0.19 mysqlclient 1.4.6 -
Django No Such Column Exception
The migration file 0001_initial.py shows I have an email column in model Join. The exception below suggests I do not have an email column in model Join. Help? OperationalError at /admin/joins/join/ no such column: joins_join.email Request Method: GET Request URL: http://localhost:8000/admin/joins/join/ Django Version: 3.0.3 Migration File: 0001_initial.py '''from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Join', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=254, unique=True)), ('updated_at', models.DateField(auto_now=True)), ('created_at', models.DateField(auto_now_add=True)), ], ), ]''' Models.py '''from django.db import models class Join(models.Model): email = models.EmailField(unique=True, blank=False) updated_at = models.DateField(auto_now=True, blank=False) created_at = models.DateField(auto_now_add=True, blank=False) def __unicode__(self): return "Join"''' Admin.py '''from django.contrib import admin from .models import Join class JoinAdmin(admin.ModelAdmin): class Meta: model = Join admin.site.register(Join, JoinAdmin)''' -
Django dropdown menu not working with tag 'load bootstrap3'
I am creating a website with django and I have a dropdown menu like this: <li class="dropdown"> <a data-toggle="dropdown" href="#">{{ user.username }}</a> <ul class="dropdown-menu dropdown-menu-left"> <li><a href="{% url 'users:profile' user.username %}">Profile</a></li> <li><a href="#">Requests</a></li> <li><a href="{% url 'booking:cars' %}">Your cars</a></li> <li><a href="#">Your reservations</a></li> </ul> </li> If I go to a page that contains this piece of code: {% load bootstrap3 %} {% bootstrap_javascript jquery='full' %} The dropdown menu is not working, but if I remove the 2 lines above the dropdown menu works fine. Knowing that I have to keep this 2 lines, how I am doing to solve this problem -
How to use yowsup(whatsapp) python lib with django channels?
Hi I'm working to create Whatsapp chat app with Django channels. I used yowsup python lib to interect with whatsapp login, this is working perfect on command line I can send and receive whatsapp message from my terminal. But I don't know how to listen messages in websocket consumer. Thanks in advance. -
Bootstrap Typeahead basic example not working in Django
I am trying to implement Bootstrap Typeahead to eventually use an Elasticsearch instance I have, but I cannot even get the basic example to work in Django (2.2.6). I am taking the majority of this code from the examples page. Here is the HTML I am using: typeahead.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script> <script type="text/javascript"> var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; // an array that will be populated with substring matches matches = []; // regex used to determine if a string contains the substring `q` substrRegex = new RegExp(q, 'i'); // iterate through the pool of strings and for any string that // contains the substring `q`, add it to the `matches` array $.each(strs, function(i, str) { if (substrRegex.test(str)) { matches.push(str); } }); cb(matches); }; }; var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', … -
assigned <= or == or >== to variables python django
Is there any way to assign operators to variables? I have function def get_age(age=0, year_level_from=0, year_level_to=0): overall = [] for level in range(year_level_from, year_level_to): if age <= 11: operator = <= else: operator = >= male_count = len([ info for info in queryset if info.age **operator** age if info.gender == 'male' if info.year_level == level ]) overall.append(male_count) I want to declare like get_age(age=11, year_level_from=1, year_level_to=7) if this is possible so this function have the ability to choose those age with that condition I want to get. thanks in advance -
loading messages in django
I am using django in which I am taking some input from webpage through and displaying back on the same page (like google translator). When I am submitting my form then I want to have loading messages till I get output on the same page. Can someone help me on this ? -
Parametrize attributes of Django-models with multi-table inheritance in pytest-factoryboy
I am using Django and want to write a test using pytest, pytest-django, pytest-factoryboy and pytest-lazyfixtures. I have Django-models that are using multi-table inheritance, like this: class User(models.Model): created = models.DateTimeField() active = models.BooleanField() class Editor(User): pass class Admin(User): pass I also created factories for all models and registered them, such as: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User created = ... # some datetime active = factory.Faker("pybool") class EditorFactory(UserFactory): class Meta: model = Editor ... Now I want to test a function that can take any of User, Editor or Admin as an input and parametrize the test with all user types and variations of active and created, like this (unfortunately it doesn't work like that): @pytest.mark.parametrize("any_user", [lazy_fixture("user"), lazy_fixture("editor"), lazy_fixture("admin")]) @pytest.mark.parametrize("any_user__active", [True, False]) def test_some_func(any_user): ... # test some stuff However that fails with In test_some_func: function uses no argument 'any_user__active'. Any idea how to best solve this? I could of course do sth like this, but it's not as nice: @pytest.mark.parametrize("any_user", [lazy_fixture("user"), lazy_fixture("editor"), lazy_fixture("admin")]) @pytest.mark.parametrize("active", [True, False]) def test_some_func(any_user, active): any_user.active = active # save any_user if necessary ... # test some stuff Any better suggestions? -
highlighting tags with cross sign when i click on right to tag when submitting a form
Like when we try to ask a question in StackOverflow, we need to place tags I want to implement that i.e when I add a tag and click right to it it should be highlighted and also add a cross symbol to its endclick here to see what I mean -
Django JSONField: None saved instead of empty strings
Working with Django, I have a JSONField in my database (PostgreSQL) where I store lists of dictionaries with actors' first names and last names. I want to form references to movies, with title, year, and actors' names. Actors'names can be left blank, and we should get a reference as "Titanic. 1997.", without any actors listed. The problem is that I get the following error when I'm not inserting any actors' names into the forms: KeyError at /add-source/ 'last_name' ... File "E:\Pycharm_projects\movieproject\movie_project\movies\views.py", line 40, in add_movie 'last_name': actor_form.cleaned_data['last_name'], KeyError: 'last_name' I have tried the following: 1) changing the JSONField parameters to null=True or blank=True, or both. To no avail; 2) changing cleaned_data['last_name'] to cleaned_data.get('last name'). This eliminates the error, but actors are stored as None None in the JSONField and are inserted as gaps into the reference (instead of being ignored): "Titanic. 1997. Actors: ." instead of "Titanic. 1997.". The question is: how can I avoid the error and what should I do to insert empty strings instead of None into the JSONField? My code is the following: movie.py: class Movie(Model): title = CharField(max_length=400, blank=True) actors = JSONField(default=dict, blank=True) year = PositiveSmallIntegerField(blank=True, null=True) In my forms.py: class MovieForm(ModelForm): class Meta: model … -
Django tests freeze randomly when run
The issue When running unit tests locally, at a certain point in time, it totally freezes, and I can't understand what's wrong. I have no clue even if I run tests with the maximum verbose -v3 option. I think it can't be related to the tests themselves, because they used to pass, or they still pass in a CI. Plus, it does not always freeze at the same stage. What I uses Docker for mac 2.2.0.3 on MacOS 10.15.3 with PostgreSQL official image (10.12) psycopg 2.7.7 What I tried I tried to run tests on another computer with Docker I tried to comment the test that freezes, but then it will freeze somewhere else I tried to change PostgreSQL version locally I tried to run tests using other options like --reverse or --parallel Any idea? How to debug this? -
No Validation on Field Choices Django Postgres?
I created a Student model with field choices. However, when I save it, it doesn't validate whether the choice is in the choices I specified in the model field. Why doesn't it prevent me from saving a new object with a choice I didn't specify in my model? Here is the model: class Student(models.Model): year_in_school = models.CharField( max_length=4, choices= [ ('FRES', 'Freshman'), ('SOPH', 'Sophomore'), ], ) And here is the code I wrote in the shell: >>> from app.models import Student >>> new_student = Student.objects.create(year_in_school='HACK') >>> new_student.year_in_school 'HA' -
How to filter out duplicate rows from child model before being displayed in Django ListView
I am using two related models in my Django application. The objects so created in the models are being displayed using the listview class. In the child model I can create multiple rows based on some key date. When I try to display values from both the models (linked with an FK field), all the child objects for the respective FK fields are displayed (wherever more than one records are there). Is there a way that I may use select distinct to filter out duplicate rows. I have tried: myModel.objects.distinct().order_by('id') but still getting all the child rows for the parent id. In my template I am using: {% for obj in object_list %} {{ obj.<field1> }} <!-- field1: Parent model field --> {% for item in obj.<child_model>_set.all %} {{ item.<field2> }} <!-- field2: Child model field --> {% endfor %} {% endfor %} My question is: How do I filter out duplicate rows before the data is displayed? -
How can I integrate cloudinary.models.CloudinaryField with Celery?
I have the following model which uploads images to Cloudinary through django admin using pycloudinary: from cloudinary.models import CloudinaryField from django.contrib import admin from django.db import models class Photo(models.Model): name = models.CharField(max_length=159) image = CloudinaryField( "Image", overwrite=True, resource_type="image", transformation={"quality": "auto:eco"}, format="jpg", ) @admin.register(models.Photo) class PhotoAdmin(admin.ModelAdmin): pass How can I assign the upload to celery and make it asynchronous? -
3 loops in one <tr> django
NOTE: if you see same question like this its probably this is it possible to select a field to apply a distinct method? I think its different question The result is totally messed up, can you guys give me an idea on how to fix my template loop? this is my models.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True,blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True,blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Date = models.DateField(null=True, blank=True) Grade = models.FloatField(null=True, blank=True) I tried this in my views.py teacherStudents = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Date') studentname = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Students_Enrollment_Records') Students = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade) and my html <tr> <th>Students Name</th> {% for student in teacherStudents %}<th>{{student.Date}}</th>{% endfor %} th data-id='headers' id='headerave'>Average</th> </tr> <tr> <tbody id="scoreboard"> {% for students in studentname %} <tr class="tr2"> <td><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{students.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> {% for studentss in Students %}<td class="td" ><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{studentss.Grade}}</td>{% endfor %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" … -
How to Access Child Model data from Parent model in django
I have these models class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=255, null = False, unique=True) product_title = models.CharField(max_length=255, null = True) product_price = models.CharField(max_length = 255) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True) class Feature(models.Model): feature_id = models.AutoField(primary_key=True) feature_name = models.CharField(max_length=255, null = False) product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True) feature_has_value = models.CharField(choices=has_value_choice, max_length = 1, null = False) class Product_feature(models.Model): product_feature_id = models.AutoField(primary_key=True) feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name='product_feature') product_feature_value = models.CharField(max_length=255, null = False) Now, how can I fetch product_features from product model? -
How to create django real time chat app with whatsapp?
I developed a chat app with django channels. Its working ok but I need to make real time django chat app with whatsapp. I found a python library on github (https://github.com/tgalal/yowsup) which is working good from command line. But I want to use its consumer with my websocket, So I can chat from frontend. How can I do that? Thanks in advance. -
Can't figure out what did I miss here, it says 'list' is not a valid function. Any help would be appreciated
Error during template rendering In template /Users/mac/myfirstproject/templates/base_layout.html, error at line 12 Reverse for 'list' not found. 'list' is not a valid view function or pattern name. 2enter code here''' 3enter code here 4enter code here 5enter code here 6enter code here 7enter code here ARTICLES 8enter code here 9enter code here 10enter code here 11enter code here 12enter code here 13enter code here {% block content %} 14enter code here {% endblock %} 15enter code here > 16enter code here 17enter code here ''' -
How to pass a javascript array in an html file to another html file in django and also redirect to the new html file
var resulttable = "<table border=1>"; resulttable += "<tr>"; resulttable += "<th>"+heading1+"</th>"; resulttable += "<th>"+heading2+"</th>"; resulttable += "<th>"+heading3+"</th>"; resulttable += "<th>"+heading4+"</th>"; resulttable += "</tr>"; for(var i=0; i<angles.length; i++) { resulttable += "<tr>"; resulttable += "<td>"+angles[i]+"</td>"; resulttable += "<td>"+expert_angle[i]+"</td>"; resulttable += "<td>"+user_angle[i]+"</td>"; resulttable += "<td>"+diff[i]+"</td>"; resulttable += "</tr>"; } Above is the javascript array in an html file. I want to pass this array into another another html file and display its contents to the user. I cant display it in the current page as it already has many contents. I want to know how to pass the javascript array to another file and how to redirect to the new html file after passing of the array. Any help would be appreciated and thanks in advance