Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 2 crud operations without database with external api
I have an external third-party API for retrieving and storing song names and I need to interface it with Django 2 and permit the user through Django forms to insert and update songs. I'm struggling as most documentation on Django assumes a database backend and even examples on consuming an external REST API assume I want to store fetched data from the API to the database. I looked into creating a Django 2 custom model manager but it seems this is used as something above an existing database and not an external API. Django 2 serializers permit to serialize and deserialize data in between an API and a database. What I'm missing is the way to create a custom model abstracting the API and permitting me to use it as if it were a database so that I can go on and follow any Django forms tutorial after having abstracted the model layer. Currently I hacked something like below: urls.py : urlpatterns = [ url(r'^$', viewSong, name='home'), url(r'^create/$', SongView.as_view(), name='create'), url(r'^update/(?P<song_id>[0-9\.a-z]+)/$', SongUpdate.as_view(), name='update'), ] templates/form.html : <form role="form" action="/create/" method="post"> {% csrf_token %} <div class="form-group"> <label for="song-id">Song Id</label> <input type="text" id="song-id" name="song-id"> </div> <div class="form-group"> <label for="son-name">Song Name</label> <input type="text" … -
How to display 3 lists together using Python 3 + django2?
I have a list as follow: item1, [subitems] item2, [subitems] ... itemN, [subitems] For instance, item1 .. itemN might be a list of classes, and [subitems] contains a list of students that attend each class. A student might attend more than 1 class. Each class and student has a description (in a string variable). I want to create a (static) table that contains two columns. The first column is the list of classes. When I click to one element in the first column, the second column will display the list of students attend this class. Also, the description of the class will be displayed. If I click to a student, the cell will expand and display the description of the student. Sorry if the description is not so clear. The idea is as the image following: The list and description are stored in TXT files, not database. -
Heroku not pushing Django App due to buildpack error
I am trying to upload my Django project to Heroku with Python. My app was built on Python 3.6.1 and when I go to push the app to heroku I am receiving the following error message in the terminal: remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to random-appio. remote: I have included a runtime.txt file containing the following: python-3.6.1 I also have a Procfile containing: web: sh -c "cd directory && gunicorn directory.wsgi" As well as a requirements.txt file containing: Django==2.0.2 gunicorn==19.7.1 pytz==2018.3 whitenoise==3.3.1 My requirements.txt, Procfile and runtime.txt are all in the project directory. I can't see where I am going wrong here - any ideas? Thanks everyone. -
Trying to display same model with different pagination
So I have this page with 2 columns. First column represents the way I display my courses in the second column. On the second column all my courses are listed and from the first column I can choose how to list specific courses (by faculty) that replaces the all courses on the second column when pressed on faculty name. I added pagination to all courses of the second column which works as intended. Then when I tried to add pagination by faculty, only first faculty will appear and if I press on second page of the faculty courses, it will redirect me to all courses pagination for some reason.. <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if courses.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ courses.previous_page_number }}">{{ courses.previous_page_number }}</a> {% endif %} <span class="current"> Page {{ courses.number }} of {{ courses.paginator.num_pages }} </span> {% if courses.has_next %} <a href="?page={{ courses.next_page_number }}">{{ courses.next_page_number }}</a> <a href="?page={{ courses.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> {% for faculty in faculties %} <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% … -
Front end development with a coupled Django back-end
There has been a lot of talk about having Django have a front-end set of tools. When will this come to fruition? What about a 'Django.js'? -
Django installation error, when install by pip3 command
After that command: aset@aset-linux ~ $ pip3 install django Traceback (most recent call last): File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 666, in _build_master ws.require(requires) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 984, in require needed = self.resolve(parse_requirements(requirements)) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 875, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.VersionConflict: (pip 8.1.1 (/usr/lib/python3/dist-packages), Requirement.parse('pip==9.0.1')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/pip3", line 6, in from pkg_resources import load_entry_point File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 3147, in @_call_aside File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 3131, in _call_aside f(*args, **kwargs) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 3160, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 668, in _build_master return cls._build_from_requirements(requires) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 681, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/home/aset/.local/lib/python3.5/site-packages/pkg_resources/init.py", line 870, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application What should I do? I want to create site on Python by Django. Perhaps someone has a similar experience and would agree to help me. Thanks! -
django rest-framework serializer reverse relation
I am programming django based web site using django rest-framework. I want to use rest-framework to get model's data. this is my model.py class TimeTable(models.Model): subject_name = models.CharField(max_length=50) subject_code = models.CharField(max_length=10, unique=True) classification = models.CharField(max_length=50) professor = models.CharField(max_length=50) department = models.CharField(max_length=50) credit = models.CharField(max_length=1) year = models.CharField(max_length=4, default='2018') semester = models.CharField(max_length=1, default='1') def __str__(self): return self.subject_code + '-' + self.subject_name class Class(models.Model): owner = models.ForeignKey(Profile, null=True) timetable = models.ForeignKey(TimeTable, null=True) grade = models.FloatField() this is serializer.py class TimeTableSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TimeTable fields = ('url', 'subject_name', 'subject_code', 'classification', 'professor', 'department', 'credit', 'year', 'semester') class ClassSerializer(serializers.HyperlinkedModelSerializer): timetables = TimeTableSerializer(read_only=True) class Meta: model = Class fields = ('url','owner', 'timetable', 'grade', 'timetables') I want to get JSON response Like this (http://localhost:8000/api/classes/) [ { "url": "http://localhost:8000/api/classes/8/", "owner": "http://localhost:8000/api/profiles/19/", "timetable": "http://localhost:8000/api/timetables/3/", "grade": 4.5 "timetables": { "url": "http://localhost:8000/api/timetables/3/", "subject_name": "Artificial Inteligence", "subject_code": "3413513413", "classification": "major", "professor": "John Lee", "department": "software", "credit": "3", "year": "2018", "semester": "1" } } ] but i got this [ { "url": "http://localhost:8000/api/classes/8/", "owner": "http://localhost:8000/api/profiles/19/", "timetable": "http://localhost:8000/api/timetables/3/", "grade": 4.5 } ] How Can I get TimeTable's JSON data in Class JSON?? -
Offline context with Wagtail Page data (Django-Compressor)
I've got Wagtail set up with Django-Compressor (COMPRESS OFFLINE = True) which all works except for one template. This template uses the Disqus plugin which requires: An absolute page url A unique page identifier In my template I have included the following: {% compress js inline %} // My JS Code this.page.url = "{{ page.full_url }}"; this.page.identifier = {{ page.id }}; {% endcompress % So when accessing the page I get the error You have offline compression enabled but key "ARANDOMKEYGOESHERE" is missing from offline manifest. As per the Django-Compressor docs: If you use any variables inside the {% compress %} blocks, make sure to list all values you require in COMPRESS_OFFLINE_CONTEXT How would I go about adding the Page instance to the context in my settings? I thought of something like (pseudo-code): COMPRESS_OFFLINE_CONTEXT = { 'page': request.get('page') } -
How does Django logging work
I want to implement logging to my live Django site so I can see errors, so I'm just practising using it on my local development server. I added this bit of code in my settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.django', }, }, 'loggers': { 'django': { 'handlers': ['console','file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } When I started the development server, it returned this: Performing system checks... System check identified no issues (0 silenced). (0.009) SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name; args=None (0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() February 14, 2018 - 08:38:57 Django version 1.11.8, using settings 'draft1.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But that doesn't tell me anything or show me errors. I was hoping for a traceback or log of all errors. Otherwise I can't see the errors in my Django code in my live server. -
Django Multi-Table Inheritance Performance
So I'm building a Django App that models companies with multiple levels of Organization: E.g. Company > Region > Store > Department, each represented with a separate Model. A User can be added as a Member to any one or multiple. In addition to Members, there are other Models that are related/"belong" to one of the organizational Models. I've been banging my head against my keyboard, but haven't found anything that answers the question: What's the best way to model that? The easiest way by far is to create a OrganizationalEntity Model that all of the above inherit from using Multi-Table inheritance, the Member Model using a M:1 relation with OrganizationalEntity. My research has yielded rather simpleton answers amounting to "Multi-table uses JOINs - that's bad!", with little evidence or context (is one level of inheritance super bad, or is just when you have 50 levels?). As far as I know, one level of inheritance is one JOIN - Relational DBs were kinda designed for that. Another solution (and my current one) is using a GenericForeignKey and some slightly hokey queries to achieve zero JOINs. It works, but adding Models is more than just adding a ForeignKey Field, plus it's … -
How do I resolve a type-error that int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' in polls app?
My models.py is class Question(models.Model): CATEGORY_SIZES = ( ('W', 'WORlD'), ('T', 'TECHNOLOGY'), ('S', 'SCREEN'), ('P', 'SPORTS') ) question_text = models.CharField(max_length= 100) pub_date = models.DateTimeField('Date Is Published') image = models.ImageField(upload_to="Question_Image", blank=True) category = models.CharField(max_length=1, choices=CATEGORY_SIZES) def __str__(self): return self.question_text And, I added four views in format inside views.py def world(request): latest_questions = Question.objects.filter(category='W') context = {'latest_questions': latest_questions} return render(request, 'polls/world.html',context) Then, I ran a command python manage.py makemigrations polls and set timezone.now as default for category Then, I ran another command python manage.py migrate And, I got this type error that TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' -
WSGIDaemonProcess causes 'You don't have permission error'
Hello I am trying to deploy my django application on digital ocean server. I did run the application inside a virtual environment and it all worked fine. But I want my domain to point to my application and followed this tutorial. But the problem is when the apache conf file is edited with the following code i get the error. Forbidden You don't have permission to access / on this server. This is how my directly looks +root +myproject +myproject settings.py urls.py wsgi.py +static manage.py +myprojectenv Here is my WSGI.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() Here is my Apache Default conf file 000-default.conf <VirtualHost *:80> #ServerAdmin webmaster@localhost #DocumentRoot /var/www/html Alias /static /home/user/alpha/static <Directory /home/user/alpha/static> Require all granted </Directory> Alias /static /home/root/myproject/static <Directory /home/root/myproject/static> Require all granted </Directory> <Directory /home/root/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/root/myproject/myprojectenv python-path=/home/root/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/root/myproject/myproject/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined I am not experience enough to find out what is causing the error. If i remove below lines in the apache conf file. I get Ubuntu home page when i try to access my server WSGIDaemonProcess myproject python-home=/home/root/myproject/myprojectenv python-path=/home/root/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/root/myproject/myproject/wsgi.py -
Could not find the GDAL library
I am unable to install GeoDjango. I am having the following error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? Try setting GDAL_LIBRARY_PATH in your settings. I tried the following the solution GeoDjango could not find GDAL library in Windows 10. But it didn't help me and I still have the same error. -
Is there a more concise notation than decorators to have a function called before any view function
All of my view functions require the django request object to pass some tests. Is there a shorter notation for this than putting a @request_passes_test(always_the_same_test) on top of each view-function? -
How can I find the locale settings with Gspread
Is there a way to find/change the locale setting of my Google Spreadsheet using Gspread? I want to import the data from multiple sheets owned by international clients and want to check the locale of each sheet before importing the data in my database. -
Display Dictionary values from python file in html page Django
I have searched alot about it but can't find the right answer. what i need to do is that in my project im running my python file which is showing me the result. Now what i need to do is that i need to show those values in my Dashboad.html page. Here is the code Dectree.py def showTree(self, dic, seperator): if(type(dic)==dict): for item in dic.items(): print(seperator, item[0]) self.showTree(item[1], seperator + " | ") else: print(seperator + " -> (", dic +")") tree = DecisionTree() tr_data, clss, attrs = tree.read_data('test.csv') tree1 = tree.create_tree(tr_data, clss, attrs) tree.showTree(tree1, ' ') right now im not using any view file for doing this. Dectree.py file is in my project folder and im trying to call it in my templates/Dashboard.html page. Kindly guide me here -
How to get jQuery range slider value into form to store in database in Django
The user have to be able to submit and save the value of the range slider 1. The purpose is that the user guesses how full an object is in real life and then can report back as part of a game the filling percentage. The user interface is in the picture below. Currently I can retrieve the data from the POST form (in the slider.html) as a preset 'value' but not the range slider value. I have looked much around, the problem is i'm not familiar enough with Javascript to implement the solution. I'm thinking one can fetch the value from the javascript function and directly tot he POST html form? Can anyone help suggesting how to do that or any other suggestions? This is the code so far, it's a bit of a mess because of many try and errors Models.py from django.db import models from django.forms import ModelForm from django import forms class Measurements(models.Model): DeviceId = models.IntegerField(blank=True, null=True) TimeStamp = models.DateTimeField(auto_now=True) Metadata = models.IntegerField(blank=True, null=True) Sensor = models.IntegerField(default=False) Button = models.IntegerField(default=False) QrUser = models.IntegerField(default=True) FillingPercentage = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True) slider_value = models.IntegerField(default=False, null=True, blank=True) def __str__(self): return str(self.DeviceId) class Meta: verbose_name_plural = "Measurements" Forms.py from django.forms … -
502 Gate Way - nginx/1.10.3 (Ubuntu) Dropplet One-Click Django Server
My Droplet One-Click Django Server respponse 502 Bad GateWay Error. Here is nginx error.log 2018/02/14 06:09:09 [error] 1486#1486: *3960 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 60.191.38.77, server: _, re$ 2018/02/14 06:12:09 [error] 1493#1493: *1 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 31.223.26.233, server: _, requ$ -
Adding forms to empty formset in HTML code
Django v1.10. How do I add forms to my formset dynamically on my webpage? Can this be done locally without using 3rd party plugins? None of the solutions for similar SO questions is working for me. -
how to send email in django
my settings in settings.py but not sending any mails to gmail account. can u please expalin me how to send confirm mail to mailenter code here EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'elearn.communication1@gmail.com' EMAIL_HOST_PASSWORD = 'kanth143' EMAIL_PORT = 587 I am getting success message in cmd but not sending email to my id def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() current_site = get_current_site(request) print(current_site) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) from_email =settings.EMAIL_HOST_USER print(from_email,"email here") # to_email = [from_email,'sridharadhi50@gmail.com'] to_email = form.cleaned_data.get('email') email = EmailMessage( subject, message, to=[to_email] ) email.send() # user.email_user(subject, message) return redirect('account_activation_sent')enter code here -
Django Cannot get media images or files
Django 2.0.2 cannot get the images or cannot show the images in media directory, also I defined them both media and static url and directory in setting.py. I don't know how to write the views.py Here is the error I am getting: (""GET /media/Cover_jDKCLdR.jpg HTTP/1.1" 404 4542") Thanks; -
How to resolve an Operational Error at /admin/polls/queston/ which says no such column: polls_queston.category_id?
I have created a class Categories in models.py class Categories(models.Model): name = models.CharField(max_length= 100) def __str__(self): return self.name And, in order to classify questions into categories, I have class Question(models.Model): category = models.ForeignKey(Categories, on_delete=models.CASCADE) def __str__(self): return self.question_text I have one category named world in views.py def world(request): category = Categories.objects.get(name='world') latest_questions = category.question_set.all() context = {'latest_questions': latest_questions} return render(request, 'polls/world.html',context) And, also I have prepared urls for each of four categories: world, technology, screen and sports and after all this when I open ...../admin/polls/question, I get an operational error. What am I supposed to modify here? -
Formset for MainClass<-ForeignKey<-OneToOneField?
I need to process applications to an amateur sports event. An event has several distances/subclasses, each of them has some restrictions (age, etc). My models are class Event(models.Model): title = models.CharField(max_length=255) # more fields class Klass(models.Model): title = models.CharField(max_length=255) capacity = models.IntegerField() event = models.ForeignKey('Event', related_name="klasses") # more fields class TeamRestrictions(models.Model): age_min = models.IntegerField() age_max = models.IntegerField() klass = models.OneToOneField(TeamRestrictions, related_name='restrict') # more fields I want to have a single page where a user creates a new event: names it, adds several subclasses into it and restrictions for every subclass. Well, without this one-to-one relationship, for just Event with several Klasses, I could use FormSet. Of course, I could move all TeamRestrictions fields to Klass, but that looks ugly for me. What should I use for this more complex structure? -
How to add a dynamic form in django form wizard
I am using django-formtools to split the registration form. I have a BaseUserProfileForm and three seperate form for different user models. At step 0, form is BaseUserProfileForm. I want to add the next form based on the value of request.user.userprofile.role. I have tried overriding get_form_list. def get_form_list(self): self.form_list = OrderedDict({'0': BaseUserProfileForm}) if self.request.user.userprofile.role == CUSTOMER: self.form_list.update({'1': CustomerForm}) elif self.request.user.userprofile.role == SELLER: self.form_list.update({'1': SellerForm}) elif self.request.user.userprofile.role == OTHER: self.form_list.update({'1': OtherForm}) for form_key, form_class in six.iteritems(self.form_list): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: self.form_list[form_key] = form_class return self.form_list Now I am getting error in get_form method. Also I am having seperate templates for these three forms. -
How to send image file without saving in database using django framework
I'm a novice in Django an am stuck in Django views.py am two field in forms.py 1st CharField 2nd ImageField my CharField is successfully rendered but ImageField does not render how solved this I want to send image file with tweet without saving in database please me to solved this problem thanks my files are here- forms.py from django import forms class HomeForm(forms.Form): tweet = forms.CharField() img = forms.ImageField(label='Select a Image file',) Views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import * from django.views.generic import TemplateView class Texting(TemplateView): Template_name = 'app_temp/xyz.html' def get(self, request): form = HomeForm() return render(request, self.Template_name, {'form': form}) def post(self, request): access_token = 'XYZ' access_token_secret = 'PQR' consumer_key = 'LMN' consumer_secret = 'ABC' api = TwitterAPI(consumer_key, consumer_secret , access_token , access_token_secret ) form = HomeForm(request.POST , request.FILES) if form.is_valid(): text = form.cleaned_data['tweet'] img = form.request.FILES['img'] r = api.request('statuses/update_with_media', {'status':text}, {'media[]':img}) return render(request,'app_temp/new_page.html') html {% extends 'login_base.html'%} {% block content %} <div class="container"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Tweet</button> </form> <h1>{{img}}</h1> <h1>{{text}}</h1> </div> {% endblock %}