Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing an Object in Database from Django Form
How can you edit an existing object in a database from a form? I use this for example: obj_ex = Model(column = value, column2 = value2) obj_ex.save() However this doesn't update my object in the database. I have tried to access the pk of the entry and save the values of the entry with the pk of x but I still can't update the table. Is there a way to use an .update() type to update objects? Or is there another way to update a table? Thank you. -
Implementing production settings in Django
I'm having trouble understanding the switchover from local to production settings for deploying Django projects. I'm using an Ubuntu virtual machine (VM) if it matters. I understand how to configure my settings. I understand best practices for creating settings files (base.py, local.py, production.py, blah, blah). I know that in local development DEBUG=True, in production DEBUG=False, blah, blah. But how do I implement this switchover? Do I get rid of the local.py? Do I create some kind of logic so that my VM only reads base.py and production.py? What's the best approach? -
Accessing templatetags globally for django project
I tried to add the path under INSTALLED_APPS and to create a folder of template tags and reuse them in multiple apps. But it is not working. Is there a smart way to work it out? All I need is to place templatetags for whole project in single directory accessible globally. -
How can I split a Django model into multiple models that inherit from the first
I have a Django model used extensively in my app. I'd like to create another model that inherits from that one so I can continue using the original model throughout the code, but move a field to the new model I have: class MyModel(models.Model): field1 =... field2=... field3=... I want to move field3 to a new model: class MyModel2(MyModel): field3=... Then I'd like MyModel instances where field3 is not null to become MyModel2 instances. The code would continue to refer to MyModel, but in some special cases, I'd use MyModel2 instead. Is this possible? Advisable? Is there a better way? I considered making a base abstract model that both could inherit from, but then you can't use the abstract model in forms and things. -
Filtering by value in list
Is there any Django filter to do "the opposite" __in does? I have an Entity with a related_entity_set, and I want to check if any of these related entities match with a given related_entity. I can do the following to achieve this behavior: Entity.objects.filter(related_entities__in=[related_entity]) But it does not look proper. There must be a more straightforward way I am missing right now. -
Disable UI Button if cookie/login has expired
I have a view on my Django website which has a Bootstrap button that performs an important operation, operation which requires the user to be logged in. However, on our site the cookies have a lifetime of 15 minutes, meaning that a user which is logged in, goes for a cup of tea, and then comes back and clicks the button will think that the operation has gone through, when in fact he/she will be logged out. Is there any way to check via JQuery or otherwise if the cookies have expired, and disable the button if this is the case? Thanks, Alberto -
django migration hell, dropped a table. Tried to get it back
So I dropped a table in my database, and I want it back. Rerunning a migration gave errors table didn't exist. After some hunting I learned I could remove everything in my django_migrations that had app name my app. So i did that, reran migrations it started to work then griped about tables that were not dropped. I have no idea how to just get the one table back again and keep everything as it was... anyway to do this? I don't care about 90% of the data in the database, only a few tables and fields. The table i dropped i cared nothing about the data. -
Django custom manager filter query set (by parameter)
I would like my models to automatically filter by current user. I did this by defining: class UserFilterManager(models.Manager): def get_queryset(self): return super(UserFilterManager, self).get_queryset().filter( owner=get_current_user() ) where get_current_user() is a middleware which extracts the current user from the request passed to Django. However, I need to use the models from Celery which does not go through the middleware. In these cases MyModel.objects.all() needs to become MyModel.objects.filter(user=<some user>) To avoid wrong queries caused by forgetting to filter by user, I would like the model/manager/queryset to assert when a query (any query) is performed without a filter on user. Is there a way to achieve this? From what I see get_queryset() cannot receive parameters and models.QuerySet won't provide aid here. -
Django (custom)form unicode object has no attrbute 'get'
I have seen several posts about the "AttributeError: 'unicode' object has no attribute 'get'" error but nothing fixed my problem. I am trying to use a formiew to redirect to my download page. i override the form_valid function from the formview to redirect to my /download url def form_valid(self, form): clean_form = form.cleaned_data print clean_form.get('starttime') return reverse('accesslogs_download', kwargs={'domain': self.get_object().domainname}) + "?a=b&b=c" this should redirect to : "/download?a=b&b=c " but i get redirected to my formView with the following error: AttributeError: 'unicode' object has no attribute 'get' My full Traceback is: Internal Server Error: /serverlogs/business.sla.nl/accesslogs/realtime/view Traceback (most recent call last): File "/home/jasperf/.virtualenvs/servicepanel/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response response = middleware_method(request, response) File "/home/jasperf/.virtualenvs/servicepanel/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'unicode' object has no attribute 'get' How can i fix this and get redirected to /download?a=b&b=c Note: i don't plan to use the variable a or b, but when u can get to that url i can put my own variable there. -
Jinja2 throwing templatedoesnotexist error in Django project
I'm trying to use jinja2 in my Django project (ver 1.10). After setting it up, once I try to run the project, I get TemplateDoesNotExist at /base/index.html and Template-loader postmortem Django tried loading these templates, in this order: Using engine jinja2: This engine did not provide a list of tried templates. In templates folder, I have a base directory where index.html is placed. Moreover, if I use Django's template engine, this same folder structure works perfectly. How can I fix this issue? My config is as follows: In settings.py (note that I've deliberately excluded the Django template fallback): TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': {'environment': 'uberfordoc.jinja2.environment', }, }, ] I also have a file called jinja2.py kept in the project folder: from __future__ import absolute_import from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env -
Django App incorporated with Multiprocessing using Gevent library facing race condition or may be some thing else
I use a global dictionary variable as a cache to keep track of tokens issued for a user on day to day basis. The tokens are getting duplicated. Code logic is given below. I use Django 1.8 with Nginx server spawning multiple Gunicorn threads using Gevent library --------------config.py---------------- global DOCTOR_TOKEN_CACHE DOCTOR_TOKEN_CACHE = {} --------------------------------------- if consultant_code in config.DOCTOR_TOKEN_CACHE: config.DOCTOR_TOKEN_CACHE[consultant_code] += 1 else: last_encounter = models.Encounter.objects.filter( consultation_date=encounter.consultation_date ).exclude(token_no=None).order_by('token_no').last() if last_encounter: tkn = (last_encounter.token_no+1) if last_encounter.token_no else 1 else: tkn = 1 config.DOCTOR_TOKEN_CACHE[consultant_code] = tkn Here even if the cache gets empty there is logic to set the cache back but in spite of all this the tokens are getting duplicated which I'am not able to figure out. Kindly help me out -
Django: Testing Formview can't submit form
I'm just doing a quick test of a CBV Formview. However for some reason the form won't submit and I've gone blind from looking at it to find out why. There is no error shown, when I click on submit nothing happens and it doesn't redirect to the success url or print out the test message. Form: class EmailTestForm(forms.Form): email = forms.EmailField() View: class EmailTestFormView(FormView): form_class = EmailTestForm template_name = "site/test_email.html" success_url = "/signup" def form_valid(self, form): print('form is good') Template: {% extends "site/signup.html" %} {% load crispy_forms_tags %} {% block inner %} <form action="" method="post" >{% csrf_token %} {% crispy form %} <input id="submit" class="btn btn-block btn-cta-primary" type="submit"/> </form> {% endblock inner %} -
Django uploading model data using excel
I am implementing data import for my application via excel. I am planning on using django-excel. Now, I am having a field (student ID) which is generated on save call. The last 3 digits of the ID is created by adding one to the previous student name. The other digits denote other things. My question is how can this be done in bulk uploading of data/ in using django-excel. Following is the student model (leaving out most of the fields): class Student(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) dob=models.DateField("Date of Birth", blank=True, null=True) key=models.CharField(db_index=True,max_length=12) gender=models.CharField(max_length=1,choices=gender_list) blood_group=models.CharField('Blood Group', max_length=3,choices=blood_list, blank=True, null=True) slug=models.SlugField(max_length=32) Key and slug would be dynamically created using the save module. -
How to implement edit in Django using ajax?
I have a table with Payments <table class="table" id="payments"> <thead> <tr> <th>Date</th> <th>Description</th> <th>Comment</th> <th>Amount</th> <th>Show</th> <th>Edit</th> <th>Destroy</th> </tr> </thead> <tbody> {% for payment in payments %} <tr> <td>{{ payment.created_date|date:'Y-m-d H:i' }}</td> <td>{{ payment.description }}</td> <td>{{ payment.comment }}</td> <td>{{ payment.amount }}</td> <td><a id="{{ payment.pk }}" class="show_payment">Show</a></td> <td><a id="{{ payment.pk }}" class="edit_payment">Edit</a></td> <td><a id="{{ payment.pk }}" class="destroy_payment">Destroy</a></td> </tr> {% endfor %} </tbody> </table> Each link to show have an id of this payment. When I click to this link my form appears with pre-filled data of the appropriate payment but when I click Submit it creates a new payment. $(".edit_payment").click(function () { var payment_id = $(this).attr('id'); $.ajax({ url: '/payment/'+payment_id+'/edit/', type: 'get', success: function (data) { $('#hide_payment').show(); $("#payments").after(data); $('#hide_payment').click(function(){ $("#payment_form").remove(); $('#hide_payment').hide(); }); } }); }); $(document).ready(function(){ $('#payment_form').hide(); $('#hide_payment').hide(); //$("#submit_payment").click(function() { var form = $("#payment_form"); var options = { success: function(data){ // var new_element = $(data).find('tr:last'); // $("#payments").append(new_element); $('#payment_form').hide(); }, clearForm: true }; $('#payment_form').on('submit', function() { $(this).ajaxSubmit(options); return false; }); }); But I want to edit this payment not to create new. def payment_edit(request, pk): if request.user.is_authenticated(): if request.user.has_perm('tracker.admin') or request.user.has_perm('tracker.manager'): payment = get_object_or_404(Payment, pk=pk) if request.method == "POST": form = PaymentForm(request.POST, instance=payment) if form.is_valid(): payment = form.save(commit=False) payment.save() return redirect('payment_list') else: form … -
Django : ImportError ; No module named urls
I'm a complete beginner in Django and I try without success to create my first django web page with just 'Hello world' on it. I've been trying for a few hours to solve my problem by looking on the internet but none of the solutions worked for me. Here is my code : I hope I can get help here... Here is my directory tree : ./ProjetArbre: AppliPageArbre arbre.db init.py manage.py ProjetArbre ./ProjetArbre/AppliPageArbre: admin.py init.py models.py tests.py views.py admin.pyc init.pyc models.pyc urls.py ./ProjetArbre/ProjetArbre: init.py settings.py urls.py wsgi.py init.pyc settings.pyc urls.pyc wsgi.pyc Here is ProjetArbre/AppliPageArbre/urls.py : from django.conf.urls.defaults import patterns,url from views import home urlpatterns=patterns('', url(r'^home/$',home,name="home") ) ProjetArbre/AppliPageArbre/views.py : from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request) : #return HttpResponse("HelloWorld") print 'HelloWorld' ProjetArbre/urls.py : from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'ProjetArbre.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^AppliPageArbre/', include('ProjetArbre.AppliPageArbre.urls')), ) And finally ProjetArbre/ProjetArbre/settings.py : """ Django settings for ProjetArbre project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os … -
Django REST :: AssertionError: Invalid image format
I have View like this: class LogoView(APIView): permission_classes = [UserWriteSafeReadPermission] def get_object(self): return Config.objects.get(domain=self.request.domain) ... def put(self, request, pk=None, format=None, **kwargs): config = self.get_object() try: image = request.FILES['image'] config.set_logo(image) return Response(status=status.HTTP_201_CREATED) except KeyError: return Response(status=status.HTTP_400_BAD_REQUEST, data={'detail': 'Expected image.'}) A model: def set_logo(self, image_data): .... try: image = Image.open(image_data) # <-- fails And a unittest: def test_foo(self): self.authenticate(USER_PERMISSION_WRITE) from PIL import Image import tempfile image = Image.new('RGB', (100, 100)) tmp_file = tempfile.NamedTemporaryFile(suffix='.png') image.save(tmp_file) response = self.client.put(self.api_reverse('my_url'), {'image': tmp_file}, format='multipart') And getting: AssertionError: Invalid image format -
Django Indentical URL Pattern in two Separate Apps Conflict
(Django v 1.10.4) I'm trying to use two separate apps who's url prefix is the root of the site (I'm migrating to django from another site and need to maintain the existing url structure). The two apps/models in question are "artistbio/Bio" and "pages/BasicPage". Currently I have the url patterns in the main url config (originally they were in their own respective url.py files but the issue I have is the same either way): from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from artistbio.views import BioDetail from pages.views import PageDetail urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^(?P<slug>[\w\-]+)/', PageDetail.as_view()), url(r'^(?P<slug>[-\w]+)/', BioDetail.as_view(), name='bio-detail'), Everything I've read (and all my experience thus far) has shown that Django will try to match the request against each URL pattern before giving either a "did not match any url patterns" error or a "404 not found" error if the requested object truly doesn't exist. But now when both patterns are together as listed above, when I request a Bio object via BioDetail it tries to match against the URL pattern for PageDetail and gives me a 404 error (which makes sense) but it also seems to mean that Django never moves on to … -
Load images and text data from django database instead of static template
Instead of loading images from static page html/css, if I load them from django databae, is there any chances of slowing down the loading speed of pages. -
How to communicate with routers using python
I am trying to do a SAAS project which helps users in configuring their routers.I am building this project with angular and django. For the angular ui part am using JUCI as a reference. JUCI uses OpenWrt in communicating with the routers.JUCI gets the live information from the routers.In my project am using netjsonconfig which also makes use of OpenWrt.The problem with netjsonconfig is that it doesn't take live information out of the routers. So my question is that is there any python libraries which can help me in taking the information out of the router which makes use of openwrt? -
QuerySet order_by intermediate models
I'm trying to create a intermediate model with the created field recording the time of following relationship. The models is as following: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile') realname = models.CharField(max_length=20, verbose_name='真實姓名', blank=True) nickname = models.CharField(max_length=20, verbose_name='暱稱/顯示名稱') ## the intermediate model is connected through following field ## followings = models.ManyToManyField('self', through='FollowShip', related_name='followers', symmetrical=False, through_fields=('profile_from', 'profile_to')) total_followers = models.IntegerField(default=0) def __str__(self): return 'Profile of User:{}'.format(self.user.username) class FollowShip(models.Model): profile_from = models.ForeignKey(Profile, related_name='follow_from_set') profile_to = models.ForeignKey(Profile, related_name='follow_to_set') created = models.DateField(auto_now_add=True, db_index=True) def __str__(self): return "{} follows {}".format(self.profile_from, self.profile_to) class Meta: unique_together = ('profile_from', 'profile_to') It works fine. However, when I tried to access the QuerySet order by created field of FollowShip model. The error occurs. In manage.py shell: >>> user.profile.followings.order_by('followship__created') Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 232, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__ self._fetch_all() File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql() File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 824, in execute_sql sql, params = self.as_sql() File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 369, in as_sql extra_select, order_by, group_by = self.pre_sql_setup() File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 47, in pre_sql_setup order_by = self.get_order_by() File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 293, in get_order_by … -
Access callable from Celery task instance
Is there a way to access the callable object from a Celery task, either directly or through a lookup method (like Django's get_model() method). I've scoured through the public and private methods but none of them seem obviously what I'm looking for: $ dir(celery_task_instance) > ['AsyncResult', 'MaxRetriesExceededError', 'OperationalError', 'Strategy', '__bound__', '__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__header__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__trace__', '__v2_compat__', '__weakref__', '__wrapped__', '_app', '_backend', '_decorated', '_default_request', '_exec_options', '_get_app', '_get_exec_options', '_get_request', 'abstract', 'acks_late', 'add_around', 'add_to_chord', 'add_trail', 'after_return', 'annotate', 'app', 'apply', 'apply_async', 'autoregister', 'backend', 'bind', 'chunks', 'default_retry_delay', 'delay', 'expires', 'from_config', 'ignore_result', 'map', 'max_retries', 'name', 'on_bound', 'on_failure', 'on_retry', 'on_success', 'pop_request', 'push_request', 'rate_limit', 'reject_on_worker_lost', 'replace', 'request', 'request_stack', 'resultrepr_maxsize', 'retry', 'run', 's', 'send_event', 'send_events', 'serializer', 'shadow_name', 'si', 'signature', 'signature_from_request', 'soft_time_limit', 'starmap', 'start_strategy', 'store_errors_even_if_ignored', 'subtask', 'subtask_from_request', 'throws', 'time_limit', 'track_started', 'trail', 'update_state'] Background I'm using django-celery-beat to create scheduled tasks for Celery within a Django project. I'd like to validate the schema of the args and kwargs fields at the time of creating the scheduled task, to anticipate and prevent future runtime issues. For example, API paramaters defined supplied via the kwargs field. I can access … -
Django: How to access information from connected Model Class
I have 3 Classes: Post Author PostAuthor In PostAuthor it's defined as: post = models.OneToOneField(Post,default=None) author = models.ForeignKey(Author, default=None) I am iterating all Posts and Wanted to update field of PostAuthor by doing this: for post in models.Post.objects.filter(active=True): result = PostAuthor.objects.filter(author=author) print(result.author.email) #gives 'unknown' error. I eventually want to update this field -
Save model with generic relation as new in Django Admin fails
I have a model that contains a generic relation _tags = GenericRelation(Tag) In the Admin the "save as new" button is activated. But when the model has actual tags attached it throws an exception: IntegrityError at /admin/rankings/rankingschema/2084/ (1048, "Column 'content_type_id' cannot be null") As far as I can see, this is a bug in Django Admin's copy functionality. Would you agree? What is the best way around it? I am using Django 1.8.7. -
Multiple chrome processes after chromedriver.quit()
I am running a Django service that fires up a chromedriver for selenium and scrapes a website for data. The Django service is called by another Java service through HTTP. Here is the code: views.py path_to_chromedriver = '/path/to/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) try: response = get_data(browser) except Exception as e: print str(e) finally: browser.close() browser.quit() scraper.py get_data(browser) try: . . . for i in range(1,6): try: . . . return "success data" except NoSuchElementException: browser.back() raise Exception("No results found") except Exception as e: print str(e) raise The problem is that after the java service has finished making all the calls and the whole process is complete, there are between 25 - 50 chrome processes orphaned in RAM occupying over 1 GB. Is there anything wrong I'm doing here? -
Django: Serializing a list of multiple, chained models
Given two different models, with the same parent base class. Is there any way, using either Django Rest Framework Serializers or serpy, to serialize a chained list containing instances of both the child models? Given some example models: class BaseModel(models.Model): created_at = models.DateField() class Meta: abstract = True class ChildModel1(BaseModel): field_one = models.TextField() class ChildModel2(BaseModel): field_two = models.TextField() And an example view: def get(self, request): q1 = ChildModel1.objects.all() q2 = ChildModel2.objects.all() chained_list = sorted( chain(q1, q2), key=attrgetter('created_at')) serializer = BaseModelSerializer(chained_list, many=True) The method for chaining the models is taken from the answer to this question. With my current attempts I get a quite obvious error saying something like: AttributeError: 'ChildModel1' object has no attribute 'field_two' I know it is not the best practice to mix two models with some different fields, but in my case I thought it necessary.