Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
heroku not serving css
I have the following code in my settings.py in django. DEFAULT_FILE_STORAGE = 'hhhh.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'hhhh.utils.StaticRootS3BotoStorage' S3DIRECT_REGION = 'us-west-2' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' STATIC_ROOT = STATIC_URL + 'static_root/' Heroku is not serving the ststic files. any ideas. I have the allowed hosts set to my site and heroku. -
Can Django work well with pandas and numpy?
I am trying to build a web application that requires intensive mathematical calculations. Can I use Django to populate python charts and pandas dataframe? Thank you! -
can you convert a python desktop app into django?
i might have a stupid question, but im new to python and some of you have much more experince than me. I have a python app with pyqt GUI and MariaDB, i would like to know if there is a methond to cpnvert this desktop app into django web app. Can i convert the pywt GUI into web interface or i need to rebuild it again? Can i convert all the code written for pyqt or do i need to write some of it again? Thank you. -
Why my Django app on heroku displays Server Error (500) for default page?
I have my django app hosted with heroku. However without anything being changed from my side default page stopped working in last few weeks.This is how I define it in my url file: url(r'^$', views.leaseterm_list, name="leaseterm_list"), This is the message in the log 2017-07-15T10:41:19.632772+00:00 heroku[router]: at=info method=GET path="/" host=****.herokuapp.com request_id=77d7c992-5338-4155-9c0a-c4c2bbb46905 fwd="70.55.61.228" dyno=web.1 connect=1ms service=104ms status=404 bytes=288 protocol=https Any idea what is going on? I assume heroku changed something on their side. -
Nested models in Django serializer
I wish to receive JSON formatted like that: { detailing: [ <detailing>, ... ], results: [ { id: <id>, data: [ { x: <tag>, y: <count> }, ... ] summ: <summary count>, percentage: <percentage summary count> }, { id: <id>, data: [ { x: <tag>, y: <count> }, ... ] summ: <summary count>, percentage: <percentage summary count> }, ... ] } In other words, i need 'detailing'(not for every 'Floor' instance, but for all) field above the 'results' field, and 'results' have to contains all of 'Floor' instances. I think, that for this problem solving, i need 3 serializers classes, one for 'detailing', one for 'results' and one for aggregate it together. Here is my code sample: # serializers.py class DetailingSerializer(serializers.Serializer): detailing = serializers.SerializerMethodField() class Meta: fields = ('detailing',) def get_detailing(self, obj): return ['dekaminute', 'hour', 'day'] class FloorTrackPointsCountSerializer(serializers.ModelSerializer): results = serializers.SerializerMethodField() class Meta: model = Floor fields = ('results','detailing',) def get_results(self, obj): res = [ { 'id': obj.id, 'data': [{'tag':tp.tag,'timestamp':tp.created_at} for tp in obj.trackpoint_set.all()], 'summ': obj.trackpoint_set.values('tag').distinct().count(), 'percentage': 0.5 } ] return res class AggregationSerializer(serializers.Serializer): detailing = DetailingSerializer(many=True) results = FloorTrackPointsCountSerializer(many=True) class Meta: fields = ('results', 'detailing') # view.py class FloorTrackPointsCountViewSet(ListForGraphicViewSet): queryset = Floor.objects.all() serializer_class = AggregationSerializer # models.py class Floor(InModel): … -
Task not executing django-celery non-periodic task
I am new in django-celery and I want to execute a non-periodic task through celery-redis.I am getting task.id but the task is not executing at given eta. Reminder_Time=5 def do(self): eventTime = arrow.get(self.scheduleTime, self.timezone.zone) reminderTime = eventTime.replace(minutes=-REMINDER_TIME) print(reminderTime) from task.perform import add action = add.apply_async((self.pk,), eta=reminderTime) return action.id And in other file i have code for add from celery import shared_task @shared_task def add(task_pk): print(2+5) The task is not performed at given eta although I got action.id as value like-6b7f7e9c-dad9-4756-8aed-fd8be331cbb1 -
How to render all the data associated with one entry through link Using Django ?
I am learning Django and created an app "myapp", having defferent components as per given bellow: Models looks like this: Model.py: from __future__ import unicode_literals from django.db import models class Country(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class CountryDetails(models.Model): country = models.ForeignKey(Country) T_attack = models.PositiveIntegerField(verbose_name="attack") year = models.CharField(max_length=254) Deaths = models.CharField(max_length=254) NEWS_ID = models.CharField(max_length=254, verbose_name="NEWS_ID") def __unicode__(self): return self.Deaths View looks like this: view.py: from django.shortcuts import render, get_object_or_404 from .models import Country, CountryDetails def home(request): c_list = Country.objects.all() return render(request, 'myapp/home.html', {'c_list':c_list}) def details(request, pk): c_details = get_object_or_404(CountryDetails, pk) return render(request, 'myapp/home.html', {'c_details':c_details}) Urls looks line this: urls.py: from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^myapp/(?P<pk>\d+)/$', views.details, name='details'), ] For rendering the view html looks like this: home.html: {% for c in c_list %} <h1><a href="{% url 'details' pk=c.pk %}">{{ c }}</a></h3></br> {% endfor %} In short, I have created an app, having some data for various countries like this Raw data: name T_attack year Deaths News_ID India 12 2006 12 NDTV India 110 2009 1 DEAN PAKISTAN 9 2002 10 XYZT PAKISTAN 11 2021 11 XXTV India 12 2023 120 NDNV India 10 2012 12 DEAN … -
Django - How to extend the swagger with additional functionalities?
I am using Django with Swagger documentation. I wonder if there is any way to extend functionalities. At this moment I have just base schema in settings. I see only URLs. When I click Django Logout it doesn't work. Is there a possibility to add an option to send an example body in methods? For instance I have also optional searching like GET /users/{user_id}/object?sth=123 is it possible to include it in swagger documentation, too? I was looking in the documentation but there isn't much information. My settings at this moment look in this way: schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^', schema_view), ] -
Control/space characters not allowed (key="\xebw\x1b}\xae\xa3\xb8\x18\xc4\xb5\xce\x0c%\x13'\xed")
I am using caching for my site using using. This is giving the following error: "Control/space characters not allowed (key="\xebw\x1b}\xae\xa3\xb8\x18\xc4\xb5\xce\x0c%\x13'\xed")". The code which I am using is as follows: def hash_key(key, key_prefix, version): new_key = '%s :%s :%s' % (key_prefix, version, key) if len(new_key) > 250: m = hashlib.md5() m.update(new_key) new_key = m.digest() return new_key CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1.11211', 'KEY_FUNCTION': hash_key, } } How can I resolve this issue. -
How to call function from template With Django
Please let me know in Django how to call method written from template html to view. Also please tell me about how to pass variables. class index(TemplateView): template_name = "index.html" def get(self, request, *args, **kwargs): text = "text" return render(request, self.template_name, {'text': text}) def Replace text = "Replaced" (I want to pass variable text to index html from here) index.html is as follows <p>{{ text }}<p> <a html="{?????}">text replace</> If you click "text replace" you want to call the function "Replace" to replace the variable "text". Though it is a rudimentary question, thank you. -
python manage.py makemigrations blog returns no changes detected in app 'blog'
this is the sublime text editor code in model.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_lenght=250) slug = models.SlugField(max_lenght=250) content = models.TextField() seo_title = models.CharField(max_lenght=250) seo_description = models.CharField(max_lenght=160) author = models.ForeignKey(User, related_name='blog_posts') published = models.DateTimeField(default=timezone.now) Created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_lenght=9, choices=STATUS_CHOICES, default='draft') def __str__(self): return self.title ===>> later after saving in sublime text editor i opened command promt and typed command "python manage.py makemigrations blog" it returned an error of - No changes detected in app 'blog' enter image description here screenshot of the error -
Can we use Orator orm with django rest framework
I am working with Orator Orm and its very nice Orm. I also like the Django rest framework for its core features like validation, api tester tool etc... I just want to know can we use Orator orm with DRF. -
Django 1.10 Postgres JSONField extract specific keys
I have a Postgres based JSONField in my model. class MyModel(models.Model): data = JSONField(default=dict) The JSON sample is like: { 'key1': 'val1', 'key2': 'val2' } I have multiple objects of the model, let's say ~50. I am trying to query for only the key1 inside data and want to get a list of all the distinct values of the key1. How can I do that? Please note I am using Django 1.10. -
How write a nose test wrapper for different test modules of django
I have a django project and there are different modules inside it. I have test script inside every module. Currently, I am running test modules individually, now I want to run all of them together. I am using nose for testing environment. - project - manage.py - foo - __init__.py - test.py - .... - bar - __init__.py - test.py - .... - baz - __init__.py - test.py - .... This is my project structure. I want to test all the tests together. -
OS X python virtualenv not working
LAD@LADs-MacBook-Pro ~/Documents/pythonenv source myvenv/bin/activate LAD@LADs-MacBook-Pro ~/Documents/pythonenv trying to activate python environment but it doesn't work without any error meaasge -
How to update a related model after another model is created?
I need to automatically update my Account's amount when a Transaction is created. I have Transaction model's model.py: class Transaction(models.Model): user = models.ForeignKey(User, default=None) account = models.ForeignKey(Account, default=None) ... Its serializers.py: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ('id', 'user', 'account_id', 'category_id', 'name', 'amount', 'description', 'created_at') def create(self, validated_data): return Transaction.objects.create(**validated_data) And its views.py: class TransactionList(APIView): def get(self, request): user_id = request.user.pk transactions = Transaction.objects.filter(user_id=user_id).order_by('-created_at') serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) def post(self, request): account_id = request.data['account_id'] category_id = request.data['category_id'] serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user, account_id=account_id, category_id=category_id) self.update_account(request) return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) def update_account(self, request): account_id = request.data['account_id'] category_id = request.data['category_id'] account = Account.objects.get(pk=account_id) category = Category.objects.get(pk=category_id) if category.type == 'expense': account.amount = (account.amount - int(self.request['amount'])) else: account.amount = (account.amount + int(self.request['amount'])) # Then what? I thought of creating a custom method that will be executed within the condition if serializer is valid, that would get the account and category by their id. I could, so far, display the current values they have, such as amount and name, but after that, I don't know what to do. I'm imagining I need to use my AccountSerializer, but I'm not sure. -
Django Apache - Unable to Open Database File
I just set up my first apache server on a debian system and I'm tryin to run a Django project. BASE_DIR is os.path.dirname(os.path.dirname(os.path.abspath(__file__))) I've run sudo chown www-data. ., so I don't think that's the problem. I'm not sure where the db_sqlite3 folder should be or if I need to install a database manually. Basically, I just want to get a basic project running with the default Django db, but I keep getting the error "Unable to open database file." I've run many Django projects in Windows 10 with no problems. What could I be missing? -
HttpResponseRedirect does not load template
Please help with the following. I am trying to redirect a django view to another view. The view is directed as shown in the server logs but the template does not log. server log [15/Jul/2017 03:08:37] "POST /myApp/index4/ HTTP/1.1" 302 0 [15/Jul/2017 03:08:37] "GET /myApp/index5/ HTTP/1.1" 200 160 here are my views. def firstView(request): url = reverse('index5') return HttpResponseRedirect(url) def secondView(request): template_name = 'myApp/testpage.html' return render(request, template_name) my urlpatterns urlpatterns = [' url(r'^index4/$', views.firstView, name='index4'), url(r'^index5/$', views.secondView, name='index5'), ] -
ImproperlyConfigured:You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I am new to django ! When I use the commad, git push heroku master I get this error. remote: django.core.exceptions.ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 My static files declarations are : STATIC_URL = '/static/' # set for the Heroku deployment. import dj_database_url DATABASES = { 'default': dj_database_url.config(default='postgres://localhost') } #make reuqest.is_secure admit X-Forwarded-Proto SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # support all the host header ALLOWED_HOSTS = ['*'] #static configuration BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) My requirements.txt/runtime.txt/Procfile are all good, I googled a lot, Even tried the whitenoise, still I cannot fix it, so can someone help me? Thanks a lot! My requirements.txt are like below: dj-database-url==0.4.2 dj-static==0.0.6 Django==1.11.1 django-bootstrap3==8.2.3 gunicorn==19.7.1 pytz==2017.2 static3==0.7.0 IF I do heroku config:set DISABLE_COLLECTSTATIC=1 I can push successfully, but the blog page does not show out because of some error. -
django rest framework api documentation through swagger
It is already giving the swagger inbuilt page on localhost. It is reading my urls perfectly. But i am unable to define the interior headers, response body. I dont know where to define it and how to connect it with my django project. urls.py from django.conf.urls import url, include from django.contrib import admin from users import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Pastebin API') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/v1/users/emailsignup/', views.SignUp.as_view()), url(r'^api/v1/users/userget/', views.UserDetail.as_view()), url(r'^$', schema_view), ] Thus the schema_view is given . But plz expalain me how to define my response body in it with code. -
Get current user
class Makale(models.Model): baslik = models.CharField(max_length=200) yazi = models.TextField() tarih = models.DateTimeField(default=timezone.now) kategori = models.ForeignKey('Blog.Kategori') yazar = models.ForeignKey('Blog.Yazar',blank=True, editable=False) class Yazar(models.Model): kullanici = models.ForeignKey(User) tam_adi = models.CharField(max_length=200) katilma_tarihi = models.DateTimeField(default=timezone.now) yazi = models.TextField() i am creating user in admin panel i want name of that user. how should i do ?? i dont very well django :( -
Embedding actions in a DataTables table
I have a datatables table on a website that I want users to be able to interact. The table is essentially a to-do list, and I'm wondering how to add a 'Done' button to each row. I saw there is row.delete(), but I want to still keep the task in the database, just remove it from the table the user sees. Here is my code implementing the table: <script type="text/javascript"> $(document).ready(function(){ // declare variable for dataTable var table = $('#example').DataTable({ // order table by most recent first "order": [[ 2, "desc" ]], // disable pagination "bPaginate": false, // define url for ajax requests "ajax": '/main/newtask/', // define columns, tells ajax.reload() how to read data "columns": [ { "data": "priority" }, { "data": "task" }, { "data": "time" } // I would like to add the 'Done' button here ] }); // every ten seconds, update table setInterval(function(){ table.ajax.reload(); }, 10000) }); </script> -
Prevent model update on updating ImageField's image / url
I'm using Django simple-history to have a historical record of a models changes. However, when updating the url / image for an ImageField as follows: response = requests.get(url, headers=HEADERS) if response.status_code == 200: img_content = ContentFile(response.content) field.delete() field.save(path, img_content) This is causing the historical record to add a new entry with the reason as Updated when save is called. This will happen on every single image I'm updating while scraping the urls to be reflected in the backend. Since I'm scraping and aggregating total changes I only want one entry to be set with the reason, I'm setting manually, once I actually save the model to reflect the changes. Moreover, the template relies on the last entry to be the aggregate change for comparison views without complicating the logic grabbing the latest updated entries. How can I avoid this? -
Simulating a submit button through jquery and collecting all html input values
I have the following form: <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="state"> <option selected disabled>Choose a State</option> <option value="1">California</option> <option value="2">New York</option> </select> <select name="State" class="state"> <option selected disabled>Choose a State</option> <option value="1">California</option> <option value="2">New York</option> </select> ... Repeated an unknown number of times. ... <br><br> </div> </div> <input type="button" id="submit" value="calculate"> </form> I would like to simulate the calculate button as a submit button with jquery using an ajax call. In a regular submit within Django/html, the post request would collect and send a list of the 'state' values (given there are multiple selections with the name 'state') and other input values to the server. Is there a similar function in jquery that collect all of the input value from the html to include as an argument for the ajax call?? -
Django - How to extend the swagger with additional functionalities?
I am using Django with Swagger documentation. I wonder if there is any way to extend functionalities. At this moment I have just base schema in settings. I see only URLs. When I click Django Logout it doesn't work. Is there a possibility to add an option to send an example body in methods? For instance I have also optional searching like GET /users/{user_id}/object?sth=123 is it possible to include it in swagger documentation, too? I was looking in the documentation but there isn't much information. My settings at this moment look in this way: schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^', schema_view), ]