Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku : django app is showing operational error: no such table
My app is running proper locally but when I deployed it to heroku it's showing error Operational Error :- no such table: sni_addthing I ran makemigrations locally and pushed to heroku. I migrated remotely as well. -
Generated .po file has msgstr "" after makemessages
I am using Django localization API for offering multilingual feature to my website. But after generating .po file all msgstr are blank. I did not get any translated strings. Following is the setting.py configuration MIDDLEWARE_CLASSES = ( 'framework.botdetection_middleware.AvoidBotsMiddleware', 'framework.cl_redirect.MainSiteRedirect', 'framework.ssl_redirect.SSLRedirect', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'framework.wlabel_middleware.CustomDomainMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'social.apps.django_app.middleware.SocialAuthExceptionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', ) # Implementation of Localiztion # Path to locale folder LOCALE_PATHS = ( os.path.join(APP_DIR, 'locale').replace('\\', '/'), ) # The language your website is starting in LANGUAGE_CODE = 'en' # The languages you are supporting ugettext = lambda s: s LANGUAGES = ( ('en', ugettext('English')), ('fr', ugettext('French')), ('pl', ugettext('Polish')), ) # Use internationalization USE_I18N = True # Use localization USE_L10N = True I use the following command for creating .po file. django-admin makemessages --locale=fr --extension=html --ignore=env --ignore=*.py And following is the output i got msgid "Change Payment Method" msgstr "" msgid "Return to Purchase Details" msgstr Am i missing something. Also how can i load translated version of my website without using url.py -
How to have multiple ajax requests in Django view?
My current is_ajax() looks like this in my view: if request.is_ajax(): if comment.is_valid(): comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id) comment.save() score = CommentScore.objects.create(comment=comment) score.save() username = str(request.user) return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username}) else: print(comment.errors) which allows me to post ajax comments. However I need to implement another ajax (ajax GET) request: username_clicked = request.GET.get('username_clicked') profile = Profile.objects.get(username=username_clicked) if username_clicked: print(profile.age) The above code only works when I put it inside the is_ajax() function, but if I do that then the ajax comment does not work anymore. Is there anything I can do to make both work? Here are the ajax functions: // ajax GET request $('a.username').on('click', function() { var username = $(this).html(); var url = window.location.href.split('?')[0]; $.ajax({ type: 'GET', url: url, data: { username_clicked: username, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() }, success: function (data) { console.log(data.username_clicked) } }) }); // ajax POST request $('.comment_form').on('submit', function(e) { e.preventDefault(); var url = window.location.href.split('?')[0]; $.ajax({ type: 'POST', url: url, data: { text: $('.comment_text').val(), csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, success: function(data) { console.log(data.text) $('.commentsContainer hr').prepend("<div class='comment_div'><div class='left_comment_div'>" + "<div class='username_and_votes'><h3><a href='#' class='username'>" + data.username + "</a></h3><span class='upvotes' style='margin: 0 6'>0</span><span class='downvotes'>0</span></div><br><p>" + data.text + "</p></div><a href='#'><span class='comment_delete'>x</span></a></div>"); $('.commentsContainer').css('height', '+=' + increaseHeight); }, failure: function(data) { alert('error'); } }); … -
In Django with Tastypie, can't get order_by to work with relation
I am using GET with tastypie to filter the results and need to order the results by a datefield, but tastypie is complaining that the field does not allow ordering. Django version: 1.10.2 Tastypie version: 0.13.3 Example URL: localhost:8000/foos/api/foos/?format=json?order_by=bars__insp_date Example Tastypie Resources: class BarResource(ModelResource): class Meta: queryset = Bar.objects.all().distinct() resource_name = 'bars' filtering = { 'insp_date': ALL_WITH_RELATIONS, } allowed_methods = ['get'] ordering = ['insp_date'] class FooResource(ModelResource): onlinereports = fields.ToManyField( BarResource, 'bars', null=True, full=True, ) class Meta: queryset = Foo.objects.all().distinct() resource_name = 'foos' filtering = { 'bars': ALL_WITH_RELATIONS, } ordering = ['bars'] Response: { error: "The 'bars' field does not allow ordering." } -
disable validation in back button in django form
I have a form representing a quiz with some questions and a result that appears in the end in Django 1.10. I need t implement two other buttons next to the "Check" button, one of them is "Mark" and the other is "Back". When I click on "back", I m handling well its behavior in the view but a pop up appears saying "Please Select One Of these Options". I need to disable it since user should not select one of the radio buttons if going back to the previous question. <form action="" method="POST"> {% csrf_token %} <input type=hidden name="question_id" value="{{ question.id }}"> <ul class="list-group"> {% for answer in form.answers %} <li class="list-group-item" >{{ answer }}</li> {% endfor %} </ul> <div id="buttons"> <input type="submit" name="question_btn" value={% trans "Check" %} class="btn btn-lg center-block btn-outline btn-success" required> <input type="submit" name="question_btn" value={% trans "Back" %} class="btn btn-lg center-block btn-outline btn-success" required> Any idea? -
How to serialize an array posted to a django backend
I'm trying to serialize an array that comes from a form. The array looks like this: some_id: 12 array1[]:1 array1[]:2 array2[]:5 array2[]:6 or, as it arrives in request.POST <QueryDict: { 'array1[]': ['1', '2'], 'array2[]': ['5', '6'], ... Now I get the serializer working for the simple id: some_id = serializers.IntegerField(), which is great. I've tested it without the arrays and everything works as expected. For the array I thought I found this serializer field: listfield I tried the following implementation: array1 = serializers.ListField( child=serializers.IntegerField(min_value=1) ) This looks like the manual says how it works, but it only seems to give me the following error: TypeError at /api/myendpoint/ 'int' object is not iterable I'm not really sure where I went wrong, maybe I'm on the wrong track (really not a Django guy :) ), but I'm sure it's a small mistake. So how can I serialize a posted array (or should I call it a Dict?) -
How to check list_display if no value, to show -- in django admin?
django ver 1.10 How can I conditionally check if a variable is blank and show "-"? i.e if get_followers and/or get_following are not set, display "-" @admin.register(Application) class ApplicationAdmin(admin.ModelAdmin): list_display = [ 'name', 'get_following', 'get_followers', 'get_friends', 'manager', ] -
How to make sorting in DB by the number of items in the ListField?
I have the next model: class Departments(Document): _id = fields.ObjectIdField() name = fields.StringField(blank=True, null=True) department_id = fields.StringField(blank=True, null=True) # Added list_of_users = fields.ListField(blank=True, null=True) list_of_workstations = fields.ListField(blank=True, null=True) As you can see list_of_users and list_of_workstations are lists of items. I wrote a code in Python, which takes all data from DB, put it into dict and then sorts as I need, but it works too slow. How can I sort Departments right in DB by length of list_of_users or list_of_workstations or by ratio of list_of_users/list_of_workstations right in the DB, something like: departments = DepartmentStats.objects.order_by(len(list_of_users)).dsc or departments = DepartmentStats.objects.order_by(len(list_of_users)/len(list_of_workstations)).dsc ? -
UnicodeDecodeError when uploading a photo to Azure using Django
I'm working on a server that requires uploading a photo from the client devices, and storing them in Azure blob storage. Following both the Django, and Azure documentation, I created the following snippet: photo = request.data['file'] blob_block = BlockBlobService(account_name=settings.AZURE_ACCOUNT_NAME, account_key=settings.AZURE_ACCOUNT_KEY) blob_block.create_container('events') blob_block.create_blob_from_bytes('events', e1.eventuuid, photo.read, content_settings=ContentSettings(content_type='image/jpeg')) However when returning the photo from storage, I keep getting: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte, and I can't find any other encoding that works. What encoding should I be specifying, or what part of my code needs to change? -
Microsoft Azure Django SQL connection w/ ADO.NET
I'm currently following this tutorial to build a Django web app that uses the Azure SQL database: https://docs.microsoft.com/en-us/azure/app-service-web/web-sites-python-ptvs-django-sql I'm on the step for "Configure the Project", where I'm supposed to paste the connection string in settings.py. (I'm using Visual Studios, with Python Tools). The string is in this format: Server=<ServerName>,<ServerPort>;Database=<DatabaseName>;User ID=<UserName>;Password={your_password_here};Encrypt=True;TrustServerCertificate=False;Connection Timeout=30; However, when I try to do a Django migrate, I get an invalid syntax error. When I copy the ADO.NET string from Azure, the server name has "tcp:" in front i.e. tcp:myserver.database.windows.net, am I supposed to include the "tcp:"? It seems like it's triggering an error. Are the spaces in the parameter titles (like "User ID" and "Connection Timeout") causing an error? Pretty new to using Django / Azure SQL so any help would be appreciated. -
Django: Turn QuerySet in Dictionary before rendering
I would like to render a QuerySet because it would be easy to render in templates. However, I am struggling to build the right one. So, I decided to build a dictionary and render it. Is that a Django way of doing? Here is a simple app which associates instances of Application with instances of Event. Purpose : let managers know status of applications on production. An event is pending when it 'status_end' properties is Null. Each new 'event' associated with an 'application' would close the last event by filling the 'status_end' value. Application without open event are all status OK! Here is a part of the model : class Application(models.Model): app_name = models.CharField(max_length=20) class Event(models.Model): STATUS = ( ('OK', 'OK'), ('KO', 'KO'), ) app = models.ForeignKey(Application, on_delete=models.CASCADE) status_start = models.DateTimeField() status_end = models.DateTimeField(null=True, blank=True, editable=True) status_global = models.CharField(max_length=20, choices=STATUS, default='OK') Usually, in my views, I render QuerySet. But in this case, there is some more processing. So, in my views.py, I wrote a view that would render a dictionnary. def dashboard_appstat(request): answer = [] for app in Application.objects.all(): try: # one event still running. open_event = app.event_set.get(status_end__isnull=True) answer.append({'app': app.app_name, 'status_global': open_event.status_global,\ 'status_bdd': open_event.status_bdd, 'status_batch': open_event.status_batch,\ 'status_comment': open_event.status_comment, 'status_start': open_event.status_start}) … -
Use Django model in client application
I have a system consisted of a few micro services that use each other. One of them is a Django server (let's name it A) and another is a python module that doesn't use Django at all (let's name it B). My project structure looks something like this: -root - commons - A - B Where commons is used both in A and B and in deployment copied to each. B uses A via HTTP calls. I would like in B to use the model objects of A instead of using them as dicts. What is the best practice for this? I attempted to move the models.py file from A to commons and import it from there in both. I don't know if it will work for B yet, as it fails the tests of A with: RuntimeError: Model class commons.models.A.SomeModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I am using Django 1.10.3 and Python 3.5 Thanks ahead, -
Creating Dynamic Form Fields based off model
I'm trying to create a form that creates an object with a foreign key field and a ManyToMany Field. I want to be able to set the foreign key with the form, and dynamically show fields based on the number of many to many fields. That is, set the foreign key data, then based on the how many options there are in the many to many field, show that number of fields (this is an inventory system, so it's an Inventory object, that has a foreign key to the item description, and a many to many field for the different location that item). The number of locations, however, can vary from year to year, and would be changed through a choices dictionary. Models.py class MerchandiseInventory(Model): item = ForeignKey('MerchandiseInventoryItem') locations = ManyToManyField('MerchandiseInventoryLocation') total_on_hand = SmallIntegerField(default=0) class MerchandiseInventoryItem(Model): item_name = CharField(max_length=255, null=False, blank=False) item_id = IntegerField(null=False, blank=False) item_description = TextField() item_price = DecimalField(max_digits=10, decimal_places=2) is_active = BooleanField(default=True) class MerchandiseInventoryLocation(Model): name = CharField(max_length=255) quantity = SmallIntegerField(default=0) is_active = BooleanField(default=True) -
Django: Filtering a queryset then count
I'm trying to limit the number of queries I perform on a page. The queryset returns the objects created within the last 24 hours. I then want to filter that queryset to count the objects based upon a field. Example: cars = self.get_queryset() volvos_count = cars.filter(brand="Volvo").count() mercs_count = cars.filter(brand="Merc").count() With an increasing number of brands (in this example), the number of queries grows linearly with the number of brands that must be queried. How can you make a single query for the cars that returns a dict of all of the unique values for brand and the number of instances within the queryset? Result: {'volvos': 4, 'mercs': 50, ...} Thanks! -
Django: Select related over nested foreign keys
I have: class A(models.Model): pass class AList(models.Model): a_list= models.ManyToManyField(A) class B(models.Model): a_list = models.ForeignKey(AList) I am defining AList like this, as my code is going to define functions that make more sense, when used with lists of A, and not A. ie, meta-data stuff, etc. Now, my question is, use select_related so that I can save all the A instances when I run a filter query over B? -
supervisord works only from project directory
Have Centos 6.8 x86, django 1.10, daphne, redis, virtualenv, celery and supervisord. See strange supervisor behavior. It is work only if i run it from django project directory in nodeamon mode. Like supervisord -n from /root/myblog/myblog directory. /root/myblog is virtualenv path. I tried to checkout old git commit(supervisor and redis config in project folder) but got same result. Not sure after what it happen, before it worked fine. I only compiled ffmpeg, install and uninstall librabbitmq. But have no ideas how it can affect OS. I try reinstall supervisor, but it doesn't change anything. In supervisor logs i see : 2017-01-23 20:47:00,423 INFO spawned: 'uwsgi' with pid 3002 2017-01-23 20:47:05,791 INFO success: worker entered RUNNING state, process has stayed up for > than 5 seconds (startsecs) 2017-01-23 20:47:05,792 INFO success: uwsgi entered RUNNING state, process has stayed up for > than 5 seconds (startsecs) 2017-01-23 20:47:07,591 INFO exited: daphne (exit status 1; not expected) 2017-01-23 20:47:07,592 INFO received SIGCLD indicating a child quit 2017-01-23 20:47:08,612 INFO spawned: 'daphne' with pid 3021 Config file: [supervisord] http_port=/var/tmp/supervisor.sock ; (default is to run a UNIX domain socket server) logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB) … -
how to get next/previous page boto3 pagination
I am retrieving several files from s3, but i want to paginate the items, I am able to paginate the whole list, but how can i for example, show only the first 30 items and have a next page that will show the next 30 and so on... client = boto3.client('s3') paginator = client.get_paginator('list_objects') # Create a PageIterator from the Paginator page_iterator = paginator.paginate(Bucket=bucket_name, PaginationConfig={'PageSize': 30}) for page in page_iterator: # do whatever -
variable in setting file using in template
everybody! I want to access to constants value that I declare in my setting.py file to use in my template, but not in a template inside the app, I just want to use in my home template the template that I declare in my setting file. CMS_TEMPLATES = ( ## Customize this ('page.html', 'Page'), ('feature.html', 'Page with Feature'), ('homeTemplate.html', 'Home Template') // I want to use here ) I found this example about the same problem in StackOverflow, but all case uses the variable inside apps not in top level. How is the best way to use this value inside this template!! -
Getting data with ajax in django
I'm trying to get some data from an external server using django requests and then loop through that data. Url patterns are as follows : from django.conf.urls import url from .business.indicata import get_makes from . import views urlpatterns = [ url(r'^$', views.login_user, name='login'), url(r'^home/$', views.index, name='home'), url(r'^login/$', views.login_user, name='login'), url(r'^makes/$', get_makes, name='makes'), ] business/indicata.py (where I get the data from an external server) is as follows : import json import requests from django.http import HttpResponse from requests.auth import HTTPDigestAuth DEFAULT_TYPE = "PASSENGER" INDICATA_URL = "http://some_url/category=" INDICATA_LOGIN = "some_username" INDICATA_PASSWORD = "some_password" def get_makes(): url = INDICATA_URL + DEFAULT_TYPE response = requests.get(url, auth=HTTPDigestAuth(INDICATA_LOGIN, INDICATA_PASSWORD)) a = json.loads(response.content.decode("utf-8")) return a['nextStep'] If I call get_makes in terminal I get something like : [ {'name': 'Abarth', 'description': [], 'href': 'http://some_url?category=PASSENGER&make=611', 'type': 'application/json', 'rel': 'make'}, {'name': 'Alfa Romeo', 'description': [], 'href': 'http://some_url?category=PASSENGER&make=16', 'type': 'application/json', 'rel': 'make'}, {'name': 'Audi', 'description': [], 'href': 'http://some_url?category=PASSENGER&make=30', 'type': 'application/json', 'rel': 'make'}, {'name': 'Bentley', 'description': [], 'href': 'http://some_url?category=PASSENGER&make=56', 'type': 'application/json', 'rel': 'make'} ] What I want is to loop through that data and show it my template. The template is as follows : {% extends "master/base_menu.html" %} {% block page_title %} <h1 class="page-header text-overflow">Dashboard</h1> <div class="searchbox"> <div class="input-group custom-search-form"> <input type="text" … -
How to handle versioning the logic and models in django?
We are building a django app with a REST API. The constraints that we have are We can't change the logic( the code base that the API uses eg: views.py and models.py) of a published API to avoid breaking the apps that our customers built on top of our API We don't want to edit the tables of a live app. Our solution is to create a new app with the version name then copy the code base that we have from a previous version ( eg: views.py, models.py and tests.py ) then modify them it as required for the new version. When doing our research we only found answers about how to handle REST API versioning using frameworks like django-rest-framework ( like django-rest-framework: api versioning ) but nothing about how to handle the logic and models. -
How to disallow admin to change instance in Django admin?
I have a model Order and model Invoice. The Order has invoice = models.OneToOneField('Invoice', related_name='order', on_delete=models.CASCADE, blank=True, null=True) Invoice object is created right after order object is created an assigned to it. Admin has to change the invoice price before customer pays. The problem is that Django-admin allows admin to change this field too (bottom of the image), which I can't risk but I want to let the pencil icon (change attributes of the invoice). Is it possible to do that? When I add invoice to readonly_fields in OrderAdmin, Admin can't change those attributes. -
API GET request returns 404
I'm currently developing a Django web application which is supposed to add some functionality to online shops based on InSales (a popular Russian web platform). I use the official InSales lib for Python called pyinsales to get objects like orders and products from registered shops. The InSales API is based on REST requests with XML. I use the code below to get information about orders in the Django shell: from install.models import Shop from insales import InSalesApi shop = Shop.objects.get(shop_url='shop-url.myinsales.ru') api = InSalesApi(shop.shop_url, 'trackpost', shop.password) orders = api.get_orders() Here shop.shop_url is the shop URL ("oh, really?"), trackpost is the name of my app and shop.password is the password needed to connect. Password is generated by MD5 (that's an InSales rule). And here I get an error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.5/site-packages/insales/api.py", line 32, in get_orders return self._get('/admin/orders.xml', {'per_page': per_page, 'page': page}) or [] File "/usr/local/lib/python3.5/site-packages/insales/api.py", line 291, in _get return self._req('get', endpoint, qargs) File "/usr/local/lib/python3.5/site-packages/insales/api.py", line 307, in _req response = getattr(self.connection, method)(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/insales/connection.py", line 85, in get return self.request('GET', path, qargs=qargs) File "/usr/local/lib/python3.5/site-packages/insales/connection.py", line 70, in request (method, path, resp.status, body), resp.status) insales.connection.ApiError: GET request to /admin/orders.xml?page=1&per_page=25 returned: 404 … -
Django Rest Framework query with uid (username, userId)
I'm building an app with Django Rest framework. Here is my Django model: class Location(models.Model): uid = models.ForeignKey('auth.User', related_name='locations', unique=True, on_delete=models.CASCADE) area = models.IntegerField(choices=AREA, default=0) address = models.TextField(max_length=150) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('created_at',) verbose_name = 'Location' verbose_name_plural = 'Locations' def __str__(self): return self.area My serializer: class LocationSerializer(serializers.ModelSerializer): # owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Location fields = '__all__' My view: class LocationViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = Location.objects.all() serializer_class = LocationSerializer permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,) My routes are registered using router.register. when I query like this: localhost:8000/locations/<locationId> I get result of perticular locations. But I want to query like this: localhost:8000/locations/<username/uid> . How can I accomplish this? P.S.: I'm new to Django. -
Django Model Admin with FileField cannot read file in save_model after reading file when validating
I have a model with a FileField and I want to read the contents of the file before saving it in the Django admin. I need to verify the file is formatted correctly and also to parse version information out of it and save it into the model. I have written code for validation and can successfully validate the file, but it seems I cannot save the version information from the file in the save_object method after i successfully run the validation. If i skip using the validation, the code in the save_object method works as expected and I can read the file contents and save the version information into the model. I just can't get them to both work at the same time. # models.py: # the validation works def validate_file_contents(value): contents = value.read() first_line, rest_of_file = contents.split('\n', 1) if not validate_file_format(rest_of_file): raise ValidationError("File is not formatted correctly.") if not parse_version(first_line): raise ValidationError("The file does not contain correctly formatted version information.") class MyModel(models.Model): file = models.FileField(validators=[validate_file_contents]) version = models.CharField(max_length=100, null=True, blank=True) ----------------------------------------------------------------------------------------------- # admin.py: class MyModelAdmin(admin.ModelAdmin): fields = ['file',] list_display = ['file', 'version'] list_filter = ['file', 'version'] def save_model(self, request, obj, form, change): contents = request.FILES['file'].read() # contents is … -
Apache redirecting Django app to index.html
I have a Django app that is being served using Apache with mod_rewrite enabled. There is a .htaccess file with the following in it: RequestHeader set X-Forwarded-Protocol https RewriteEngine on RewriteBase / RewriteCond %{REQUEST_URI} !^/static/ RewriteRule ^(.*) http://127.0.0.1:8000/$1 [proxy, last] When I open sub urls, like http://www.mypage.com/goodstuff it works, whereas when I go to the main page http://www.mypage.com/ apache redirects it to http://www.mypage.com/index.html/ and returns the page not found error. I asked a question already, thought I solved the issue by getting rid of the $1 and clearing my local cache, but it doesnt work - messes up some of the links when I get rid of the $1 (redirects to /# dont work). Sorry about the duplicate Question, but I really have been hitting my head against a wall here. Im using Apache 2.4.10, it might have been working on Apache 2.2.22. Also using a redis cache.