Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass javascript variable to Django template
This piece of code is a javascript variable which passes url to a callback function and clicking on certian part of a map renders associated views and subsequently the template "Country_Details.html" var var_1 = "{% url 'County_Details' pk=1 %}" In the given example, I have passed an argument, that was "pk=1" it work fine fetched the object associated with the "id" = 1. def County_Details(request,pk): C_Details = CountryDiseases.objects.filter(country__pk=pk) return render(request, 'DATAPLO/Country_Details.html', {'C_Details': C_Details }) but I have a list of ids and I want a solutions that can replace the pk values dynamically according to clicks through a variable, say, "my_id". Though i have tried many things but nothing is working for me. A very close thread as of mine, I found on web is given bellow. Get javascript variable's value in Django url template tag I have tried all the solution suggested but nothing is working. How could I solve this problem. Thanks -
Reduce django app memory usage on heroku
i just got a webapp up and running on heroku web server. It uses celery worker and beat, each scaled with 1 dyno to run some background process. I'm trying to fetch all of the youtube video urls from a youtube channel, which consists of about 1500 get requests to the youtube data api, but i'm running into E14 memory issues when I get about half way through. According to the Heroku metrics, my worker is peaking the memory quota limit at about 540mb where my limit is 512mb. Any tips on how to reduce the memory usage? Also, in general would it take more memory to do the get requests or to actually save all of those things in the database? Thanks -
A simple tutorial for using JavaScript in Django apps?
What's the simplest tutorial for using JavaScript in Django apps that you'd recommend? Besides the "default": https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/javascript/# I've found this one: https://lethain.com/intro-to-unintrusive-javascript-with-django/ Please, I'm open to suggestions about where to begin. -
Celery accessing logger file - [Errno 13] Permission denied:
I'm having a hard times with logging settings. I'm running celery worker and beat using supervisor. The celery is inside django project. I've created a folder logs where I want to have all logs. permissions: /logs/ drwxrwxrwx 2 django django 4096 Jul 20 15:03 logs /logs/any_file total 1488 drwxrwxrwx 2 django django 4096 Jul 20 15:03 . drwxrwxr-x 9 django django 4096 Jul 20 15:02 .. -rw-r--r-- 1 root root 762824 Jul 20 15:07 celeryb_err.log -rw-r--r-- 1 root root 0 Jul 20 15:03 celeryb_out.log -rw-r--r-- 1 root root 737880 Jul 20 15:07 celery_err.log -rw-r--r-- 1 root root 0 Jul 20 15:02 celery.log -rw-r--r-- 1 root root 0 Jul 20 15:03 celery_out.log -rw-r--r-- 1 root root 0 Jul 20 15:02 engine.log -rw-r--r-- 1 root root 0 Jul 20 15:02 scrapy.log I suppose that it's because every log file owns root. The problem is that celery returns: celeryb_err.log Traceback (most recent call last): File "/home/django/realestate_scanner/realestate_scannervenv/bin/celery", line 11, in <module> sys.exit(main()) File "/home/django/realestate_scanner/realestate_scannervenv/local/lib/python2.7/site-packages/celery/__main__.py", line 14, in main _main() File "/home/django/realestate_scanner/realestate_scannervenv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/django/realestate_scanner/realestate_scannervenv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/django/realestate_scanner/realestate_scannervenv/local/lib/python2.7/site-packages/celery/bin/base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/django/realestate_scanner/realestate_scannervenv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 480, in handle_argv return self.execute(command, argv) File "/home/django/realestate_scanner/realestate_scannervenv/local/lib/python2.7/site-packages/celery/bin/celery.py", … -
Django 1.8.17 django-debug-toolbar Logging panel
I have Django 1.8.17 and I can see django-debug-toolbar from my dashboard. I'd like to be able to log messages in Logging panel\ setting.py import logging # create logger logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) # 'application' code logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message') I can see output in Terminal console but not in Logging panel Any clue? -
Link a function to a model entry
I was looking at the result of this question on linking a specific method to a model entry, but not sure the solution used in the end is that elegant... I want to have some sort of pointer to a specific method from a model entry in the database. This is my idea on how to do it but it seems abit clunky: class Results(models.Model): result_ref = models.CharField(...) result_name = models.CharField(...) result_unit = models.CharField(...) def result_1_method(): return "My custom result for entry 1" ... >>> results_map = {1: result_1_method, 2: result_2_method, ...} >>> required_result = Results.objects.get(results_ref='XAY') >>> required_result_method = results_map[required_result.id] >>> result = required_result_method() Is there a better or more commonly used solution? Like storing a method as part of the db entry for example? Thanks :) -
variable model name with orm et class meta in django
I have a probleme for use a variable in model name, i want to take this command : MyVar.objects.all().delete() and in the same way i have to a probleme for take this : class MyCsvModel(CsvDbModel): class Meta: dbModel = MyVar delimiter = delimiter_csv these actions are on methode of a class. and variable is created on here methode. Sorry for my english, i am beginner... -
Mutually Referential Serializers Django Rest
So I've been creating a bidding system in which each bid model is attached to a particular request instance or offer. Conversely, every request instance has a bidpick field representing the selected bid. It is easy to see that the code will exhibit what I like to call mutually referential design, the Bid class will refer to the Request class and vice versa. Now I've moved on from standard Django to working with the Django Rest Framework, and my first step has been to serialize these models. Unfortunately, Python has no standard support for forward declarations nor does DRF support mutually referential classes right out of the box, so I've had to use a patch to handle recursive definitions like so: class RequestSerial(ModelSerializer): servuser = UserSerial() bidpick = RecursiveField('BidSerial', allow_null = True, required = False) class Meta: model = Request fields = '__all__' class BidSerial(ModelSerializer): biduser = UserSerial() request = RequestSerial() class Meta: model = Bid fields = '__all__' Unfortunately, this doesn't really seem to work despite the fact that my code mirrors an example use case in the patch. I'm getting a max recursion depth exceeded error, and I was wondering if you guys had any thoughts or suggestions … -
django ListView - Sort queryset by the order of mptt-TreeForeignKey field
I have the following two models. class Category(MPTTModel): name=models.CharField(max_length=75,null=False,blank=False, unique=True) parent=TreeForeignKey('self', null=True, blank=True, related_name='children') and class ProductGroup(models.Model): name = models.CharField(max_length=30,null=False, blank=False) category=TreeForeignKey('category.Category', null=False,blank=False) I have set and order for the categories through the admin panel. I need to get the productgroup objects sorted in the same order through its ListView sub class. I have tried, class ProductGroupList(ListView): model=ProductGroup ordering = ['category'] but this lists the objects in the order of id of Categories. Is there a way to specify the order specified in the mptt tree? Thanks. -
Phone Number formatting in Django
I have a database with all variations to enter a phone number. It also includes special characters and different formats entered by the user. The data is in Excel and I am trying to get all the phone numbers into a single format i.e, Countrycode - phone number Eg: +1 - 1234567899. I have phone numbers from different countries in the data. Can you guys please suggest on how to do this in Django. -
Styling an Accordian Table
I made this accordian table using bootstrap accordian. IT works well, but it looks terrible. The way i have it set up is a nested accordian. the code can be seen as follows: <!DOCTYPE html> <html> <head> {% load staticfiles %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <!-- {# Load CSS and JavaScript #} --> <!-- {# Load the tag library #} --> {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} {% block javascript %} <script> //this is not working as yet $(document).ready(function() { //script to refresh div - formclass is class name of form $('#formclass2').submit(function(event){ var servername = $('#servername').val(); var divname=servername+"div"; $.ajax({ url: 'formsubmitcode', type: 'post', dataType:'html', //expect return data as html from server data: $('#formclass').serialize(), success: function(response, textStatus, jqXHR){ $('#'+divname).html(response); //select the id and put the response in the html }, error: function(jqXHR, textStatus, errorThrown){ console.log('error(s):'+textStatus, errorThrown); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function () { var frm = $('#myform'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), //picks up the action from form data: frm.serialize(), success: function (data) { $("#test").html(data); $("MESSAGE-DIV").html("Something not working"); }, error: function(data) { $("#MESSAGE-DIV").html("Something went wrong!"); } }); ev.preventDefault(); }); }); </script> {% endblock %} </head> <body> <ul> {% for checkkey,checkvalue in orgnizedDicts.items %} … -
Django, matching query does not exist with existing db row
I got strange issue with Django ORM. Here's Action objects with id 1 and 6, but a can't get first by id. Both of them exist in database. In [17]: Action.objects.get(code='check_email').pk Out[17]: 6L In [18]: Action.objects.get(code='periodic_order_check').pk Out[18]: 1L In [19]: Action.objects.get(pk='6') Out[19]: <Action: Check Email> In [20]: Action.objects.get(pk='1') --------------------------------------------------------------------------- DoesNotExist Traceback (most recent call last) <ipython-input-20-728196789a45> in <module>() ----> 1 Action.objects.get(pk='1') /home/vagrant/.pyenv/versions/vagrant/lib/python2.7/site-packages/django/db/models/manager.pyc in manager_method(self, *args, **kwargs) 120 def create_method(name, method): 121 def manager_method(self, *args, **kwargs): --> 122 return getattr(self.get_queryset(), name)(*args, **kwargs) 123 manager_method.__name__ = method.__name__ 124 manager_method.__doc__ = method.__doc__ /home/vagrant/.pyenv/versions/vagrant/lib/python2.7/site-packages/cacheops/query.pyc in get(self, *args, **kwargs) 351 qs = self 352 --> 353 return qs._no_monkey.get(qs, *args, **kwargs) 354 355 def exists(self): /home/vagrant/.pyenv/versions/vagrant/lib/python2.7/site-packages/django/db/models/query.pyc in get(self, *args, **kwargs) 385 raise self.model.DoesNotExist( 386 "%s matching query does not exist." % --> 387 self.model._meta.object_name 388 ) 389 raise self.model.MultipleObjectsReturned( DoesNotExist: Action matching query does not exist. -
Django check if querysets are equals
I have this django code q1 = MyModel.objects.all() q2 = MyModel.objects.all() when I try print q1 == q2 I get as results False So How can I check if two querysets result's in django are equals ? -
django. Templates working local but not on pythonanywhere.com
I have a working project in django when I run it local but not when I run it on pythonanywhere.com. I get error TemplateDoesNotExist. How do I make it run on pythonanywhere.com? Do i have to do something in the code or in pythonanywhere web app settings? Thanks! My code: settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = ['www.estateify.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'taskoftheday', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Ask_Oskar.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Ask_Oskar.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ url(r'^taskoftheday/', include('taskoftheday.urls')), … -
django celery crontab periodic_task hourly not working
I have a periodic_task that works if I set crontab to run every hour, it works. But if I set it to something specific like hour="13" minute="5" (run at 1:05PM) it doesnt work. The problem might be in timezone configuration. Am I doing something wrong? settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Manila' USE_I18N = True USE_L10N = True USE_TZ = True celery_app.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IrisOnline.settings') app = Celery('IrisOnline', broker='redis://localhost:6379/0',include=[ "IrisOnline.tasks", "order_management.tasks" ]) app.conf.update( CELERY_TIMEZONE = 'Asia/Manila' ) app.conf.update( broker_url = 'redis://localhost:6379', result_backend = 'redis://localhost:6379', task_serializer='json', accept_content=['json'], result_serializer='json', timezone='Asia/Manila', ) app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'IrisOnline.tasks.printthis', 'schedule':(crontab(hour=13,minute=33)), }, } # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) -
Static fiels doesn't load in django 1.11
I'm using django1.11 to build a web app.I have add required settings for static files in settings.py and all of static files was working fine. But I was trying to add 404 custom templates during that suddenly my static files stop loading. Here's my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'IGui', 'static'), ) Here's my urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', home_url.index, name='home'), url(r'^dockers/', views.DockerStuff.as_view(), name='docker-stuff'), url(r'^user/', include(user_urls, namespace='users')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My directory tree: -IGui IGui -static --css --js Help me, please! -
Django created folder can't be removed apache on Centos 7
I have a django application which creates a work directory for a package. This is done with: if not os.path.exists(dest): os.makedirs(dest) The creation of the folder works great, but when the django application later try to remove the very same folder, I get "Permission denied". Apparently the permissions of the folder and files created by django is owned by root and not by apache. Why is it not owned by apache if apache created it? How can I make apache and django to create it as apache? -
psycopg2.Error isn't being caught in python try/except block
I am developing an application using django with a PostgreSQL database. The application is designed to be used within an organization, so user-supplied SQL requests need to be executed. To deal with the possibility of malformed SQL requests, the database calls are wrapped in a try/except block: import psycopg2 ... def djangoView(request): ... try: result = DBModel.objects.raw(sqlQuery) return getJSONResponse(result) #Serializes result of query to JSON except psycopg2.Error: pass #Handle error (no db requests are made) However, when I make a request to the view with malformed SQL, I am greeted with a 500 internal server error. The stack trace reveals that the cause of the 500 is a ProgrammingError, which is a subclass of psycopg2.Error. However, the except statement doesn't catch it correctly. -
add new field on button click event field django forms
add new field on button click event field Django forms. I have button that is created using jdango form, while clicking on that button I have to add another text field in UI. I tried with JavaScript and its working. But I am not getting value while submitting to python file. I am new to django. please someone help me. -
Thwarting form multi-submission through server side tokens (Django)
I am trying to implement a server-side check to prevent users from double-submitting my forms (Django web app). One technique I'm trying is: 1) When the form is created, save a unique ID in the session, plus pass the unique ID value into the template as well. 2) When the form is submitted, pop the unique ID from the session, and compare it to the same unique ID retrieved from the form. 3) If the values are the same, allow processing, otherwise not. These SO answers contributed in me formulating this. Here's a quick look at my generalized code: def my_view(request): if request.method == 'POST': secret_key_from_form = request.POST.get('sk','0') secret_key_from_session = request.session.pop("secret_key",'1') if secret_key_from_form != secret_key_from_session: return render(request,"404.html",{}) else: # process the form normally form = MyForm(request.POST,request.FILES) if form.is_valid(): # do something else: # do something else else: f = MyForm() secret_key = uuid.uuid4() request.session["secret_key"] = secret_key request.session.modified = True return render(request,"my_form.html",{'form':f,'sk':secret_key}) And here's a sample template: <form action="{% url 'my_view' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="sk" value="{{ sk }}"> {{ form.my_data }} <button type="submit">OK</button> </form> This set up has failed to stop double-submission. Specifically, one can go on a click frenzy and still end up submitting tons … -
Taggit default tag list
On the official documentation I saw that I can edit tags from the Admin page, but how can I do it automatically with a migration? I want that the user will havo to choose between a set of default tags which I set the first time I create the database. Thanks -
ValueError: could not convert string to float: in django in my models
I try to create a simple rest api with django but when i migrate my model i get this error : File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1789, in get_prep_value return float(value) ValueError: could not convert string to float: The joke is : i have no field of type FloatField() in my model !! So someone could be help me, i give you the code below Thk !! May be the problem could be come from the srializer.py but ... my_api/model.py : class Bucketlist(models.Model): """This class represents the bucketlist model.""" name = models.CharField(max_length=255, blank=False, unique=True,default="") date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.name) class Meta: """test for admin interface""" verbose_name_plural = "Ma list de courses" my_api/Serializer.py : class BucketlistSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON format.""" class Meta: """Meta class to map serializer's fields with the model fields.""" model = Bucketlist fields = '__all__' # == fields = ('id', 'name', 'date_created', 'date_modified') read_only_fields = ('date_created', 'date_modified') my_api/View.py : class CreateView(generics.ListCreateAPIView): """This class defines the create behavior of our rest api.""" queryset = Bucketlist.objects.all() serializer_class = BucketlistSerializer def perform_create(self, serializer): """Save the post data when creating a new bucketlist.""" serializer.save() my_api/Test.py … -
Django Integrity Error - NOT NULL constraint failed: zdorovo_page.category_id
While working with Django, I created an app which shows different categories. Click on any one of them it opens up a window showing all the pages related to it . On the same window you have the option to add a new page to that particular category. I am getting this integrity error type for a value of not null constraint failed error. I cannot comprehend this error. Please help me understand where am i going wrong . I have posted all the required scripts. models.py from django.db import models from django.template.defaultfilters import slugify class Category(models.Model): name = models.CharField(max_length=128, unique=True) slug = models.SlugField(blank = True, null= True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) def __unicode__(self): return self.title I am basically trying to add a page to an existing category. This is my add_page view views.py for add_page def add_page(request , category_name_slug): category = Category.objects.get(slug = category_name_slug) form = PageForm() if request.method == 'POST': form = PageForm(request.POST) if form.is_valid(): if category: page = form.save(commit = True) page.category = category page.views = 0 page.save() … -
formating a string and pass it to an URL in python
How can i append two different strings variable in a url. But this is not accepting def get_customer_action_by_target_group(self): payload = {"TargetGroupID": "%s" % self.TargetGroupID, "Date":"%s" % self.date, } if not self.TargetGroupID or not self.date: get_target_group_id = int(raw_input("Please provide the target Group id:")) get_date = (raw_input("Please provide the date as required:")) self.TargetGroupID = get_target_group_id self.date = get_date response = self.send_request(self.get_customer_action_by_target_group_url % self.TargetGroupID % self.date, json.dumps(payload), "GET") print response, response.text, response.reason return response -
Django query ORM to query based on primary key then get information from junction tables linked by foreign key
I have a table which has a primary key and I want to query that table on that primary key. This links to 2 junction tables who are foreign key linked to my first table. Can I access all of the information relating to this primary key from all of these tables: models.py: class Variant(models.Model): variant = models.CharField(max_length=60, primary_key=True) class VarSamRun(models.Model: sample = models.ForeignKey(Sample, on_delete=models.CASCADE, db_column='sample') variant = models.ForeignKey(Variant, on_delete=models.CASCADE, db_column='variant') run = models.ForeignKey(Run, on_delete=models.CASCADE, db_column='run') .... more attributes ... class ClinVarSamRun(models.Model: sample = models.ForeignKey(Sample, on_delete=models.CASCADE, db_column='sample') variant = models.ForeignKey(Variant, on_delete=models.CASCADE, db_column='variant') run = models.ForeignKey(Run, on_delete=models.CASCADE, db_column='run') .... more attributes ... I want to query VarSamRun with some variables such as: obj = VariantSampleRun.objects.filter(sample=sample, run=run).select_related('variant') but I dont seem to be able to get any of the information from ClinVarSamRun from this object I have also tried: obj = Variant.objects.prefetch_related('variant__clinicallyreportedvariant_set', 'variantsamplerun_set') but this again doesnt hold any VarSamRun or ClinVarSamRun object attributes How can I get these out?