Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Query - How to use the objects.filter results
If I use the following code it works perfectly: campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] for x in campaignnoquery: test2 = x.campaignno However, when I try: campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] test1 = campaignnoquery.campaignno I get the following error: test1 = campaignnoquery.campaignno AttributeError: 'QuerySet' object has no attribute 'campaignno' I am sure it is something basic and I could just crack on with the one that worked but I am just intrigued on whats happening. Many thanks in advance, Alan. -
Djang Allauth dynamic LOGIN_URL
I am using django-allauth on my website to handle user login/logout/signup. For now I simply want users to be able to login/register from every page on the site. For this purpose i added a bootstrap modal to my base.html, accessible over a button in the header. <div class="modal-body"> <form method='post' action='/accounts/login/?next={{ request.get_full_path }}' id='login'> {% csrf_token %} {{ login_form|crispy }} <input type='submit' class="btn btn-primary" value='Log In'> </form> </div> I used a context processor to provide the LoginForm from allauth: from allauth.account.forms import LoginForm def login_form(request): return { 'login_form': LoginForm } This works well as long as the login data is correct. I get redirected to my source page with a logged in state. Now if a user enters a wrong password, the allauth template in /accounts/login gets rendered and the error messages displayed. I would like to override the LoginForm/LoginView in a way that it calls the view from the request and adds the form (with errors) to the context. Is this possible? -
Django-paypal can't call "process_pdt" django 1.10
I'm using Django 1.10 with the plugin django-paypal. I've followed the guide, but when i try to call the process_pdt fonction, it doesn't work... I've imported : import paypal.standard.pdt.views.process_pdt But, it seem there is no views.process_pdt This is the guide : http://django-paypal.readthedocs.io/en/stable/standard/pdt.html -
Why do we need cmd in window for many work?Why cant we use windows for all work?
We use cmd for various purposes.For eg we use it for developing web app in django,we use it for hacking.Why cant we use GUI windows for all work. -
What the right setting for django-dbbackup?
Using django 1.10, django-dbbackup 3.0, postgresql-9.5.4 I'm wrote in config settings from the docs http://django-dbbackup.readthedocs.io/en/stable/installation.html, but got this error: Traceback (most recent call last): File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/utils/module_loading.py", line 23, in import_string return getattr(module, class_name) AttributeError: module 'dbbackup.storage' has no attribute 'filesystem_storage' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/dbbackup/utils.py", line 99, in wrapper func(*args, **kwargs) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/dbbackup/management/commands/dbbackup.py", line 49, in handle self.storage = get_storage() File "/home/user/envs/siteEnv/lib/python3.5/site-packages/dbbackup/storage.py", line 30, in get_storage return Storage(path, **options) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/dbbackup/storage.py", line 66, in __init__ self.storageCls = get_storage_class(self._storage_path) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/core/files/storage.py", line 469, in get_storage_class return import_string(import_path or settings.DEFAULT_FILE_STORAGE) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/utils/module_loading.py", line 27, in import_string six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/user/envs/siteEnv/lib/python3.5/site-packages/django/utils/module_loading.py", line 23, in import_string return getattr(module, class_name) ImportError: Module "dbbackup.storage" does not define a "filesystem_storage" attribute/class (siteEnv) -
django request.session throws Atrribute error
I get this error 'WSGIRequest' object has no attribute 'session' on the manage.py runserver. When I try to retrieve the session dict from request.session. Searches on this item say I need to put 'django.contrib.sessions.middleware.SessionMiddleware' on top of the MIDDLEWARE settings. However this does not seem to work. My settings.py: """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '@ta=3ful!*bzj^o@3+avt#qrm9@uz%6ur_d@ihs#j--5us*r_(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'FEM', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'laizen.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', #'django.core.context_processors.csrf', ], }, }, ] WSGI_APPLICATION = 'laizen.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
How to use SearchResult.get_additional_fields()
I am new to django haystack. I am using Haystack with Xapian backend. My search results from search queryset API dont give all the fields. I read in the documentation that I need to use How to use SearchResult.get_additional_fields() method from Search Result API but the documentation doesn't provide any examples. Can someone please let me know how to use the method with my queryset? -
Show Django Model @property as a bool in model admin
I have a model with a property, It returns boolean, I want to show it as icon in django model admin. models.py class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) @property def is_new_bar(self): return bar == 'NEW' admin.py class FooAdmin(admin.ModelAdmin): list_display = ('bar', 'is_new_bar') # is_new_bar is shown as True/False text, I want this as bool icon of django. -
how to add change language dropdown to Django(1.10) admin?
I'm planning to add change language dropdown in my admin page. according to this code and How to extend admin page. I copy base_site.html and copy it to myapp/templates/admin, the i create a html file named change_language.html and write this code in it: {% load i18n %} / {% trans 'Change language' %} <form action="/i18n/setlang/" method="post" style="display: inline;"> <div style="display: inline;"> <select name="language" onchange="javascript:form.submit()"> {% for lang in LANGUAGES %} <option value="{{ lang.0 }}"{% ifequal LANGUAGE_CODE lang.0 %} selected="selected"{% endifequal %}>{{ lang.1 }}</option> {% endfor %} </select> </div> </form> I add {% extends 'admin/base_site.html' %} at the top of this file, noting happens. I add {% extends 'admin/base.html' %} , again noting happens. All hints and answers says that we should change something name <div id="user-tools"> at line 25 of base.html, But in Django 1.10 it goes to line 31 with a different staff. im kinnda lost because i read many different staff every where and non of them works for me. Dose any know where im doing wrong ? -
django wsgi.py cannot recognize settings file
A strange problem occured while trying to configure apache2 to serve a Django project via wsgi. My project is a small to-do list implemented here. https://github.com/panospet/toDoList When apache tries to run wsgi.py, returns this error: Traceback (most recent call last): File "/var/www/toDoList/myToDoList/wsgi.py", line 19, in <module> application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named myToDoList.settings My wsgi.py file is like: import os import sys sys.path.append(' /var/www/toDoList') sys.path.append(' /var/www/toDoList/myToDoList') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myToDoList.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() and also my .conf file inside /etc/apache2/sites-enabled: <VirtualHost *:80> DocumentRoot "/var/www/toDoList" ServerName blahblah WSGIDaemonProcess todolist user=test group=test threads=5 WSGIScriptAlias / /var/www/toDoList/myToDoList/wsgi.py <Location /todolist> WSGIProcessGroup todolist </Location> <Directory /var/www/toDoList/toDoList> Order allow,deny Allow from all </Directory> Alias /static /var/www/toDoList/myToDoList/static/ <Directory /var/www/toDoList/myToDoList/static> Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> -
Push media files to a seperate nginx VM with Django in production
I don't know if I missed information regarding this. But I want to know how to store static files to a different VM. I've read that some recommend doing that to larger sites to seperate the load. My current setup is that I use one computer engine with nginx, virtualenv, gunicorn etc. I use nginx to display the static files (including the media files) on the same server. How can I push media files to a seperate nginx server when a user uploads an image? How can I obtain the same url as well? -
Reduce quantity when product is sold
I have a model of product and sale. A product contains a list of product with name, price and quantity where a sales model has product(Foreign key), quantity and price. There is a form for sale which shows list of products, quantity and price. Whenever a user selects for the product, the price field should show the price of that product and which should be uneditable. How can it be done? My code Product class Product(models.Model): name = models.CharField(max_length=120, blank=True, null=True, help_text="name of the product") quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return self.name product/forms.py PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' product/views.py def add_product(request): if request.method=='POST': form = ProductForm(request.POST or None) if form.is_valid(): # product = form.save(commit=false) # product.save() name = form.cleaned_data['name'] price = form.cleaned_data['price'] quantity = form.cleaned_data['quantity'] Product.objects.create(name=name, quantity=quantity, price=price) messages.success(request, 'Product is successfully added.') return redirect('/product/') else: form = ProductForm() return render(request, 'product/product_add.html', {'form':form}) sales/models.py class Sale(models.Model): product = models.ForeignKey(Product) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return self.product.name class SaleForm(forms.ModelForm): class Meta: model = Sale fields = '__all__' def add_sale(request): if request.method=='POST': form = SaleForm(request.POST or None) if form.is_valid(): # product = … -
Why am I getting 502 Bad Gateway on Django app with Nginx and Gunicorn?
I have been trying to deploy a demo app with this tutorial. I am doing this on a CentOS 7 in Virtualbox. However, I am getting 502 Bad Gateway. How can I fix this? server {} block in nginx.conf file server { listen 80; server_name 172.16.16.215; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/michel/myproject; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/michel/myproject/myproject.sock; } } gunicorn.service file [Unit] Description=gunicorn daemon After=network.target [Service] User=michel Group=nginx WorkingDirectory=/home/michel/myproject ExecStart=/home/michel/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:/home/michel/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target -
Migrate users data from django to drupal 7
Is there a way to migrate users data from django to drupal-7. I have 800 users in my old django website and want to migrate these users to drupal-7. Please suggest some tricks or tutorial. I googled a lot but was unable to find any direct solution. Thank you for your help and suggestions. -
Turn list of dictionaries into Django model isntances
I have a huge array of JSON objects in a json file. some objects have more keys than others, but they are all keys that are fields in a model class that I have. I am wondering, what is the best way to iterate over each JSON object to create a model instance with the data from that object, creating null values for any field that the object does not include ? minerals.json (snippet) [ { "name": "Abelsonite", "image filename": "240px-Abelsonite_-_Green_River_Formation%2C_Uintah_County%2C_Utah%2C_USA.jpg", "image caption": "Abelsonite from the Green River Formation, Uintah County, Utah, US", "category": "Organic", "formula": "C<sub>31</sub>H<sub>32</sub>N<sub>4</sub>Ni", "strunz classification": "10.CA.20", "crystal system": "Triclinic", "unit cell": "a = 8.508 Å, b = 11.185 Åc=7.299 Å, α = 90.85°β = 114.1°, γ = 79.99°Z = 1", "color": "Pink-purple, dark greyish purple, pale purplish red, reddish brown", "crystal symmetry": "Space group: P1 or P1Point group: 1 or 1", "cleavage": "Probable on {111}", "mohs scale hardness": "2–3", "luster": "Adamantine, sub-metallic", "streak": "Pink", "diaphaneity": "Semitransparent", "optical properties": "Biaxial", "group": "Organic Minerals" }, { "name": "Abernathyite", "image filename": "240px-Abernathyite%2C_Heinrichite-497484.jpg", "image caption": "Pale yellow abernathyite crystals and green heinrichite crystals", "category": "Arsenate", "formula": "K(UO<sub>2</sub>)(AsO<sub>4</sub>)·<sub>3</sub>H<sub>2</sub>O", "strunz classification": "08.EB.15", "crystal system": "Tetragonal", "unit cell": "a = 7.176Å, c = … -
models Django invalid literal for int() with base 10: 'None'
I am new to Django, I am tring to make a Blog here is my models from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): name = models.OneToOneField(User) def __unicode__(self): return self.user.user_name class Category(models.Model): category = models.CharField(max_length=150) def __str__(self): return self.category class Blog(models.Model): title = models.CharField(max_length=150, default="No title") body = models.TextField(default="None") creation_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(UserProfile, default=1) category = models.ForeignKey(Category, default="None") def __str__(self): return self.title class Comment(models.Model): comment = models.TextField(default="") blog = models.ForeignKey(Blog) but when i run the command: python manage.py migrate i get the ValueError: invalid literal for int() with base 10: 'None' I tried to delete the old migration file and migrate again but I got the same error, what should I do? -
Python Django Package
django.conf.urls.url() Where django, Conf and urls are packages And url() is a function How can directly import a function from a package? Shouldnt there be a module? please help. Thanks. -
I cant get a request send from a form to a view in Django?
Here is my views.py: def favorite_song_album(request, album_id): album = get_object_or_404(Album, pk=album_id) try: selected_song = album.song_set.get(pk=request.POST['song'])#request.POST.get("title", "") except (KeyError, Song.DoesNotExist): return render(request,'musica/detalle.html', { 'album':album, 'error_message':"No seleccionaste una cancion valida"}) else: selected_song.is_favorite = True selected_song.save() return render(request, 'musica/detalle.html', {'album':album,'selected_song':selected_song,}) models.py from django.db import models class Artist(models.Model): nombre_artist = models.CharField(max_length=60) edad = models.IntegerField() def __str__(self): return self.nombre_artist class Album(models.Model): album_nombre = models.CharField(max_length=60) genero = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) def __str__(self): return "Album: "+self.album_nombre+" - "+self.artist.nombre_artist class Song(models.Model): song_nombre = models.CharField(max_length=40) album = models.ForeignKey(Album, on_delete=models.CASCADE) artist = models.ManyToManyField(Artist) is_favorite = models.BooleanField(default=False) def __str__(self): return "Song: "+self.song_nombre urls.py urlpatterns = [ # /music/ url(r'^$', views.index, name="index"), # /music/id/ url(r'^(?P<album_id>[0-9]+)/', views.album_detail, name="detail"), # /music/id/favorite url(r'^(?P<album_id>[0-9]+)/favorite/', views.favorite_song_album, name="favorite_song_album"), ] and finally heres my template detalle.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <img src="{{album.album_logo}}"> <h1>{{album.album_nombre}} - {{album.artist.nombre_artist}}</h1> <h4>{{album.genero}}</h4> {% if error_message %} <p><strong>{{error_message}}</strong></p> {% endif %} <form action="{% url 'musica:favorite_song_album' album.id %}" method="POST"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.pk}}"/> <label for="song{{forloop.counter}}"> {{song.song_nombre}} {{song.is_favorite}} {% if song.is_favorite %} <img src="https://cdn2.iconfinder.com/data/icons/diagona/icon/16/031.png"> {% endif %} </label><br> {%endfor%} <input type="submit" value="Favorite"> </form> </body> </html> so basically this website must show a star when i change the value "is_favorite" but … -
Installed app in Django not found when running tests
I have a pretty simple Django app, that I am trying to run unit tests on. In my tests.py file I am trying to import the parent apps views file. I tried 'from . import views' but got an error: SystemError: Parent module '' not loaded, cannot perform relative import I read that when a relative path does not work, you can try using an absolute path so I tried 'from menu import views' but than got another error: ImportError: No module named 'menu' When I run a local server for the application it works just fine. Its only when I run 'coverage run 'coverage run menu/tests.py'. Since it is running fine, and the module is in my setting's installed apps, Im not entirely sure why this is happening. menu/tests.py import unittest from menu import views class ModelTestCase(unittest.TestCase): def setUp(self): pass def test_menu(self): pass if __name__ == '__main__': unittest.main() settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'menu', 'django_nose' ) -
How to serialize 2 models with custom relationship in django-rest-framework?
I have 2 existing tables in database and i haven't permission to alter them. Show as models below. class Prenames(models.Model): typ = models.DecimalField(max_digits=1, decimal_places=0, db_column='tprpretyp') code = models.DecimalField(max_digits=3, decimal_places=0, db_column='tprprecod') name = models.CharField(max_length=20, db_column='tprprenam') class Profiles(models.Model): userid = models.CharField(max_length=6, db_column='rmsuserid') prename = models.CharField(max_length=4, db_column='rmsprenam', null=True) name = models.CharField(max_length=25, db_column='rmsname') surname = models.CharField(max_length=25, db_column='rmssurnam') If sql i have to SELECT * FROM Profiles left join Prenames on tprpretyp = int(rmsprenam/1000) and tprprecod = mod(rmsprenam,1000) WHERE trim(rmsuserid) = ? Things I've already try: from rest_framework import serializers from .models import * class PrenameSerializer(serializers.ModelSerializer): class Meta: model = Prenames fields = ('type', 'code', 'name') class ProfileSerializer(serializers.ModelSerializer): prenames = PrenameSerializer(read_only=True) class Meta: model = Profile fields = ('userid', 'name', 'surname', 'prenames') Things I've got: { "userid": "560174", "name": "******", "surname": "******" } Things I expected: { "userid": "560174", "name": "******", "surname": "******" "prenames":[ { "type:":10, "code": 01, "name": "Mr." } ] } I'm using django-rest-framework 3.2.5 and django 1.6 how do i serialize them? -
alter the structure Tastypie uses in the list view
I have json list view that look like this: { "objects": [ { "active": false, "id": 4, }, { "active": false, "id": 5, } ] } I want to get rid of "objects" word, so that structure will look like this: { [ { "active": false, "id": 4, }, { "active": false, "id": 5, } ] } This link to docs has no clue in it -
What is the difference between table level operation and record-level operation?
While going through the documentation of django to muster the detailed knowledge, i endured the word 'table level operation' and 'record level operation'. What is the difference in between them? Could anyone please explain me this 2 word with example? Does they have other name too? P.S I am not asking their difference just because i feel they are alike but i feel it can be more clear to comprehend this way. -
Cusomize json output in django tastypie
How to exclude meta information and "objects" word from tasypie json output? { "meta": { "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1 }, "objects": [ { "id": 4, "long_desc": "long", }, ] } I want it to look like this: [ { "id": 4, "long_desc": "long", }, ] -
How to count blank or NULL fields for a particular record
I would like to make work a progress bar in a view with the ratio of the fields already completed with to the total number of fields. If any body have an idea, thanks -
Django error admin panel
Hi guys can someone help me i'm totaly noob in python when i wont delete user or add something i have that error enter image description here