Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-carton cart with two product models
I am using django-catron and I wonder if I can associate two of models as products for my cart? If yes, how? I have two models: Hall and Caterer and I want them to be my products, which I can insert in my cart (and basically perform any other provided operations). CART_PRODUCT_MODEL = ['marriage_halls.models.Hall', 'marriage_halls.models.Caterer'] I tried something like this setting but it gives me error: no attribute 'rsplit' -
Set the length of a modle field to a length of 5
I am using Django and I want to set one of my fields in my database to only allow numbers that are 5 integers long. I found max_length, is there a length? Here is my code zip_code = models.IntegerField(max_length=5) Is there a way to zip_code = models.IntegerField(length=5) Force user to enter 5 numbers. -
Django amazon s3 collectstatic not updating
I am uploading my django static files to an amazon s3 bucket. Installed django-storages==1.4 boto==2.39.0 Also , set AWS_PRELOAD_METADATA = True in settings Still the updated static files are not uploaded. Any ideas? -
How do I update my Django url for version 1.10?
So I'm going through PluralSight's 'Django Fundamentals' and it's based on an older version of Django. As I'm writing this now I am using Django 1.10 which I believe is the up to date version. As I'm following the video I'm creating a database for a fictional school. This is my url pattern based on the one on the Pluralsight tutorial: from django.conf.urls import url from django.contrib import admin from school.views import home urlpatterns += patterns( 'django.contrib.auth.views', url(r'^login/$', 'login', {'template_name': 'login.html'}, name = 'school_login'), url(r'^logout/$', 'logout', {'next_page': 'school_home'}, name = 'school_logout'), ) Now how to I update it so that it works with Django 1.10? -
django ModelFormWithFileField, ModelWithFileField
I am trying to import ModelWithFileField without sucsess. here https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/ it says to import in the following manner: from .models import ModelWithFileField this does not work for me, I get: ImportError: cannot import name ModelWithFileField I have upgraded to the latest version of django I get the same error when trying to do this: from .forms import ModelFormWithFileField Anyone out there know how to get these imports working? -
django-registration-redux with custom user model error NOT NULL constraint failed: myauth_user.username
In my project occurre this error: IntegrityError at /accounts/register/ NOT NULL constraint failed: myauth_user.username I need use django-registration-redux but i dont subscribe view to transform username=email. How do make this? -
Parsing XML into a dictionary of lists Python/Django
I'm having a little issue with parsing an xml with python. I'm trying to get my dictionary to look like the following listDict = [{'name':'Sales','id':'1','position':'1','order_by_type':'True','order_by_asc':'True;}, {'name':'Information','id':'2','position':'1','order_by_type':'True','order_by_asc':'True;}] I'm thinking my loop after pulling data from the xml string is wrong. xml_data = ElementTree.fromstring(self.data) # Lets grab all the base cats info and add them to a dict containing a list base_cats = xml_data.findall('./BaseCategory/Name') base_cats_id = xml_data.findall('./BaseCategory/base_id') base_postion = xml_data.findall('./BaseCategory/position') base_order_by_type = xml_data.findall('./BaseCategory/order_by_type') base_order_by_asc = xml_data.findall('./BaseCategory/order_by_asc') # store all information into lists base_cat = [t.text for t in base_cats] base_id = [t.text for t in base_cats_id] base_p = [t.text for t in base_postion] base_obt = [t.text for t in base_order_by_type] base_asc = [t.text for t in base_order_by_asc] base_dict = defaultdict(list) # lets put everything in the list into a dictionary for base in range(len(base_cat)): # for each base in base_cat loop base_dict[base].append(base_cat[base]) base_dict[base].append(base_id[base]) base_dict[base].append(base_p[base]) base_dict[base].append(base_obt[base]) base_dict[base].append(base_asc[base]) This produces the following. instance = {0: ['Sales 2', '1', '10', 'True', 'True'], 1: ['Information 2', '2', '20', 'True', 'True'], 2: ['Listing 2', '3', '30', 'True', 'True'], 3: ['Information', '4', '40', 'True', 'True'], 4: ['Land', '5', '50', 'True', 'True'], 5: ['&', '6', '60', 'True', 'True'], 6: ['Tax', '7', '70', 'True', 'True'], 7: ['Construction', '9', '90', 'True', … -
With Django CKeditor, how to load different toolbars on different fields?
I'm using the django CKeditor plugin. My config is as follows: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', #'office2013' 'toolbar': 'Custom', #selects from below 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript'] ], 'toolbar_simple': { 'skin': 'moono', 'toolbar': 'Custom', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList'], ], }, 'toolbar_basic': { 'toolbar': 'Basic' }, 'toolbar_full': { 'toolbar': 'full', }, } How to load these different toolbars on different fields? I hope there's an option like: directions_car = RichTextField("Directions by car", max_length=1000, blank=False, default="", uses="toolbar_Custom") -
Need to add primary and foreign keys to a column postgresql 9.3.2 using phpPgAdmin
My apologies if this is a question with an obvious answer- but I am recovering from the lingering effects of a car accident, and still working to regain some of the things I used to know. I've got a django application that uses a PostgreSQL database indexed by Xapian, and while I was in recovery, one of the columns in an empty table somehow got dropped. When I returned to work, I found that running ./manage.py rebuild_index failed because it was expecting the missing column and couldn't find it. To make the repair a little easier (I hope) I installed phpPgAdmin. There's no problem connecting to the database, and I was able to add the missing column through the interface. After that, the Xapian index was able to rebuild with no errors, but the table is still not functioning correctly. I had hoped that the application would apply the primary and foreign keys once tested, but I am still seeing this in the phpPgAdmin interface: (Screen snip of the columns involved) As shown in the link, the key icons in the top column are not replicated in the bottom column. I'm fairly certain I can add them with ALTER TABLE, … -
Django IntegrityError with DateTimeField
i have field in object: view_time = ArrayField( models.DateTimeField(auto_now_add=True)) but i get error: django.db.utils.IntegrityError: null value in column "view_time"violates not-null constraint DETAIL: Failing row contains (18, 0, null, null, null). error rise when i try to create new object, and add value: recent_views = UserRecentViews.objects.create() recent_views.add_view(product.article) i use django 1.8.8 and Python 3.5.2 i reset database fiew times but it doesn`t help, db is Postgres. I think problem in object creation? but why django can not create object with current datetime? auto_now_add=True was added for this. My question is how add autogenerated datetime field with django? -
Django - int() argument must be a string or a number, not 'Patients'
for the context : I have 2 tables, user (which is a copy of the auth_user table, with small modifications) and patients I want to make a DetailView without passing the pk argument, so my user don't have access to his id The primary key of Patients is a the foreign key "patients" in User, so I can link these two tables My Patients model: class Patients(models.Model): id = models.IntegerField(primary_key=True) # And other keys not importants My views.py: class ProfilView(LoginRequiredMixin, generic.DetailView): login_url = '/membres/login/' #model = Patients template_name = 'membres/profil.html' def get_object(self): user_loggin = get_object_or_404(User, pk=self.request.user.id) return Patients.objects.get(pk=user_loggin.patients) I think I return something wrong, but after searching on internet a lot, I don't understand how i'm suppose to make this working, thanks for your help. -
DRF - using view classes for custom URL design?
I would like to realise the following URL design (based on githubs' REST api) for a User model in django rest framework: # get authenticated user (the currently logged in user): # # GET user/ # # update authenticated user: # # PATCH user/ # # get single user (will only return instructors) # # GET user/:username # # get all users (will only return instructors) # # GET users/ Given a User model I have the following standard serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = models.MyUser fields = '__all__' I can implement the url routes using function based views for each URL, but DRF offers many class-based views and routers and I was wondering if there was a more concise way of implementing it? -
Errors from back-end are not coming on front
I'm using django on server and angular 2 on front. When server response error I have an empty response. When I do this request through curl I have an error that server send me. P.S. I'm using CORS. Nginx config server { listen 80; server_name server_name location / { proxy_pass *in docker container* } location ~ /rest { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Methods' 'PROPFIND, PROPPATCH, COPY, MOVE, DELETE, MKCOL, LOCK, UNLOCK, PUT, GETLIB, VERSION-CONTROL, CHECKIN, CHECKOUT, UNCHECKOUT, REPORT, UPDATE, CANCELUPLOAD, HEAD, OPTIONS, GET, POST'; add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, X-XSRF-TOKEN'; add_header 'Access-Control-Allow-Credentials' 'true'; if ($request_method = 'OPTIONS') { return 200; } proxy_pass *in docker container* } } -
Different versioning scheme for Django REST Framework Browsable API
I have a requirement for an API that no default version is allowed. All clients are required to explicitly specify the version of any resource. I have achieved this with the following configuration: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.ext.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning', 'ALLOWED_VERSIONS': ['2.0'], 'DEFAULT_RENDERER_CLASSES': ( 'api.renderers.CustomJSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), } This works great, however I just lost the ability to use the browsable API renderer: HTTP 406 Not Acceptable Allow: GET Content-Type: application/vnd.acme+json Vary: Accept { "detail": "Invalid version in \"Accept\" header." } I would like to specify that if a request is done to the browsable API, the default version should be 2.0. The reasoning is that when experimenting with the browsable API, the default should be the latest version, however when consuming the API programmatically a user should not be exposed to breaking changes because they neglected to specify their version. How can I make my API require a version but allow the browsable API to be exempt? -
Django 1.10 migration support for apps in subdirectories
I put a simple project together with two apps in an apps directory: myproject/ | manage.py |-- myproject/ | | __init__.py | | settings.py | | urls.py | | wsgi.py |-- apps/ | | __init__.py | | app1/ # with models.py and views.py | | app2/ # with models.py and views.py I've updated the INSTALLED_APPS setting to include apps.app1 and apps.app2. The apps.app1 is the only app with models: class Thing(models.Model): stuff = models.CharField(max_length=255) If I run ./manage.py check and it comes back fine. However, if I try to run ./manage.py makemigrations apps.app1 I get the following error: App 'apps.app1' could not be found. Is it in INSTALLED_APPS? But apps.app1 is clearly in the settings file, here is the settings file (copy and pasted): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.app1', 'apps.app2', ] Other things I've read seem to indicate that is should be possible to have Django apps in subdirectories. Is this not actually possible? OR, if it is possible, what am I doing wrong? -
Updating Google Calendar using Django-Allauth
I'm using django-allauth to log users in and get a view of their calendars and I want to be able to add appointments. I'm using the following code which is more or less a cut and paste from quickstart.py: from __future__ import print_function import httplib2 import os from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage from oauth2client.client import OAuth2WebServerFlow from apiclient.discovery import build import datetime from django.shortcuts import render try: import argparse flags = tools.argparser.parse_args([]) except ImportError: flags = None # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/calendar-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/calendar' CLIENT_SECRET_FILE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/cal/client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials … -
Django Allauth: How to keep the session data after fb social login?
I write information in the session. After I login with facebook I am losing the data in the session. Is there a way to keep the data after login? -
Django get full url including an odd query string
I need to get a url from views.py of the structure: localhost:8000/path/name#stuff=2&otherstuff=3 Notice that instead of the usual '?' char to start the query string there is a '#'. In Django, I've tried: stuff = request.GET.get('stuff') This returns None, I'm guessing because of the url structure. I've also tried to get url info using: url = request.resolver_match.url_name and request.get_full_path() which returns only: /path/name/ Does anyone know of a way to get this full url in views? -
Unknown command 'refreshcodes'
I'm new in python and following the youtube videos to learn how to code. But now i got a problem. I tried to write custom django-admin command 'refreshcodes'. Here is my file located in src/shortener/managment/commands/refreshcodes.py: from django.core.management.base import BaseCommand, CommandError from shortener.models import KirrURL class Command(BaseCommand): help = 'Refreshes all KirrURL shortcodes' def handle(self, *args, **options): return KirrURL.objects.refresh_shortcodes() Here is shortener/models.py: import random import string from django.db import models from .utils import code_generator, create_shortcode # Create your models here. class KirrURLManager(models.Manager): def all(self, *args, **kwargs): qs_main = super(KirrURLManager, self).all(*args, **kwargs) qs = qs_main.filter(active=True) return qs def refresh_shortcodes(self): qs = KirrURL.objects.filter(id__gte=1) new_codes = 0 for q in qs: q.shortcode = create_shortcode(q) print (q.shortcode) q.save() new_codes += 1 return "New codes made: {i}".format(i=new_codes) class KirrURL(models.Model): url = models.CharField(max_length=220, ) shortcode = models.CharField(max_length=15, unique=True, blank=True) updated = models.DateTimeField(auto_now=True) #everytime model is saved timestamp = models.DateTimeField(auto_now_add=True) #when model was created active = models.BooleanField(default=True) #empty_datetime = models.DateTimeField(auto_now=False, auto_now_add=False) #shortcode = models.CharField(max_length=15, null=True) Empty in database is ok #shortcode = models.CharField(max_length=15, default='cfedefaultshortcode') objects = KirrURLManager() #some_random = KirrURLManager() def save(self, *args, **kwargs): if self.shortcode is None or self.shortcode == "": self.shortcode = create_shortcode(self) super(KirrURL, self).save(*args, **kwargs) #def my_save(self): # self.save() def __str__(self): return str(self.url) So, when … -
Could not import 'edit_contact'. The path must be fully qualified
So, I'm trying to create a table filled with contacts in Python/Django. When I attempt to run the program, I get the above error message ("ImportError: Could not import 'edit_contact'. The path must be fully qualified.") Here is the views.py I'm using: from contacts.models import Contact #, Address, Telephone from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404, render from django.template import Context, loader from django.forms.models import inlineformset_factory from django.template import loader, Context, RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required # Create your views here. def index(request): #return HttpResponse("Hey! You can see contacts here!") contact_list = Contact.objects.all().order_by('last_name') return render_to_response('contacts/index.html', {'contact_list': contact_list}, RequestContext(request)) def detail(request, contact_id): c = get_object_or_404(Contact, pk=contact_id); def new_contact(request): print "new_contact" #AddressInlineFormSet = inlineformset_factory(Contact, if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): contact = form.save() return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,))) else: form = ContactForm() return render_to_response("contacts/form.html",{ "form": form, }, RequestContext(request)) def edit_contact(request, contact_id): contact = Contact.objects.get(pk=contact_id) if request.method == "POST": form = ContactForm(request.POST, instane=contact) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,))) else: form = ContactForm(instance = contact) return render_to_response("contacts/form.html", { "form": form, }, RequestContext(request)) This is the urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<contact_id>\d+)/$', 'detail', name='contactdetailsurl'), url(r'^new/$', 'new_contact', … -
Django postgres full text search in reverse related models
How to add reverse related models to search vector? class Container(models.Model): text = models.TextField() class Item(models.Model): container = models.ForeignKey(Container) text = models.TextField() I want to search in both Item and Container models text fields and return QuerySet of Container models if related Item contains search pattern -
Adding a custom heading button inside tinymce for django admin
I have a HTMLField set up, which I can use django-tinymce to edit. I have the configuration set up inside my settings.py file, but what I can't figure out is how to add a custom button to the tinymce toolbar, which will wrap the text in h1 or h2 tag, depending on what is selected. Does anyone know how I would get this done? -
Django - How to combine 2 queryset and filter to get same element in both queryset?
I have a model: class LocationItem(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) stock_qty = models.IntegerField(null=True) Example: I have some data like this: ------------------------------ | ID | Item | Location | Qty | ------------------------------ | 1 | 1 | 1 | 10 | ------------------------------ | 2 | 2 | 1 | 5 | ------------------------------ | 3 | 1 | 2 | 2 | ------------------------------ | 4 | 3 | 1 | 4 | ------------------------------ | 4 | 3 | 2 | 20 | ------------------------------ I have 2 queryset to get items of each location: location_1 = LocationItem.objects.filter(location_id=1) location_2 = LocationItem.objects.filter(location_id=2) Now I want to combine 2 queryset above into 1 and filter only same items in both 2 location such as result of this example above is [1, 3] because item 1 and 3 belong to both location 1 and 2 -
Get summ of items by date django
everybody! I have some shop model with products in it, and I have a sales model, like this: sale_product_name = models.CharField() sale_product_price = models.IntegerField() sale_date = models.DateField() Now for the statistics i want to get summs of the sales by date (month to date) So it look like this: Lets say that today is 15 November 2016 01.11 - 500.00 $ | 02.11 - 150.00 $ | and so on... with template code like this {% for dayly_summ in dayly_summs %} {{ dayly_summ.date }} {{dayly_summ.summ)) {% endfor %} -
Django: Allow only logged in users to download files uploaded by them
Thanks to SO, could manage to progress. You may refer these 2 questions asked for the code to upload file and download files. Django: Adding files to a form gives multiple argument error Django: Downloading uploaded files Now the major issue I have is how to prevent file download by unauthorized users. Files uploaded have a download url and this url works even if user is not logged in. I tried it with private browser window and got downloaded. Is there any solution to prevent downloading of file in production and development mode and files should be downloadable by users who uploaded them?