Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap grid content position
I have the following code for django-oscar <ul class="row"> {% for product in products %} <li class="col-xs-6 col-sm-4 col-md-3 col-lg-3">{% render_product product %}</li> {% endfor %} </ul> it works find except on the phone. As you can see from the screen shot, there is a weird space in the grid system when the size is reduced to the phone (it actually displays like this on the phone). On the desktop, the grid system displays correctly until the size of the browser becomes less than certain px. Is there a way to fix this? (I think I am using bootstrap3) Grid system working well Phone mode -
Django field cleaning ValidationErrors don't prevent form from processing
I'm designing a Django form with custom cleaning methods for both fields, and the form itself. Ideally, I'd love for my form to stop processing and throw an error if my fields don't validate. However, the custom clean() method that I wrote for my form runs even when fields throw ValidationErrors. Here's an example: forms.py from django import forms from .models import User class BasicsForm(forms.Form): email = forms.EmailField(label='E-mail address', max_length=128) def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError("E-mail is already taken.") return email def clean(self): # Call the parent clean method cleaned_data = super().clean() email = cleaned_data.get('email') u = User(email=email) u.save() If I attempt to submit the above form with an invalid e-mail address (for example, an e-mail already registered on the site, which will raise the ValidationError within clean_email), I get an IntegrityError that says I can't add a NULL e-mail to my database. What's happening is that even though clean_email catches an error, the lines that create a user in my clean() method (i.e., u = User(email=email) and u.save()) still run. How do I make it so that if my clean_email() method catches an error, clean() doesn't run, and my form instead shows the error thrown by … -
How do you split a Django queryset without evaluating it?
I am dealing with a Queryset of over 5 million + items (For batch ML purposes) and I need to split the queryset (so I can perform multithreading operations) without evaluating the queryset as I only ever need to access each item in the queryset once and thus I don't want to cache the queryset items which evaluating causes. Is it possible to select the items into one queryset and split this without evaluating? or am I going to have to approach it by querying for multiple querysets using Limits [:size] to achieve this behaviour? N.B: I am aware that an Iterable can be used to cycle through a queryset without evaluating it but my question is related to how I can I split a queryset (if possible) to then run an iterable on each of the splitted querysets. -
Django shows 404 error on media files when debug = False in production
I'm trying to put a django website live and after going through the deployment checklist and turning debug = False django gives out a 404 error and only static files are loaded no media files uploaded from users are displayed. However with debug=True all the images and files work properly. below are the configurations of the project with debug = True. The console logs show multiple missing files.can someone point to me what i'm doing wrong? settings.py urls.py console errors -
How to update Heroku superuser password after changing Django superuser password?
I have a web app on Heroku and I recently changed the pw to the admin site through terminal with command python manage.py changepassword <user_name>. When I log into the admin site through the local address (http://127.0.0.1:8000/admin) the updated password works, but when I try to log in to the admin site through my heroku web app with the same newly created password, it doesn't work and I have to use the old admin password, defeating the purpose entirely. How do I update the admin password on my heroku website? -
Machine learning web service
I want to build a webservice that takes as input some parameters and a .h5 file , runs a Random Forest model and then populate a chart with the model's output . I'm wondering what is the best framework to accomplish this project ? I start learning both Django and Flask but I'm not sure about the suitable solution . I think there is another alternative by using Ajax and D3js . Could anyone help me to decide ? I will appreciate any recommendation . Many thanks -
Django FormWizard Post to database with FK
I am using the Django Form Wizard and I have successfully created a multistep form that is able to create a new User. I have a second model called UserAddon that I set a OnetoOne relation to. I cant figure out how to POST to that model and to create that relation in the UserAddon. Also if someone knows, should I be using the checks like if form.is_valid(): or if request.method == 'POST': Within this before I post? Thanks! Wizard class ContactWizard(SessionWizardView): template_name = "wizardApp/contact_form.html" def done(self, form_list, **kwargs): process_form_data(form_list) return HttpResponseRedirect('../home') Process form data def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] first_name = form_data[0]['first_name'] last_name = form_data[0]['last_name'] email = form_data[0]['email'] print(last_name) print(first_name) print(email) user = User.objects.create_user(email) user.first_name = first_name user.last_name = last_name user.email = email user.save() ##### SOMETHING LIKE THIS #### user_addon = UserAddon.objects.create(user.email) return form_data Its also worth noting my code is written to set the users email address as the username -
Django error in assigning path using variable album_id and a new path
I have the following urls.py file and an error in the path calling favourite. urlpatterns = [ #this is matching /music/ path('', views.index, name='index'), path("<album_id>/", views.detail, name="detail") #music/<album_id>/favorite/ path("<album_id>/favorite/", views.favorite, name='favorite'), ] The error (while running server) is: INVALID SYNTAX referring to this line: path("<album_id>/favorite/", views.favorite, name='favorite'), Is anyone able to fix/spot the error? -
How to rename column from csv in django_import_export?
I want to import data to my django model from csv by import_export module. Unfortunatelly, field in csv is named "surname" but in model I need "last_name". Is the option to rename column? When I use last_name = Field(column_name='last_name', attribute='surname') I have no data inside. docs:http://django-import-export.readthedocs.io/en/latest/getting_started.html#declaring-fields -
Show foreign key in DJANGO REST
My first question here. Glad to be part of this community. My question: I'm using python3 and the django rest framework to create an API. I have the following models: class Game(models.Model): # id = models.AutoField(primary_key=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) url = models.CharField(max_length=100) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() summary = models.CharField(max_length=2000) first_release_date = models.BigIntegerField() category = models.SmallIntegerField() cover = models.CharField(max_length=100) def __str__(self): return self.name class ReleaseDate(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, on_delete=models.CASCADE) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() category = models.SmallIntegerField() platform = models.SmallIntegerField() date = models.BigIntegerField() region = models.SmallIntegerField() y = models.SmallIntegerField() m = models.SmallIntegerField() human = models.CharField(max_length=10) To create a serializer for the Game and ReleaseDate I'd do: class ReleaseDateSerializer(serializers.ModelSerializer): class Meta: model = ReleaseDate fields = '__all__' class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = '__all__' ... and this would provide me with: [ { "name": "God of war", "url": "efgsd" }, { "name": "Uncharted", "url": "sgdfd" }, { "name": "Fortnight", "url": "efgsd" } ] How would I go about to get this, ie: [ { "name": "God of war", "url": "efgsd" "release_dates": "[ {..}, {..} ]" }, { "name": "Uncharted", "url": "sgdfd" "release_dates": "[ {..}, {..} ]" }, { "name": "Fortnight", … -
Error on terminal while installing django taggit via pip install on ubuntu gnome
I am getting the error on installing django-taggit module... what might be the problem? Please help I have tried everythin and it̀s still bringing the same error even tried updating my setup tools :~$ pip install django-taggit Collecting django-taggit Using cached django_taggit-0.22.1-py2.py3-none-any.whl Installing collected packages: django-taggit Exception: Traceback (most recent call last): File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/taggit' -
django - AttributeError: type object 'file' has no attribute 'set_user'
I have created a model named file. It was running well, then I created an element inside the class named set_user which gave an error. So, I removed it. But, I think it's not deleted my my database as I am getting this error while trying to migrate: AttributeError: type object 'file' has no attribute 'set_user' Here's models.py: from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User class file(models.Model): title = models.CharField(max_length=250) FILE_TYPE_CHOICES = ( ('audio','Audio'), ('games','Games'), ('videos','Videos'), ('applications','Applications'), ('books','Books/Docs'), ('others','Others') ) file_type = models.CharField(max_length=12,choices=FILE_TYPE_CHOICES,default='others') description = models.TextField(max_length=6000) def get_absolute_url(self): return reverse('one:user') def __str__(self): return self.title -
Django and Python models.py indentation error
I have the following code and an error that says 'inconsistent use of spaces and indentation' but I cannot see what has been done wrong? class Song(models.Model): album=models.ForeignKey(Album, on_delete=models.CASCADE) file_type=models.CharField(max_length=10) song_title=models.CharField(max_length=250) def __str__(self): return self.song_title The code above it for another class is exactly the same, but it works class Album(models.Model): artist=models.CharField(max_length=250) album_title=models.CharField(max_length=500) genre=models.CharField(max_length=100) album_logo=models.CharField(max_length=1000) def __str__(self): #this is a string representation of this object - useful for testing/viewing purposes return self.album_title+""+self.artist The error appears to be in the line that returns the string representation of the Song object def __str__(self): return self.song_title More specifically the error seems to point to this line: def __str__(self): (if you note its position above int he Song class, the indentation looks fine...) Can anyone spot the error or suggest a fix? -
Is it better to use path() or url() in urls.py for django 2.0?
In a django online course, the instructor has us use the url() function to call views and utilize regular expressions in the urlpatterns list. I've seen other examples on youtube of this. e.g. from django.contrib import admin from django.urls import include from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] #and in polls/urls.py urlpatterns = [ url(r'^$', views.index, name="index"), ] However, in going through the Django tutorial, they use path() instead e.g.: from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), ] Furthermore regular expressions don't seem to work with the path() function as using a path(r'^$', views.index, name="index") won't find the mysite.com/polls/ view. Is using path() without regex matching the proper way going forward? Is url() more powerful but more complicated so they're using path() to start us out with? Or is it a case of different tools for different jobs? -
python manage.py collectstatic is loading the wrong (local) settings
I am using cookiecutter-django .env design to load different settings depending on environment. Running locally should use "local.py" settings and wunning in aws elatic beanstalk, it should load "dev.py". Both import from "common.py". Running the server in AES with dev settings works, but collectstatic fails, because it tries importing the local settings instead of dev settings. How can the EC2 instance run collectstatic and load the (appropriate) dev.py settings? -
Django Rest How can I show data from a foreign key relationship
Everyone! Using django's rest framework. I created a basic api. Now I want to show my foreign key relationship in my ReleaseDate Model to my Game Model. A game can have one or multiple release dates. My models: # Create your models here. class Game(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) url = models.CharField(max_length=100) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() summary = models.CharField(max_length=2000) first_release_date = models.BigIntegerField() category = models.SmallIntegerField() cover = models.CharField(max_length=100) def __str__(self): return self.name class ReleaseDate(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, on_delete=models.CASCADE) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() category = models.SmallIntegerField() platform = models.SmallIntegerField() date = models.BigIntegerField() region = models.SmallIntegerField() y = models.SmallIntegerField() m = models.SmallIntegerField() human = models.CharField(max_length=10) Now on the API side, I created two serializes for both of my models class ReleaseDateSerializer(serializers.ModelSerializer): class Meta: model = ReleaseDate fields = '__all__' class GameSerializer(serializers.ModelSerializer): #release_date = ReleaseDateSerializer(many=True, read_only=True) class Meta: model = Game fields = '__all__' #fields = ('name', 'url', 'release_date') I want to get all the Game's release dates to show in the JSON Game object. Thank you -
Timezone offset changes in django/postgres
I'm having an issue with Django changing the UTC offset of my data, not entirely at random, but with no prompting that I can see. When I observe it as a datetime.datetime object before saving (via Model.objects.Create()): 2017-12-29 05:16:00-08:00 When I check the column manually in Postgres: 2017-12-29 06:32:00-07 (the -07 offset corresponds to my local timezone) When I re-load the object in Django: 2017-12-29 13:16:00+00:00 How can I get it to preserve the original UTC offset? Do I need to save it in a different way? -
Linking User Profile Page to a model in Django
I am new to Django. i have created a model for a simple textbox app as follows: enter code here from __future__ import unicode_literals from django.db import model class TODO(models.Model): task= models.CharField(max_length=200) Also ,I have created a user login portal.Now I want to activate the model and redirect the user to that page when he logs in.Please help me with that. -
some issue with migrate django saleor e-commerence
I am on ubuntu virtual machine on mac laptop.. I want run saleor e-commerence storefront for django and Django based on saleor docs i solve many errors and now I don not know what to do with the maybe my last error , this in may manage.py file : #!/usr/bin/env python3 mport os import sys if name == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE","saleor.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) and this is installed_apps part of settings.py file: INSTALLED_APPS = [ django.setup() # External apps that need to go before django's 'storages', # Django modules 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'django.contrib.sites', 'django.contrib.staticfiles', 'django.contrib.auth', 'django.contrib.postgres', 'django.forms', # Local apps 'saleor.userprofile', 'saleor.discount', 'saleor.product', 'saleor.cart', 'saleor.checkout', 'saleor.core', 'saleor.graphql', 'saleor.order', 'saleor.dashboard', 'saleor.shipping', 'saleor.search', 'saleor.site', 'saleor.data_feeds', # External apps 'versatileimagefield', 'django_babel', 'bootstrap3', 'django_prices', 'django_prices_openexchangerates', 'graphene_django', 'mptt', 'payments', 'webpack_loader', 'social_django', 'django_countries', 'django_filters', 'django_celery_results', 'impersonate', 'phonenumber_field', ] when i run : python manage.py migrate i got this error: File "/home/sahar/Desktop/last/saleor/saleor/settings.py", line 154 'storages', ^ SyntaxError: invalid syntax did anyone has the same issue? -
Django page failing to render - error in views.py url path
I have an error arising in the views.py file, and as a result I cannot load the page. music/views.py from django.shortcuts import render from django.http import HttpResponse from .models import Album # Create your views here. #each URL is connected to a view or an Http Response def index(request): all_albums = Album.objects.all() html = ' ' for album in all_albums: url= '/music/' + str(album_id) + '/' html +='<a href="' + url + '">'+album.album_title+'</a><br>' return HttpResponse(html) def detail(request,album_id): return HttpResponse("<h2>Details for Album id:" + str(album_id) + "</h2>") The line causing the error is presumably: url= '/music/' + str(album_id) + '/' The actual (page) error is: NameError at /music/ name 'album_id' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/music/ Django Version: 2.0 Exception Type: NameError Exception Value: name 'album_id' is not defined Exception Location: C:\Users\User\Desktop\website\music\views.py in index, line 13 Python Executable: C:\Python34\python.exe Python Version: 3.4.3 Python Path: ['C:\\Users\\User\\Desktop\\website', In a separate test album_id does seem to be "accessbile" in that http://127.0.0.1:8000/music/1/ will correctly load the page (the album id number is displayed on the page). The error points to the code above, but I cannot see how to fix it. Following the New Boston Tutorials and I have googled to see … -
Regex in url not working correctly
I have the following url path. path('(?P<address>add_[a-zA-Z0-9]{60})', views.detail, name='Account Detail'), Here is what I am using: add_3tz8jreirf54a5nknzksqqfbtxchxdy34zds9anxnw4j9sfkzujay6u441pk I've checked on RegExr and all seems fine but I'm getting a 404 error. -
How to search text containing non-ASCII characters with Django icontains query?
I would like to search for text that contains non-ASCII characters using ASCII search keywords, so that 't' matches 'ṭ'. For example, given a Book object with Sanskrit title 'Aṣṭasāhasrikā-prajñāpāramitā-sūtra' in field title, I would like the following query to return it: Book.objects.filter(title__icontains='prajna') -
What is the difference between postgres and psotgres_psychopg2 as a database engine for django?
I have worked with python for a while, but never django. I am taking over a project that a different employee made before leaving our company. I am wondering if there is a difference between the option postgesql and postgres_psycopg2 as a database driver for django. In some articles and the docs about how to set up a django project I have seen just postgresql and in others I have seen the postgres_psycopg2. I couldn't find anything in the docs (here or here) that mentioned psycopg2, so is this just the old way of writing the option? Is one just an alias for the other or are they actually different enignes? I also couldn't find any other SO questions on this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql',# here I also saw postgres_psycopg2 'NAME': 'premqcsite', 'USER': 'django_user', 'PASSWORD': 'Encepta_123', 'HOST': 'localhost', 'PORT': '5432', }} -
How to predict data faster in Django app deployed on Heroku?
I have an algorithm in my Django app deployed on Heroku which predicts data. My problem is that this function works many hours to generate predictions. I need to do it faster. Much faster. The faster the better. It seems to me that the best solution would be to predict each object separately and asynchronously. I mean running predict(name1), predict(name2), predict(name3) ... at the same time. Any ideas how can I solve my problem? @sched.scheduled_job('cron', day_of_week='mon-fri' , hour=19, minute=35) def scheduled_job(): objects = Object.objects.all().values("name") for key in objects: try: predict(key["name"]) except: print("Error in prediction") -
Best appraoch to have different user types in my project?
Desired Outcome: To have a website that has two different types of users. There are the main users who are the customers. There are also the employee users. The customers has an address, an appointment. The employees have available hours to work. On this website users who create an account through the site will automatically become customer accounts. They will have their own dashboard which displays different fields than the employee users see. Steps To Success: Should there be a separate app for the main site where the customers create their account? And then there will be a separate app for the employees. And each app will have their own objects specific to that user type?