Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Print entered values of form fields if form is not valid in django
This is my from, I want to display all values entered before submitting this form, if this form is not valid. When i submit this form validation works successfully, but it removes all values from form fields class PromoterRegistrationForm(forms.Form): email = forms.EmailField(required = True, max_length=50, widget=forms.EmailInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'required' : 'required', 'data-empty-message' : 'Please enter a email.', 'data-error-message' : 'Please enter a valid email.' })) password = forms.CharField(required = True, widget=forms.PasswordInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'required' : 'required', 'data-empty-message' : 'Please enter password.' })) firstname = forms.CharField(required = True, max_length=50, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'required' : 'required', 'data-empty-message':'Please enter first name.' })) lastname = forms.CharField(required = True, max_length=50, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'required' : 'required', 'data-empty-message':'Please enter last name.' })) -
Troubles to set up a simple task
I'm trying to set up a simple task (printing "foo" every 5 seconds) with django and celery. Assuming I have the following project : . βββ manage.py βββ proj βββ __init__.py βββ settings.py βββ tasks.py βββ urls.py βββ wsgi.py with tasks.py : from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') from django.conf import settings app = Celery('tasks', broker='django://127.0.0.1:8000//') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task def test(): print("FOO") And settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'celery', 'kombu.transport.django', ] [...] # Celery : CELERYBEAT_SCHEDULE = { 'test-celery': { 'task' : 'proj.tasks.test', 'schedule' : timedelta(seconds=5) }, } CELERY_TIMEZONE = 'Europe/Paris' and proj/__init__.py: from .tasks import app as celery_app I migrate, launch with celery -A proj.tasks worker --loglevel=info and celery is launched, I just have two warning with the pickle use with this version (3.1.23) and about settings.DEBUG being True. But celery seems working. I also launch my dev server with manage.py. So why isn't my task (test()) running? -
Mongoengine signals listens for all models
I have setup django project with mongoengine for using mongodb with django. I have created 2 models and they work fine, but when I use signal listener for one model It also listens for another model, so how can I keep the signals bound to their models? Here's my code for model User: from mongoengine import * from mongoengine import signals from datetime import datetime class User(Document): uid = StringField(max_length=60, required=True) platform = StringField(max_length=20, required=True) index = StringField(max_length=80) last_updated = DateTimeField(required=True, default=datetime.now()) meta = { 'collection': 'social_users' } def before_save(sender, document, **kwargs): if document.platform and document.uid: document.index = document.platform+'/'+document.uid signals.pre_save.connect(before_save) Here's another model Error from mongoengine import * from datetime import datetime class Error(Document): call = DictField(required=True) response = DictField(required=True) date = DateTimeField(default=datetime.now(), required=True) meta = { 'collection': 'errors' } Here's the file which I'm using to test the code: from src.social.models.app import Error from src.social.models.user import User error = Error.objects.first() print(error.to_json()) But it doesn't work, throws the following error: AttributeError: 'Error' object has no attribute 'platform' Please help me with this, thanks. -
tastypie saving foreignkey field throws exception
I'm trying to add the foreign key to my tastypie resources, but django throws out this error: "error_message": "'BB' object is not iterable", I've created a minimal working example: models.py class AA(models.Model): n = models.IntegerField() class BB(models.Model): aa = models.ForeignKey(AA, related_name='xox') t = models.CharField(max_length=2) resources.py from ..models import AA, BB from tastypie.authorization import Authorization from tastypie.fields import ForeignKey class AResource(ModelResource): class Meta: queryset = AA.objects.all() authorization = Authorization() class BBResource(ModelResource): aa = ForeignKey(AResource, 'aa', related_name="xox", full=False, blank=True, null=True) class Meta: queryset = BB.objects.all() authorization = Authorization() Now using curl to perform the post action: $ curl -XPOST --dump-header - --header 'Content-Type: application/json' localhost:8000/api/v1/a/ --data '{"n": 18}' $ curl -XPOST --dump-header - --header 'Content-Type: application/json' localhost:8000/api/v1/bb/ --data '{"t": "di", "aa": "/api/v1/a/1/"}' traceback: { "error_message": "'BB' object is not iterable", "traceback": "Traceback (most recent call last):\n\n File \"/home/mee/.venvs/env_pro/lib/python2.7/site-packages/tastypie/resources.py\", line 219, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/home/mee/.venvs/env_pro/lib/python2.7/site-packages/tastypie/resources.py\", line 450, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"/home/mee/.venvs/env_pro/lib/python2.7/site-packages/tastypie/resources.py\", line 482, in dispatch\n response = method(request, **kwargs)\n\n File \"/home/mee/.venvs/env_pro/lib/python2.7/site-packages/tastypie/resources.py\", line 1384, in post_list\n updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))\n\n File \"/home/mee/.venvs/env_pro/lib/python2.7/site-packages/tastypie/resources.py\", line 2175, in obj_create\n return self.save(bundle)\n\n File \"/home/mee/.venvs/env_pro/lib/python2.7/site-packages/tastypie/resources.py\", line 2322, in save\n self.save_related(bundle)\n\n File \"/home/mee/.venvs/env_pro/lib/python2.7/site-packages/tastypie/resources.py\", line 2382, in save_related\n setattr(related_obj, field_object.related_name, bundle.obj)\n\n File β¦ -
ipdb input lag when debugging phantomJS webdriver
so I was trying to debug the tests we have running django/phantomjs/selenium-webdrive with ipdb, but the interactive debugger input was too slow, I need to hold a key for 3-5 seconds to get that character written down. so I tracked it down and find out it was happening right after initiating phantomJS Code class IntegrationTest(StaticLiveServerTestCase): serialized_rollback = False @classmethod def setUpClass(cls): # this will be executed at the start of IntegrationTest super(IntegrationTest, cls).setUpClass() import ipdb; ipdb.set_trace() cls.driver = webdriver.PhantomJS("node_modules/phantomjs-prebuilt/bin/phantomjs") # input speed = normal cls.driver.set_window_size(1440, 900) # input speed = need to hold key 3-5 seconds cls.commonOp = commonOp(cls.driver, cls.live_server_url + settings.STATIC_URL + 'index.html') cls.customDriver = customDriver(cls.driver) @classmethod def tearDownClass(cls): # this will be executed at the end of IntegrationTest IPDB > /project/bx/integration_test/tests.py(20)setUpClass() 18 super(IntegrationTest, cls).setUpClass() 19 import ipdb; ipdb.set_trace() ---> 20 cls.driver = webdriver.PhantomJS("node_modules/phantomjs-prebuilt/bin/phantomjs") 21 cls.driver.set_window_size(1440, 900) 22 cls.commonOp = commonOp(cls.driver, cls.live_server_url + settings.STATIC_URL + 'index.html') ipdb> n <- INPUT SPEED = NORMAL > /project/bx/integration_test/tests.py(21)setUpClass() 19 import ipdb; ipdb.set_trace() 20 cls.driver = webdriver.PhantomJS("node_modules/phantomjs-prebuilt/bin/phantomjs") ---> 21 cls.driver.set_window_size(1440, 900) 22 cls.commonOp = commonOp(cls.driver, cls.live_server_url + settings.STATIC_URL + 'index.html') 23 cls.customDriver = customDriver(cls.driver) ipdb> <- INPUT SPEED = SLOW! (3-5 seconds hold on key) How can I fix this? Why is it β¦ -
Celery + Django + Rabbit stopping
I have this Django application that is configuring some servers via long running tasks (avg task 20 min). We usually have/need to process about 4-5 such tasks in parallel but I can't seem to get celery to play ball with that. I am adding tasks to the worker and I can sometimes see 4 or 5 running, other times just 2 and very rapidly (usually after 10 mins) the worker stops accepting/running anything. My question is more about how to achieve the max out of this celery setup and avoid such deadlocks or whatever they are as I can't seem to debug anything useful as to why it is performing that way. I have 8 CPUs on my machine and we're currently running celery on default celery -A main worker -l debug --pidfile=/tmp/celeryworker.pid which creates 8 processes by itself. Since I run it with docker-compose I tried using --concurrency=2 and scaling the workers to 4 but that just blocked it entirely. I also tried leaving it as is and scaling it to 4 or 5 without any performance gains and the usual time when nothing runs even though we are scheduling tasks. Here are my celery settings: BROKER_HEARTBEAT = '?heartbeat=30' β¦ -
Django, How does models.py under auth folder create initial tables when you migrate very first time?
If you migrate very first time after making new project in Django, you can find that Django creates tables like below. auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_user_permissions django_admin_log django_content_type django_migrations django_session Now I learned that those tables are created because lines under INSTALLED_APPS in settings.py. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] so I started to look into models.py under auth folder(in Django folder where I installed). I expected that there would be six classes in models.py. Because I learned that Class turn to table thanks to ORM(Ojbejct Relation Mapping). auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_user_permissions I could find class named 'Permission', a class named 'Group' and a class named 'User' in models.py under auth folder. I think those made tables 'auth_permission', 'auth_group' and 'auth_user'. Then what about other?(auth_group_permissions, auth_user_groups, auth_user_user_permissions) I would like to understand how those tables are created by Django(models.py in auth folder). Where should like look into in models.py to understand that? I expect that I can understand how other tables are created(django_admin_log, django_content_type, django_migrations, django_session) if I can understand that. I will appreciate if you can also explain how Django creates tables named 'django_migrations' and 'django_session' too. Thank you in advance. Have β¦ -
Using a registration form to add to custom user fields (django)
I'm creating custom user models for a registration form in django, but I'm having some problems getting the data into the database. Currently the users can register and their username, password, email, first name and last name are saved, but all the other form data isn't saving into the object. Below are my forms and the output: Models.py class user(models.Model): user = models.OneToOneField(User) password = models.CharField(max_length=15) password2 = models.CharField(max_length=20) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) gender = models.CharField(max_length=20) medication = models.CharField(max_length=50, blank=True) medical_history = models.CharField(max_length=50,blank=True) DOB = models.CharField(max_length=20) email = models.EmailField(max_length=30) telephone = models.CharField(max_length=20) address = models.CharField(max_length=30) city = models.CharField(max_length=20) state = models.CharField(max_length=20) postcode = models.CharField(max_length=30) forms.py: class CreateAccountForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) first_name = forms.CharField() last_name = forms.CharField() gender = forms.CharField() medication = forms.CharField() medical_history = forms.CharField() DOB = forms.CharField() email = forms.CharField() telephone = forms.CharField() address = forms.CharField() city = forms.CharField() state = forms.CharField() postcode = forms.CharField() class Meta: model = user fields = ("username",) views.py: def create_account(request): form = CreateAccountForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] password2 = form.cleaned_data['password2'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] gender = form.cleaned_data['gender'] medication = form.cleaned_data['medication'] medical_history = form.cleaned_data['medical_history'] DOB = form.cleaned_data['DOB'] email = form.cleaned_data['email'] β¦ -
Save multiple form objects with CreateView
I'm currently trying to use a CreateView to save multiple objects. I have already written a View that does this by inheriting from View. What it does is take the form data and creates the objects from a post list, but I wondered was if there is a better way of doing that using a CreateView, instead of writing a View from scratch? Or am I already doing it the best way? I know that the CreateView creates a single object but can I modify it to iterate through a list of objects and create them instead of creating a single object? -
TypeError at /post/ render_to_response() got an unexpected keyword argument 'context_instance'
I am trying to preview form before saving using 'formtools'. When I visit post it gives following errors: Request Method: GET Request URL: http://127.0.0.1:8000/post/ Django Version: 1.10.1 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pagedown', 'bootstrapform', 'contact', 'crispy_forms', 'formtools', 'member'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/formtools/preview.py" in __call__ 34. return method(request) File "/home/ohid/test_venv/lib/python3.5/site-packages/formtools/preview.py" in preview_get 58. context_instance=RequestContext(request)) Exception Type: TypeError at /post/ Exception Value: render_to_response() got an unexpected keyword argument 'context_instance' Here is my preview.py: from formtools.preview import FormPreview from django.http import HttpResponseRedirect from .models import Person class PersonFormPreview(FormPreview): form_template = 'member/person_form.html' preview_template = 'member/person_review.html' model = Person def done(self, request, cleaned_data): self.form.save() # Do something with the cleaned_data, then redirect # to a "success" page. return HttpResponseRedirect('/form/success') Here is my urls: from .preview import PersonFormPreview from .forms import MemberForm from django import forms url(r'^post/$', PersonFormPreview(MemberForm)), How do I fix this errors? -
all of a sudden django bootstrap pagination stopped working
I was just about to work on my site by running the server and when it did I got an error that says 'RequestContext' object has no attribute 'current_app' Exception Value: 'RequestContext' object has no attribute 'current_app' Exception Location: /Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/bootstrap_pagination/templatetags/bootstrap_pagination.py in render, line 206 This was working as early as today. i don't know what's going on. heres my traceback (practice) apples-MBP:src ray$ ./manage.py runserver Performing system checks... System check identified no issues (0 silenced). September 21, 2016 - 22:35:21 Django version 1.10.1, using settings 'gettingstarted.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ray/Desktop/myheroku/practice/src/blog/views.py", line 108, in post_list return render(request, template, context) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/template/loader.py", line 68, in render_to_string return template.render(context, request) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/template/base.py", line 208, in render return self._render(context) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File β¦ -
Django upload image to imagefield in model
I'm using django 1.10 and I'm trying to upload a profile image to a User model. But I met all kinds of errors, could someone give me a simple example for uploading a profile image using this User model? User model: class User(AbstractUser): profile_photo = models.ImageField(upload_to='/someplace/', blank=True) HTML: <form enctype="multipart/form-data" action="{% url 'somewhere' %}" method="post"> {% csrf_token %} Profile: <input type="file" name="profile" /> <input type="submit" name="submit" /> </form> Thanks in advance! -
How does Django make tables relating to user,auth,group,session and so on with very first migration?
I am little bit exciting to write my question in here. Normally I searched other questions to figure out my own problem. By the way, this time I couldn't figure out my question by searching it. That's why I am leaving question in here in person. My question is : How does Django framework make initial tables? if you make Django project and then migrate. it makes tables like below. even thought you didn't make any apps in project or didn't write any code in models.py of each app. auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_user_permissions django_admin_log django_content_type django_migrations django_session I understood what ORM, MTV, migrations are. I hope I can understand Django framework more deeply and want to figure what hidden code(or Django structure) in Django made those initial tables. Thank you in advance. if my explanation for my question was not clear, please leave me comment. Have a nice day! -
Django REST Framework: duplicate queries due to model __str__ method
I'm working on a webapp with a Django backend that provides a Django REST Framework API for the frontend to consume. I've recently run into some performacne issues, so I've started investigating the performance of each of my endpoints- and most of them are issuing far too many queries to the database. I've got several prefetch-related issues that I can't figure out, but this is (I think) the simplest. I've implemented select_related and prefetch_related where I can, thanks to the docs as well as this excellent post on how to think about eager loading. For one particular model, I've reduced the number of queries decently, but I can't figure out why I still have certain duplicates. Here's the model: class ReadingGroup(models.model): owner = models.ForeignKeyField(settings.AUTH_USER_MODEL) users = models.ManyToManyField(settings.AUTH_USER_MODEL) .... <other group related fields> def __str__(self): return '%s group: %s' % (self.name, self.book_types) And the serializer: class ReadingGroupSerializer(serializers.ModelSerializer): users = UserSerializer(many = True,read_only=True) owner = UserSerializer(read_only=True) class Meta: model = League fields = ('url', 'id','owner', 'users') @staticmethod def setup_eager_loading(queryset): #select_related for 'to-one' relationships queryset = queryset.select_related('owner') #prefetch_related for 'to-many' relationships queryset = queryset.prefetch_related('users') return queryset The setup_eager_loading() method reduced the number of queries to retrieve all 12 ReadingGroup instances in my database β¦ -
Convert data on AlterField django migration
I have a production database and need to keep safe the data. I want to change a Field in model and convert all data inside that database with this change. Old field class MyModel(models.Model): field_name = models.TimeField() Changed field class MyModel(models.Model): field_name = models.PositiveIntegerField() Basically I want to convert the TimeField value (that has a Time object) in minutes. Example: I have in an object time(hour=2, minute=0, second=0) and I want to convert that field value in all database table to 120 when I apply the migrate. -
Django-import-export with Django admin, how to add new file format
I'm using Django-Admin to import/export data with Django-import-export package, every thing is OK with Json, csv... but I realy can't find how to import ".dbf" files via Django admin app. Can someone help me! Thinks -
is DjangoRestFrameWork really needed for a website
Does it worth it using DRF+Ajax+bootstrap to build a website where no app is needed? or it's better to stick to the normal django template language without even Ajax.What is the best way to proceed with this? I want to avoid using angular since I dont want things to get complicated. I want to create a website where a user or an admin logs in and access a different set of views and performs different actions. Sorry for my primitive question, I m newbie in web development and to Django. -
How to use MongoDB with Django Framework and Python3
I've setup Django project with the following: Django==1.10.1 django-mongodb-engine==0.6.0 djangotoolbox==1.8.0 mongoengine==0.9.0 pymongo==3.3.0 but when I tried to syncdb using python3 manage.py syncdb, then it's showing ~/virtenv/lib/python3.5/site-packages/django_mongodb_engine/base.py", line 272 raise ImproperlyConfigured, exc_info[1], exc_info[2] ^ SyntaxError: invalid syntax -
Heroku local works fine but Server Error (500) with heroku open
I have now followed the Heroku instructions as well as another deploy tutorial. I am able to get the app running locally when I run heroku local and the site looks fine. I then go for heroku open and I get a System Error (500) My question is: a) how do I read these logs to determine the error, and b) what is some other troubleshooting when the local app runs fine but I get a server error when trying to open through the Heroku app? Thanks for any help. Here is the tail from heroku logs 2016-09-21T22:14:22.183850+00:00 heroku[web.1]: Starting process with command `gunicorn aptly.wsgi` 2016-09-21T22:14:25.965426+00:00 app[web.1]: [2016-09-21 22:14:25 +0000] [3] [INFO] Starting gunicorn 19.6.0 2016-09-21T22:14:26.018518+00:00 app[web.1]: [2016-09-21 22:14:26 +0000] [3] [INFO] Listening at: http://0.0.0.0:6663 (3) 2016-09-21T22:14:26.018676+00:00 app[web.1]: [2016-09-21 22:14:26 +0000] [3] [INFO] Using worker: sync 2016-09-21T22:14:26.023706+00:00 app[web.1]: [2016-09-21 22:14:26 +0000] [7] [INFO] Booting worker with pid: 7 2016-09-21T22:14:26.092715+00:00 app[web.1]: [2016-09-21 22:14:26 +0000] [8] [INFO] Booting worker with pid: 8 2016-09-21T22:14:26.764197+00:00 heroku[web.1]: State changed from starting to up 2016-09-21T22:15:02.410363+00:00 heroku[router]: at=info method=GET path="/" host=desolate-cove-94597.herokuapp.com request_id=53f43d4a-5b5c-477b-a355-39bf5156f8b3 fwd="73.163.191.79" dyno=web.1 connect=1ms service=223ms status=500 bytes=239 2016-09-21T22:15:28.285891+00:00 heroku[api]: Starting process with command `python manage.py migrate` by me@gmail.com 2016-09-21T22:15:41.534684+00:00 heroku[run.7412]: Awaiting client 2016-09-21T22:15:41.555107+00:00 heroku[run.7412]: Starting process β¦ -
Inline edit of django ForeignKey and proxy models
I get an 404 error when I try to edit inline (in a popup) an object referenced by a ForeignKey to a proxy model in the admin part (using django suite) of my application. My base model and the proxy model: class Book(MyBase): """ Base book model """ # [...] class SpecialBook(Book): """ Need to leave this separated as a proxy model. """ class Meta: proxy = True My model to bind books with it's genre. The book field can hold references to both Book and SpecialBook, via documentation: [proxy] class operates on the same database table as it's parent class BookGenre(MyBase): """ bind books with it's genre """ book = models.ForeignKey(Book) genre = models.ForeignKey(Genre) The admin.py stuff to manage the genres: class BookGenreInline(suit.admin.SortableTabularInline): model = BookGenre # [...] @admin.register(Genre) class GenreAdmin(Foo): inlines = [ BookGenreInline, # [...], ] fields = [...] The above generates me an admin page with a select field with the existing Book (and SpecialBook) objects. On the right to the select I've got the "Change selected" and "Add another" buttons (template imported from here I believe). The only problem is that the edit option works only when a Book object is selected, doesn't work for β¦ -
django: Had NoReverseMatch using django-autocompelet-light
So I am trying to use autocomplete-light 3.1.8 and following this tutorial. Now I have a model called "Equipment" with a many-to-many field "used_for_tests". Following the tutorial, I set the following code up but had this no reverse match error. in models.py: class Meta: model = Equipment fields = ['asset_number', 'used_for_test'] widgets = {'used_for_test': autocomplete.ModelSelect2Multiple(url='tests') } urls.py: url( r'^tests-autocomplete/$', TestsAutocomplete.as_view(), name='tests', ), views.py: class TestsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Tests.objects.none() qs = Tests.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs But as showed here, in models it points to "tests" and that's right the name I gave in urls. Why there is a no reverse match problem? Also, the "Using autocompletes outside the admin" part in the tutorial is confusing. {% block footer %} <script type="text/javascript" src="/static/collected/admin/js/vendor/jquery/jquery.js"></script> {{ form.media }} what are those for? Thanks guys -
django-allauth custom user model
I coding with django-allauth and I have a problem.When twitter logining, I do not want savining Django User model and Social Accounts.Even, I want to removed SocialAccounts model completely.I want to saving own model. My models.py class Developer(models.Model): username = models.CharField(max_length=120) email = models.EmailField(max_length=110) developer_name = models.CharField(max_length=120) phone_number = models.CharField(max_length=22) password = models.CharField(max_length=110) My settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = '/profile/' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = None ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False -
How to avoid having idle connection timeout while uploading large file?
Consider our current architecture: +---------------+ | Clients | | (API) | +-------+-------+ β§ β¨ +-------+-------+ +-----------------------+ | Load Balancer | | Nginx | | (AWS - ELB) +<-->+ (Service Routing) | +---------------+ +-----------------------+ β§ β¨ +-----------------------+ | Nginx | | (Backend layer) | +-----------+-----------+ β§ β¨ ----------------- +-----------+-----------+ File Storage | Gunicorn | (AWS - S3) <-->+ (Django) | ----------------- +-----------------------+ When a client, mobile or web, try to upload large files (more than a GB) on our servers then often face idle connection timeouts. Either from their client library, on iOS for example, or from our load balancer. When the file is actually being uploaded by the client, no timeouts occurs because the connection isn't "idle", bytes are being transferred. But I think when the file has been transferred into the Nginx backend layer and Django starts uploading the file to S3, the connection between the client and our server becomes idle until the upload is completed. Is there a way to prevent this from happening and on which layer should I tackle this issue ? -
Type error: descriptor 'tell' of '_io.StringIO' object needs an argument
I am using xlsxwriter to export models to an Excel file from Django admin. I'm following the tutorial provided here on how to format the Excel spreadsheet, which calls for using StringIO. For the data I am just using the examples given in the xlsxwriter documentation, for now, before I sub in my own data. Before, I was able to get the Export button that I added to admin to work - a file would be exported and it would just contain "None" in one cell. Now I am getting the following error when I click the Export button: TypeError at /export/ descriptor 'tell' of '_io.StringIO' object needs an argument Why am I getting this error and how do I fix it? Here is the function I wrote for the formatting, in excel_utils.py: from io import StringIO import xlsxwriter def write_to_excel(): output = StringIO workbook = xlsxwriter.Workbook(output) worksheet_s = workbook.add_worksheet("Summary") title = workbook.add_format({ 'bold': True, 'font_size': 14, 'align': 'center', 'valign': 'vcenter' }) header = workbook.add_format({ 'bg_color': '#F7F7F7', 'color': 'black', 'align': 'center', 'valign': 'top', 'border': 1 }) expenses = ( ['Rent', 1000], ['Gas', 100], ['Food', 300], ['Gym', 50], ) row = 0 col = 0 for item, cost in expenses: worksheet_s.write(row, β¦ -
django: single modelform for a foreign key object
Sorry if the title is not clear enough. Basically, I have two model, equipment and calibration, of which calibration is a foreign key of equipment. In the detail view of each piece of equipment, I have a table listing all the calibrations associated to this equipment and the details of calibration data. When user click on the calibration date, which is a link to calibration change view, there supposed to be a modelform of this particular calibration. However, now when I do this, it gives me a complete form containing all the calibrations. However I just only want modelform for the particular calibration that I clicked. How should I do this? My code: models.py: class Calibration(models.Model): cal_asset = models.ForeignKey(Equipment, on_delete = models.CASCADE) cal_by = models.CharField(max_length = 200, null=True) cal_17025_check = models.CharField(max_length = 20, choices = CHECK_CHOICES, null=True) cal_date = models.DateField(null=True) mesure_uncertainty_included = models.BooleanField(default=False) a2la_Cal = models.BooleanField(default=False) qc_test_by = models.CharField(max_length = 200, null=True, blank = True) qc_test_date = models.DateField(null=True , blank = True) location = models.CharField(max_length = 20, choices = LOCATION_CHOCIES, null=True) cal_cert_location = models.FileField(upload_to = 'cal_cert/', null=True, blank = True) notes = models.CharField(max_length = 200, null=True) forms.py: class CalibrationForm(ModelForm): helper = FormHelper() helper.form_tag = False helper.layout = Layout( Div( Div( β¦