Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django tastypie - how to populate a nested resource which is not field in current resource
I have a resource like this: class User(ModelResource): friends = fields.ToManyField(UserResource, ....blah blah) Where friends is not a field in the model User But I want the friends to be listed in the api. How to do that ? -
Django static files (404 not found) - Openshift
I'm trying to run my very first project using Python/Django on Openshift and have problem with loading my static files. I've read the https://docs.djangoproject.com/en/dev/howto/static-files/ multiple times I have been breaking my head over this for a full day but can't figure out the problem. I'm running a developer server: python manage.py runserver setting.py STATIC_URL = '/static/' if 'OPENSHIFT_REPO_DIR' in os.environ: STATIC_ROOT = os.path.join(os.environ.get('OPENSHIFT_REPO_DIR'), 'wsgi', 'static') else: STATIC_ROOT = os.path.join(WSGI_DIR, 'static') template {% load static %} <a href=""><img src="{% static "logo2.png" %}"></a> urls.py from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^$', RedirectView.as_view(url='/index/')), url(r'^index/', include('index.urls')), url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ] urlpatterns += staticfiles_urlpatterns() The weirdest thing is that after pushing my app to openshift everything is working just fine but on localhost sth goes wrong. Make long story short: 127.0.0.1:8000/static/logo2.png - Not found mysite.rhcloud.com/static/logo.png - Yeah, I see the image I hope it's clear and my problem is as stupid as I imagine. Django 1.8, OS Windows -
Django models.save() is not saving to the Database
I am attempting to pass a models a dictionary of values so that i can set the fields of the model and save the data to my database, but i seem to be running into an error when i try and save the model. line_sample = Sample(**sample_dict) #line_sample = Sample.objects.create(**sample_dict) line_sample.contract = contracts[line['contract_no']] line_sample.status = 'Pending' #errors_found.append('Or Here') # if the contract requires reconciliation then if contracts[line['contract_no']].reconciliation_required: # pass SampleDesignParameters the parameter dictionary and create line_parameters line_parameters = SampleDesignParameters(**parameter_dict) line_parameters.contract = contracts[line['contract_no']] line_parameters.name = 'Auto-Created' line_parameters.save() line_sample.parameters = line_parameters #errors_found.append('Maybe Here') line_sample.save() The error is on line_sample.save() and not line_parameters.save(). I checked to make sure that all of the dictionary names matched up with the field names in class Sample (models.Model). Could the error in the save be due to a data typing error? installation_date = models.DateField(help_text="Please enter in the following format: MM/DD/YYYY") Is one of the fields that is in class Sample(models.Model), if this is where the error is, how would i go about passing the model the installation date in a datetime format? -
Timeout error with nginx and Django app using uWSGI
I have a problem with a Django application; I'm trying to set up a deployment server but I am getting a timeout error. I am running uWSGI: uwsgi --http :8000 --chdir /home/rrcms/myproject/ --wsgi-file /home/rrcms/myproject/quickstart/wsgi.py and when I go to www.mydomain.com:8000 I can see the site running but when I try to configure nginx on port 80 to make it communicate with uWSGI I get a 504 Gateway Time-out, here's my nginx sites-available file: upstream django { server 127.0.0.1:8000; } server { listen 80; server_name www.mydomain.com; charset utf-8; # max upload size client_max_body_size 75M; location /static { alias /home/rrcms/myproject/static; } location / { uwsgi_pass django; include /home/rrcms/myproject/uwsgi_params; } } I'm running out of ideas on what might be happening. -
Displaying results using custom HTML for Select2QuerySetSequenceView in django-autocomplete-light
I'm using django-autocomplete-light 3.2.1 with Django 1.10. What I am building is an autocomplete that gives results from 2 different models in custom HTML (as I want to display thumbnails). The documentation shows how to display autocomplete results with custom HTML when using Select2QuerySetView and get_result_label(self, item), and this works great when building an autocomplete which gives results from 1 model only. However, I am using Select2QuerySetSequenceView because I need to display results from multiple models. get_result_label(self, item) doesn't seem to be working with Select2QuerySetSequenceView and I've tried jumping into the source code but still cannot figure out how to display results with custom HTML. Appreciate any advice, thanks! -
OSError libpoppler error in django
I recently installed ArchLinux (i686 architecture). I have been trying to get my django application running and successfully installed all the requirements from the txt file. Now, when I run python manage.py runserver or python manage.py migrate, I get the following error Traceback ..... ..... File "/usr/lib/python2.7/ctypes/__init__.py", line 362, in __init__ self._handle = _dlopen(self._name, mode) OSError: libpoppler.so.59: cannot open shared object file: No such file or directory I have looked inside /usr/lib/ and there is only a libpoppler.so.66. I am not sure but libpoppler seems to be a dependency/requirement for the gdal package. i have tried installing some python and system packages that I thought might fix the problem but to no avail. I did find the file available here but as an rpm file. I found this post which explains how to extract from rpm, but I am not even sure if that would fix my problem. -
Is Django better than PHP while developing a social networking site?
I am thinking of developing my own social networking site,which will be better,Django or PHP? -
Custom orderable Radiogroup in Wagtail admin FormBuilder
By default we can add a Radiogroup as a comma-delimited text (Radio 1, Radio 2, Radio 3, ...). This is inconvenient and limits. It would be much easier if it were possible to add radio buttons dynamically, like InlinePanel and expand their content using StructBlock or something else to add extra data to radio. In my case, I need to do something like this Is it posible at all? If yes, how can I do this? -
Django Formset Errors With Input Name
I want to get formset errors corresponding to its input name. Here I am using ajax to send the form data. models.py class Category(models.Model): category = models.CharField(max_length=128) forms.py class CategoryForm(forms.ModelForm): class Meta: model=Category field ="__all__" CategoryFormset = modelformset_factory(Category, CategoryForm, , min_num=2, extra=0) when i submit the form, i got the errors like this python shell formset.errors [{'category': [u'This field is required.']}, {'category': [u'This field is required.']}] But in my templates input name is different form-0-category and form-1-category. So is it possible to get errors something like this: [{'form-0-category': [u'This field is required.']}, {'form-1-category': [u'This field is required.']}]. Somebody please help me. templates <p> <input id="id_form-0-category" maxlength="128" name="form-0-category" type="text"/> </p> <p> <input id="id_form-1-category" maxlength="128" name="form-1-category" type="text" /> </p> -
How serialize count() from sql query to JSON
I have spatial query for postgresql (and postgis). I use raw() function. So I have something like this: observations = Square.objects.raw('SELECT validation_birds_square.id AS id, validation_birds_square.identification, Count(validation_birds_checklist.position) AS total FROM validation_birds_square ...the rest of sql query...') I use Square model which I defined in my models.py. Then I want serialize observations, so I make this: return HttpResponse(serializers.serialize("json", observations), content_type='application/json') But here is the problem. It serialize only properties of Square model, not total from sql query. Is there any better way how to put total to serialized JSON than iterate over observations and serialize it manually to JSON? -
Google App Engine, Cloud SQL Django: Lost connection to MySQL server at 'reading initial communication packet'
I created an App Engine Django project and a Cloud SQL database to use with that project. I followed this sample project from Google. Here are my Django project's requirements: django==1.10 djangorestframework==3.5.3 djangorestframework-jwt==1.9 MySQL-python==1.2.5 Here's the app.yaml file: runtime: python27 api_version: 1 threadsafe: yes handlers: - url: .* script: cuz.wsgi.application builtins: - django_wsgi: on libraries: - name: MySQLdb version: "latest" And here's my database connection setting in settings.py: import os if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): # Running on production App Engine, so use a Google Cloud SQL database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/<my-project-id>:<my-cloudsql-connection-string>', 'NAME': 'edbox', 'USER': 'user', 'PASSWORD': 'password' } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # I took the IP address from the Overview section in Cloud SQL Console 'HOST': 'IP_ADDRESS', 'NAME': 'edbox', 'USER': 'user', 'PASSWORD': 'password' } } This is a screenshot from the IAM & Permissions section. And I can confirm that my Cloud SQL database and the App Engine app belongs to the same project, that my database connection string is correct, that the username and password for the database is correct too. In fact, I can run the project successfully with the with the Cloud Shell using the … -
TypeError: BookList is not a constructor
I have code js in my template in django app: bookList = new BookList(); bookList.init(); updateBookUrlList(); And in this code I get an error: Uncaught TypeError: BookList is not a constructor I have this code in external file book-list.js: var BookList = function () { }; ... ... ... I can't figure out what is wrong with my code. -
Django's admin does not login after custom authentication
The custom authentication I wrote follows the instructions from the docs. I am able to register, login, and logout the user, no problem there. Then, when I create a superuser python manage.py createsuperuser, it creates a user in the database, but it does not let me login when I go to the admin page and try to login saying Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive. Here is my code: models.py: from __future__ import unicode_literals from django.db import models from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser, Group, Permission from django.contrib.auth.models import BaseUserManager from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied, ObjectDoesNotExist, MultipleObjectsReturned from datetime import datetime from django.contrib.auth.models import PermissionsMixin import re class CustomUserManager(BaseUserManager): def create_user(self, email, password = None): '''Creates and saves a user with the given email and password ''' if not email: raise ValueError('Email address is requied.') user = self.model(email = self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): ''' Creates and saves a superuser with the given email and password ''' user = self.create_user(email, password = password) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """ Custom … -
Apache2, Django. Import Error
I have some problem with deployment Django app on Apache2 web server. I had so error: ImportError: No module named 'myproject.settings' But I didn't know why. Could you help me? My config file: <VirtualHost *:80> Alias /static /var/www/myproject/myproject/static <Directory /var/www/myproject/myproject/static> Require all granted </Directory> <Directory /var/www/myproject/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/var/www/myproject python-home=/var/www/agora/ENV WSGIProcessGroup myproject WSGIScriptAlias / /var/www/myproject/myproject/myproject/wsgi.py </VirtualHost> And wsgi.py: import os import sys path = '/var/www/myproject' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Django queryset sum and average values
I have trouble in finding a sum and avg value of the shares bought, my code is as follows models.py class Stock(models.Model): name = models.CharField(verbose_name='Name of Stock', max_length=300) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) slug = models.SlugField(unique=True) purchase_price = models.DecimalField(verbose_name='Purchase Day Price', blank=True, null=True, max_digits=30, decimal_places=2) pre_price = models.DecimalField(verbose_name='Last Day Price', blank=True, null=True, max_digits=30, decimal_places=2) current_price = models.DecimalField(verbose_name='Current Price', blank=True, null=True, max_digits=30, decimal_places=2) class BuyStock(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) stock = models.ForeignKey(Stock, verbose_name='Search') quantity = models.IntegerField(verbose_name='Quantity Required',default=0) timestamp = models.DateTimeField(auto_now=True, auto_now_add=False) views.py def stock_bought(request): queryset = BuyStock.objects.filter(user=request.user) context = {'queryset': queryset} return render(request, 'stock/stock_bought_list.html', context) stock_bought_list.html {% for item in queryset %} <tr> <td> <a href="{{ item.get_absolute_url }}">{{ item.stock.name }}</a> </td> <td> {{ item.purchase_price }} </td> <td> {{ item.quantity }} </td> </tr> {% endfor %} Now if the user purchase same stock many times the list also shows that much times seperately, but I want it to be as a single item(based on name) and sum of quantity and average of price, hope somebody can help me, thank you. -
Token authentication based on custom user while using dajngo rest_framework
i have register page,the users register their data.the thing is i need to provide tokens to registered users while they are registering,for this i have User model,and i added rest_framework.authtoken in installed apps and DEFAULT_PERMSSION ,AUTH_USER_MODEL in settings.py, and i have ower field in User class, when i'm trying to register getting this error IntegrityError: (1048, "Column 'owner_id' cannot be null") . views.py def transregister(request): if request.POST: args = {} args.update(csrf(request)) # try: if request.method == 'POST': user = UserForm(request.POST) username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_pwd = request.POST['confirm_pwd'] company_name = request.POST['company'] profile_type = request.POST['trainer-company'] trainerprofile = TrainerForm(request.POST) corporate_profile = CorporateProfileForm(request.POST) print username if user.is_valid(): userModel = user.save(commit=False) userModel.is_user = True userModel.is_active=True userModel.save() models.py class User(models.Model): username = models.CharField(max_length=150) #username = models.OneToOneField(User, on_delete=models.CASCADE) email = models.CharField(max_length=250,unique=True) company = models.CharField(max_length=250) password = models.CharField(max_length=150) confirm_pwd = models.CharField(max_length=150) is_admin = models.BooleanField(default=False) is_user = models.BooleanField(default=False) is_active = models.BooleanField(default=False) device_id = models.CharField(max_length=1000, blank=True, null=True) # User = get_user_model() user = settings.AUTH_USER_MODEL owner = models.ForeignKey('user', related_name='User', on_delete=models.CASCADE) highlighted = models.TextField(default = '') objects = UserManager() #class Meta: # db_table = u'index_user' REQUIRED_FIELDS= ('username',) USERNAME_FIELD = ('email') def __str__(self): return self.username @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) serializers.py class UserSerializer(serializers.ModelSerializer): … -
Iterating Django class object in manage.py shell?
I am trying to iterate through Django Class objects inside models.py in order to create a pie graph which is relevant to each Class object, based on information stored in another db. Running the shell in the command prompt, I input: from file.models import Person, piemaker for i in Person.objects.all(): i.piegraph = i.pgraph() i.save() When doing so, I get a piegraph as png file for each of the objects in my Person class; however, it looks like the graphs are being layed one on top of the other instead of popping out as a single graph. Like labels are repeated and on top of each other. I am stuck at where this is broken, but my guess is inside my for loop? When I just run the piemaker function on one class object alone, it spits out the correct png file containing a nice piegraph. from file.models import Person, piemaker a = Person.objects.get(name='name') a.piegraph = a.pgraph() a.save() I have been working on this for two days straight to no avail. Any help would be appreciated. #!python3 ###import statements#### from django.db import models import pandas as pd import sqlite3 import re import matplotlib.pyplot as plt ##global start and end variables#### start … -
Ordering CharField form choices in Django
I currently have a form that I am creating via django.forms.ModelForm. I've listed the choices for one of the CharFields that is in the form, but upon translation, the choices are of course out of order -- they remain in the order that they were listed in models.py. I'd like for the choices to be alphabetized in the translated language. How can I go ahead and translate them, and then order them, so that in the form, they are listed in alphabetical order? I think I might have to override the __init__ method for self.fields, but have not been able to do so in a way that successfully re-orders my categories. def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) SORTED_CATEGORIES = sorted(CATEGORIES) self.fields['category'].choices = SORTED_CATEGORIES -
Reading data from a CSV and uploading information to database
I am attempting to allow users to upload a csv file rather than manually inputting all the information that is requried to create a contract. When i read the csv the information needs to populate 3 different tables in the database. Im attempting to do this by creating a dictionary of the fieldnames and their values and then passing this information to a function to populate the database. The part that im stuck on is that creating the Contract and Sample Design Parameters work fine, but the Sample Table is not updating and gives me an error. (The error code is commented out right now just to make sure everything else works). for num, line in lines: try: # creates a dictionary of all the field names for sample fields # and the values in the csv file sample_dict = {k: line[k] for k in sample_fields} # creates a dictionary of all the field names for parameter_fields # and the values in the csv file parameter_dict = {k: line[k] for k in parameter_fields} # this is working because when the except is commented out the # csv will create the contracts, but the samples are not added # if the … -
EC2: Deploying a django project with a apache server
I have set up an ec2 instance and I'm able to connect to it via ssh. I've installed apache, django, git and all the necessary dependencies. I've managed to clone a git repository which is located in /home/ubuntu/. I've also set up the configuration file in /etc/apache2/sites-enabled/hyper-blog.conf. This is my hyper-blog.conf file: <VirtualHost *:80> ServerName ec2-52-11-240-28.us-west-2.compute.amazonaws.com ServerAlias ec2-52-11-240-28.us-west-2.compute.amazonaws.com ServerAdmin webmaster@localhost DocumentRoot /home/ubuntu/hyper-blog/ AddDefaultCharset UTF-8 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined alias /static/ /home/ubuntu/hyper-blog/static/ alias /media/ /home/ubuntu/hyper-blog/media/ <Directory "/home/ubuntu/hyper-blog/static"> Require all granted Options -Indexes </Directory> <Directory "/home/ubuntu/hyper-blog/media"> Require all granted Options -Indexes </Directory> <Directory /home/ubuntu/hyper-blog/hyper-blog> <Files wsgi.py> Require all granted </Files> </Directory> #RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^ https://www.hyperiondev.com%{REQUEST_URI} WSGIDaemonProcess hyper-blog python-path=/home/ubuntu/hyper-blog:/usr/local/lib/python3.4/dist-packages WSGIProcessGroup hyper-blog WSGIScriptAlias / /home/ubuntu/hyper-blog/hyper-blog/wsgi.py The problem is when I go to my public domain: ec2-52-11-240-28.us-west-2.compute.amazonaws.com it takes a while to load and eventually does not render anything. I need to know how to get my application up and running. I've tried this documentation on digital ocean https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04, but still doesn't work. How can I get my application working without installing virtualenv? -
Django iFrame Login
I have a client that has a CMS built in Radial. They'll be loading a Django website using an iFrame. That Django website requires a logged in user. The client does not want to have their users login/register twice (once in their Radial site, and second in the Django iFrame). I've setup a RESTful API call that they can call each time someone registers on their site, so that it automatically creates an account on the Django site. But how can I implement some kind of an auto login functionality so that when the user logs in on the Radial site, or when the iFrame is loaded, the user is already logged in on the Django site? -
HTML5 constraint validation translation with Django
I have some form that I am generating using the standard django.forms.ModelForm. When a required field isn't filled out, an HTML5 validation error is trigged (i.e., Please fill out this field, or Please lengthen this text to 200 characters or more (you are currently using 3 characters). However, the validation text is not translated, and I do not see it in my translations I've generated with makemessages. How could I make sure that these validation errors get appropriately translated? Thanks, -
Python continue in csv reader loop skips all rows
I am trying to iterate through a CSV file and I have a try..except block to catch malformed data. The fist line on the file I am testing with has a bad entry which it should skip, but then it also skips every subsequent line. If I delete the first row with the bad entry the rest of the data loads as expected. csvfile = TextIOWrapper(request.FILES['doc'].file, encoding=request.encoding) reader = csv.reader(csvfile) next(reader) ## Skip the header line for r in reader: data = {'field1' : r[1], 'field2' : r[2]} try: my_object = MyObject.objects.create(**data) except: ## There was en error with the data continue I'm at a bit of a loss as to why every line gets skipped if only the first line actually contains malformed data. The other lines work if the first line is removed.. -
Django Forms and Languages
I am trying to do form with Language Select field. This field is for the user and I am going to store it in the Database. language_code = forms.ChoiceField(choices=settings.LANGUAGES, widget=forms.Select(), initial='en') class LanguagesForm(): class Meta: model = Languages fields = ('language_code', ) Everything works fine except the translation of the languages. I am getting for language ENGLISH / RUSSIAN.... But I would like RUSSIAN to be written in Cyrillic How to achieve the same effect like {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} -
Create several pages from array
I'm developing my Django Project about Civil State and I have a question according to my HTML template. I'm displaying a list of objects from my BirthCertificate table with an HTML Array as you can see in my script : {% extends 'Base_Accueil.html' %} {% load staticfiles %} {% block content %} {% load bootstrap %} <style> table, th, td { border: 1px solid black; padding: 10px; border-collapse: collapse; text-align: center; } th {background-color: #0083A2;} tr:hover td{background-color:lightslategray;} </style> <!-- Title page --> <h2 align="center"> <font color="#0083A2"> Consultation des tables annuelles et décennales </font></align></h2> <!-- Body page --> <br></br> <h4> <b><font color="#0083A2"> <span class="glyphicon glyphicon-user"></span> Liste des actes de naissance </b></font></h4> <form method="GET" action=""> <input type="text" name="q1" placeholder="Entrer une année" value="{{ request.GET.q1 }}"> &nbsp; <input class="button" type="submit" value="Rechercher"> </form> <br></br> <table style="width:50%"> <tbody> <tr> <th>ID</th> <th>Nom</th> <th>Prénom</th> <th>Date de Naissance</th> <th>Ville de Naissance</th> <th>Pays de Naissance</th> <th>Date création de l'acte</th> </tr> {% for item in query_naissance_list %} <tr> <td> {{item.id}} </td> <td> {{item.lastname}} </td> <td> {{item.firstname}} </td> <td> {{item.birthday}} </td> <td> {{item.birthcity}} </td> <td> {{item.birthcountry}} </td> <td>{{item.created}}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock content %} I get this website page : My question is : How I can …