Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which web hosting service is free and easy to host my Django app?
I want to host my Django app in Google search engine for free.I know there are many web hosting services like PythonAnywhere,AWS,Heroku etc... Which one is free for hosting? Also, I am hosting a website for first time Please tell which one will be easy to host? -
Update multiple documents in django-mongodb with user inputs
I have a form which is meant to update all the price attribute of the objects in the product_details collection of my mongoDB.It is like Bulk price updating feature. Please suggest the method to do so in django. How can I update the price of multiple products using the same form and view? price.html <form class="col s12" action="{% url "bulk" %}" method="POST">{% csrf_token %} <button class="btn waves-effect waves-light" type="submit" name="action">Update<i class="material-icons right">cloud</i> </button> {% for r in result %} <div class="col s6 m7"> <div class="card horizontal"> <div class="card-image" > <img class ="materialboxed" width="650" src="{{r.ppro}}" style="width:100px; height:150px; max-width:100%; max-height:100%;" > </div> <div class="card-stacked"> <div class="card-content"> <p style="font-size:15px;">{{r.ptitle}}<br>{{r.price}}</p> </div> <div class="card-action"> <div class="input-field col s4"> <input id="input_text" type="text" name=price value="{{r.price}}" data-length="10"> <label for="input_text">Price</label> </div> </div> </div> </div> </div> {% endfor %} </form> </div> views.py def bulk_price(request): product_list= user_db.product_details.find({"shop_id":request.session["_id"]}) user_data = user_db.store_details.find_one({"_id":request.session["_id"]}) if product_list is not None: return render(request,'price.html',{'result':product_list,'status':user_data['status']}) return render(request,'price.html') mongoDB structure of product_details object -
error in column reading of django p
Traceback: File "E:\intallpython\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "E:\intallpython\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "E:\intallpython\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Hamza Ahmed\Desktop\Python\database\customer\views.py" in add 60. cursor.execute("INSERT INTO {0} VALUES ({1},{2})".format(t, name,contactNo)) Exception Type: OperationalError at /customer/add/ Exception Value: no such column: ali where name = ali and contactNo = 0321465 why hes saying no column : ali where column name are C_name and C_contact -
Combine multiple dictionary i
import requests,ast,json r = requests.get(url) data = r.text The output I got is a unicode data u'[{"NOSId":"SSC/N3022","TotalPratical":"85","TotalTheory":"35","Project":"PMKVY","QPID":"SSC/Q2212","QPName":"Domestic Data Entry Operator","QPLevel":"4","BatchNumber":"286279","CandidateId":"7226651","CandidateName":"Amina Begum ","Theory":"0.00","NOSName":"Undertake data entry services","TPName":"OrionEdutechPrivateLimited","TestLocation":"Kamrup","TestDate":"01-Sep-2015"},{"NOSId":"SSC/N9001","TotalPratical":"27.5","TotalTheory":"12.5","Project":"PMKVY","QPID":"SSC/Q2212","QPName":"Domestic Data Entry Operator","QPLevel":"4","BatchNumber":"286279","CandidateId":"7226651","CandidateName":"Amina Begum ","Theory":"0.00","NOSName":"Manage your work to meet requirements","TPName":"OrionEdutechPrivateLimited","TestLocation":"Kamrup","TestDate":"01-Sep-2015"}]' data_detail = ast.literal_eval(data) after performing with ast.literal_eval() data changes to list type and O/P is [{'BatchNumber': '286279', 'CandidateId': '7226651', 'CandidateName': 'Amina Begum ', 'NOSId': 'SSC/N3022', 'NOSName': 'Undertake data entry services', 'Project': 'PMKVY', 'QPID': 'SSC/Q2212', 'QPLevel': '4', 'QPName': 'Domestic Data Entry Operator', 'TPName': 'OrionEdutechPrivateLimited', 'TestDate': '01-Sep-2015', 'TestLocation': 'Kamrup', 'Theory': '0.00', 'TotalPratical': '85', 'TotalTheory': '35'}, {'BatchNumber': '286279', 'CandidateId': '7226651', 'CandidateName': 'Amina Begum ', 'NOSId': 'SSC/N9001', 'NOSName': 'Manage your work to meet requirements', 'Project': 'PMKVY', 'QPID': 'SSC/Q2212', 'QPLevel': '4', 'QPName': 'Domestic Data Entry Operator', 'TPName': 'OrionEdutechPrivateLimited', 'TestDate': '01-Sep-2015', 'TestLocation': 'Kamrup', 'Theory': '0.00', 'TotalPratical': '27.5', 'TotalTheory': '12.5'}] My question is I want to remove [ ] from the both end of the data and want to wrap multiple dictionary into one so that I can pass this to django template. My approach to do this x = ",".join(map(str,data_detail)) O/P i got is "{'QPID': 'SSC/Q2212', 'TotalPratical': '85', 'NOSName': 'Undertake data entry services', 'CandidateId': '7226651', 'Theory': '0.00', 'QPName': 'Domestic Data Entry Operator', 'Project': 'PMKVY', 'TestDate': '01-Sep-2015', 'TotalTheory': '35', 'TPName': 'OrionEdutechPrivateLimited', 'NOSId': … -
Cronjobs set by "django_crontab" do not run for Django manage.py custom command
I want to set a cron job for Django manage.py custom command. I installed the django-crontab by pip install django-crontab then fixed the settings script: Added 'django_crontab', to the INSTALLED_APPS list; Put the following parameter at the end of the settings: CRONJOBS = [ ('* * * * *', '.<app_name>.management.commands.<command>', {'<option1>': "<param1>", "<option2>": True}) ]; I tried to do everything as described in the documentation and after I used /srv/web/<project_name>/manage.py crontab add the changes were made to the crontab configuration file: * * * * * /srv/web/<dev_env>/bin/python /srv/web/<project_name>/manage.py crontab run 375cf15c056862d0d54b5fcf7e52d14b # django-cronjobs for <project_name> But my script never ran so I checked the cron logs which looked like this: May 20 12:55:01 webdevbg CRON[2500]: (<user_name>) CMD (/srv/web/<dev_env>/bin/python /srv/web/<project_name>/manage.py crontab run 375cf15c056862d0d54b5fcf7e52d14b # django-cronjobs for <project_name>) May 20 12:55:01 webdevbg CRON[2499]: (CRON) info (No MTA installed, discarding output) When I manually start the script by using manage.py it runs as expected. I spent quite some time troubleshooting this so I decided to ask for your help and suggestions so thanks in advance. -
Django - operate on db or on data
I'm using django with PostreSQL to retrieve some data via DRF and use this JSON in React. The data that gets called is already filter with models.objects.filter(owner=request.user, date=last_month) All of the fields in the dataset are required, thus no further filtering is required and there is no overhead data. Now I want to split the data of last_month into groups per days. The question is should I: Make different ORM calls for everyday Make ORM call as in the example above and iterate through it in django with pandas Make an call as in the example above and iterate through it in react Which is the most efficient? -
Django form-fields: Styling for Bootstrap without losing functionality?
So form.as_p in django gives a plain, yet very catered form, with field inputs matching the entity attribute type, like so: Notice how vintage is a dropdown item, and so is brand. But then again, it's very plain. I want to use bootstrap styling with the django form without losing the way django customizes each input type by the model attributes. I have managed to achieve this: By doing this in my .pug template: form(method="post" action=".") | {% csrf_token %} for field in da_form div(class="form-group row") label(class="col-lg-4 col-md-3 cold-sm-6 col-form-label") {{field.label_tag}} div(class="col-lg-8 col-md-3 cold-sm-6") input(class="form-control") {{field}} input(class="form-control")(type="submit" value="submit") But how can I both get the style, and the catered form inputs from django? In my current form all fields are simple input types. -
Saving a data stream in a django project
I'm working on a django website project where logged in users are answering questions. I want to store the answers of all users, collecting which user answered, what answer they gave and what question got asked as well as some data on when it was answered etc. I guess this qualifies as stream. How should I go about this? Just write a model to enter the data to a table and give all users the permission to write to that table? Are there better solutions as I heard that writing to a sql db too often isn't good. -
How to extract items out of a QueryDict whcih contains keys with more than one value?
I have this QueryDict: >>> from django.http import QueryDict >>> q = QueryDict('a=1&a=2&c=3') I need a piece of code which returns this result: { 'a': ['1','2'], 'c': '3'} I should inform you that dict(q.iterlists()) returns this: { 'a': ['1', '2'], 'c': [u'3']} regards, -
DataError: value too long for type character varying(10)
The project which I developed contains two forms in two different pages with one text field which is common to both of them. One page text field is working fine but other page text field is giving this error when submitting the form. I couldn't get a solution from other questions of this type. All the parameters for the text field in both models is the same but this error is showing up. -
Django MultiSelect Choices with extra field
i want to have MultiSelectField with and extra field related to each of choices option. for example consider i have 5 option in my choices and i want to let the user to select some of them .it's not difficult to do this , but i want to let the user to fill one extra input per each option. (in django-admin and in the template) how can i achieve this ? Models.py city_names = ( ('C1','City One'), ('C2' , 'City Two'), ('C3' , 'City Three'), ) class City(models.Model): forms = MultiSelectField(max_length=2, blank=True , choices=city_names) Admin Panel: with above lines i can let the user in the admin panel to select multiple choices from the city_names , but i want to have DateTime field for each option that user select. Example City 1 |---- DateTime for City 1 City 2 |---- DateTime for City 2 City 3 |---- DateTime for City 3 -
Can we use filter in django templates?
I was curious to know can we use filter tag in Django templates like that we have in views. like we have in views:- studentcount = Users.objects.using('cms').filter(universityId=item.id,userTypeId=2).count() can we use something like that in templates:- <td>{{ item.users.userTypeId=1_set.all.count }}</td> i know above method is wrong and not working just wrote it so that it is better to understand.And my user model is there in case you want to see my user model. I have a users table which has 3 types of users Student, Faculty and Club. My user model:- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from cms.models.masterUserTypes import MasterUserTypes from cms.models.universities import Universities from cms.models.departments import MasterDepartments # WE ARE AT MODELS/APPUSERS requestChoice = ( ('male', 'male'), ('female', 'female'), ) class Users(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") userTypeId = models.ForeignKey(MasterUserTypes, db_column="userTypeId") universityId = models.ForeignKey(Universities, db_column="universityId") departmentId = models.ForeignKey(MasterDepartments , db_column="departmentId",help_text="") name = models.CharField(db_column="name",max_length=255,help_text="") username = models.CharField(db_column="username",unique=True, max_length=255,help_text="") email = models.CharField(db_column="email",unique=True, max_length=255,help_text="") password = models.CharField(db_column="password",max_length=255,help_text="") bio = models.TextField(db_column="bio",max_length=500,help_text="") gender = models.CharField(db_column="gender",max_length=6, choices=requestChoice,help_text="") class Meta: managed = False db_table = 'users' -
Django 1.5 + gunicorn - No module named website.wsgi?
I am taking over this django legacy project which was built on 1.5.12. I have no idea why they decided to remove wsgi.py from the project. So I am trying to put it back it. wsgi.py import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "website.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() settings.py: try: from local_settings import * except ImportError: from default_settings import * default_settings.py: ... ... ROOT_URLCONF = 'website.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'website.wsgi.application' Then I compile the project with: $ python manage.py runserver 0.0.0.0:8000 Validating models... 0 errors found May 20, 2017 - 07:47:34 Django version 1.5.12, using settings 'website.settings' Development server is running at http://0.0.0.0:8000/ Quit the server with CONTROL-C. It works fine and I can see wsgi.pyc is generated. … -
How to use Django's {% trans %} with Pug/Jade
I'm using pypugjs in my Django project, which is very very simillar to pyjade. Below is a snippet from my .pug file: H3 Bottle Form form(method="post" action=".") | {% csrf_token %} | {{ form.as_p }} input(type="submit" value="{% trans 'Submit' %}") No matter how I try to variate the value attribute for input, I get the following error: 'trans', expected 'endif'. Did you forget to register or load this tag? Please note that I do have the following in my base.html, which the .pug file above extends: <!DOCTYPE html> {% load static %} {% load i18n %} // <-- import for trans tags {% load compress %} Any help is much appreciated! -
livestatus.py on Python 3.5
Sorry for the dummy question, but I'm stuck... :-( Please help me with livestatus.py library, which I tool here: http://git.mathias-kettner.de/git/?p=check_mk.git;a=blob;f=livestatus/api/python/livestatus.py;h=63a95cb6167c2e81701c5067e452c770c18d76a0;hb=HEAD That was written for Python 2.7, that works with it. I'm trying to use it with Python 3.5.3 and it doesn't see work with encoding. Here is code block: # socket.send() will implicitely cast to str(), we need ot # convert to UTF-8 in order to avoid exceptions if type(query) == str: query = str(query, 'utf-8') self.socket.send(query) Error: TypeError: decoding str is not supported Any help would be much appreciated! Thanks! -
How to show validation error as django admin default errors
Is there any way to show validation error in a standard way as the other errors ? class Student(models.Model): ... def save(self, *args, **kwargs): try: super(Student, self).save(*args, **kwargs) except ValidationError: raise forms.ValidationError('There aren't places anymore') -
Updating the values for a Model instance in django with a dictionary
I want to update my model instance using a dictionary, here's an example of what I have instance.attr1 = d['attr1'] instance.attr2 = d['attr2'] instance.save() I read around that it was possible to do: instance.update(**d) but I've ran into <model> object has no attribute 'update' Is there are more elegant solution to what I'm trying to accomplish? Am I misunderstanding the update method? -
does parser always take in arguments as list?
Python Version: Python 3.5.1 Django Version: Django 1.10.2 I am trying to write my own django custom command and I noticed that to take in an argument, it always ends up as a list. See https://docs.python.org/3/library/argparse.html Notice that the arguments for integers is a list of integer. I wanted to have an argument that takes in a relative path or absolute path to a directory written in obviously str format. My question is: is it even possible to only accept the argument as a single str object for the parser object? if it's possible, what do I need to change? My current code is def add_arguments(self, parser): parser.add_argument('path', nargs='+', type=str) # Named (optional) arguments parser.add_argument( '--whiteware', action='store_true', dest='whiteware', default=True, help='Affects whiteware variants only', ) def handle(self, *args, **options): directory_in_str = options['path'] print(directory_in_str) -
object has no attribute 'get_notification_display'
I am trying to display human readable label of choicefield. def reminder(request, pk=None): reminder = get_object_or_404(Reminder, pk=pk) print(reminder.id) # printing correct value print(reminder.get_notification_display()) return render(request, 'reminder.html', {'reminder': reminder, 'title': 'Reminder'}) But it throws this error : AttributeError: 'Reminder' object has no attribute 'get_notification_display' Here is the model: class Reminder(models.Model): provider_type = ( ('Em', 'Email'), ('Sm', 'SMS'), ('De', 'Desktop'), ('Mo', 'Mobile'), ) notification = ArrayField(models.CharField(choices=provider_type, max_length=2, default='Em')) -
Deploying a django 1.5 legacy project with gunicorn and nginx - 502 Bad Gateway
This is how I deploy a django project with gunicorn and nginx: $ sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=teelou Group=www-data WorkingDirectory=/var/www/html/django-project/helloapp ExecStart=/var/www/html/django-project/helloapp/env/bin/gunicorn --workers 3 --bind unix:/var/www/html/django-project/helloapp/helloapp.sock helloapp.wsgi:application [Install] WantedBy=multi-user.target And I can get this sample project working at http://127.0.1.1:8000/. It shows the django default welcome screen. This is Django==1.11.1. But I am taking over this legacy project which is on Django >= 1.5. The trouble is the previous developers are reluctant to hand over this project and so making it very difficult for me to figure out how this django legacy can be run on my local machine and the new production server. I can get it running with python manage.py runserver 0.0.0.0:8000 both on my localhost and the production. But I cannot get it running with gunicorn. This is what they are willing to provide in ~/services/gunicorn.template with: #!/bin/bash SCRIPT=$(readlink -f $0) SCRIPTPATH=`dirname $SCRIPT` # go one dir up PROJECT_ROOT=`dirname $SCRIPTPATH` cd $PROJECT_ROOT source .env/bin/activate exec \ setuidgid %(USER)s \ python manage.py run_gunicorn \ 127.0.0.1:%(PORT)s \ --workers=4 \ --timeout=180 \ --log-file=$PROJECT_ROOT/logs/gunicorn.log \ --graceful-timeout=10 \ --log-level=DEBUG \ --worker-class=eventlet \ --debug There is no wsgi.py in this legacy so if I have the config below in /etc/systemd/system/gunicorn.service: [Service] … -
How to get CSRF protection work with pagination?
I want to enable pagination in a search form with CSRF protection, so I have to add the csrfmiddlewaretoken GET parameter to the link to the previous/next page. The url looks like this: localhost:8000/myapp/search/?csrfmiddlewaretoken=JHgf7Cs6WgX29oOsLEpkW1w91ROVTpxXtNAgU1kSA3sDW1aUUOcXmBnxufahqfIS&q=foobar Here is what I've done: search.html <form method="get" action=""> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary btn-block"> {% trans "Search" %} </button> </form> ...... {% include 'pagination.html' %} pagination.html <a href="{# csrf_token #}?q={{ query }}&amp;?page={{ page_obj.previous_page_number }}"> <span aria-label="Previous">&larr;</span>{% trans "Previous" %} </a> What should I replace {# csrf_token #} with to pass the CSRF token to the next page? -
is there a way to refactor these two functions? django
I figured I have been using this quite a lot to render info from a query. I wonder if there's a way to refactor them? examples of the codes are def render_objA(self, objAs): output = [] for obj in objAs: output.append({ 'id': obj.id, 'name': obj.name 'description': obj.description, 'createdAt': obj.created, 'modifiedAt': obj.modified }) return output def render_objB(self, objBs): output = [] for obj in objBs: output.append({ 'id': obj.id, 'name': obj.name, 'content': obj.content, 'createdAt': obj.created, 'modifiedAt': obj.modified }) return output def render_objC(self, objCs): output = [] for obj in objCs: output.append({ 'id': obj.id, 'first_name': obj.first_name, 'last_name': obj.last_name, 'full_name': obj.full_name, 'createdAt': obj.created, 'modifiedAt': obj.modified }) return output Some output might have more fields than others and of course different field name too. This really depends. The only similar and for sure fields will be the same is the createdAt and modifiedAt Can someone give me an idea or let me know how? Thanks in advance -
django - CreateView form_valid is not cleaning image fields
I'm using a CreateView with multiple required image fields. When images are uploads and submitted form_valid returns false and claims that no images were uploaded. If I get the images directly via POST however, I can gain access to the files. Has anyone came across the same error? Thanks in advance. -
How might one implement Site-specific Tags?
My code shop is developing a multi-tenant Wagtail site, and we'd like each Site to have its own set of tags. We want this so that tags defined by users of Site A don't appear in the autocompleter or the "popular tags" listing for users of Site B. Would this be possible with a custom Tag model? I'm thinking that we could prefix the tag's slugs with the hostname of the current Site, then filter them based on that prefix when pulling tags for the "popular tags" listing or the autocompleter. If this is not currently possible, could Wagtail be monkey-patched to support it? If so, what code might need to change? -
Get related model name from current model name in abstract model class
In my Django 1.11 app, I have an abstract model class AbstractModel, from which I subclass concrete models FooModel and BarModel. There are also concrete models FooValue and BarValue defined. From within AbstractModel, I want to define a one to one field to the corresponding Value model. class AbstractModel(models.model) value = models.OneToOneField(<corresponding Value Model class>, ...) class Meta: abstract = True class FooModel(AbstractModel): pass class BarModel(AbstractModel): pass class FooValue(models.model): pass class BarModel(models.model): pass How do I get corresponding XXXValue class depending on which concrete XXXModel class is in scope? To do this, I need to do three things: I need the current concrete model class name _my_class_name in the class definition (which seems hard to impossible) Then I can string replace to get the XXXValue class name: _value_class_name = _my_class_name.replace('Model', 'Value') Finally, I need the XXXValue concrete model object from its name. The recommended approach since Django 1.7 seems to be to get it via apps.get_model(app_label, model_name), but this doesn't work in models.py, giving AppRegistryNotReady error.