Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'NoneType' object has no attribute 'is_relation'
this error comes up when I try to makemigrations for my python project. I don't where to look because i have 5 apps with 5 models and views ! does it have relation with attributes with the same name in different models ? (i added related_name='+' to avoid conflict names). My django version is : 1.11.3 this is what my terminal returned when i tried to makemigrations : Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/user/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/user/.local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 150, in handle loader.project_state(), File "/home/user/.local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 323, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "/home/user/.local/lib/python2.7/site-packages/django/db/migrations/graph.py", line 409, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "/home/user/.local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 92, in mutate_state operation.state_forwards(self.app_label, new_state) File "/home/user/.local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 149, in state_forwards delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' -
Django: Count of Objects in a Queryset does not return a value
I am implementing a template that needs to return a value that is a count of results returned in a queryset. I have the following pieces of codes. #views.py def score(request): if request.user.is_authenticated: context = { 'total_orders': OrganizationOrders.objects.filter(organization__organizationuserprofile__user=request.user.pk).count(), } return render(request, 'base.html', context) else: return render(request, 'base.html') I am calling the context value in my base template as follows: #base.html {{ total_orders }} It must be noted that the Queryset filter works just fine without the count method. The idea is to return Orders done for a specific Organization of the logged in user. Thanks in advance. -
Why can't I find a way to excape django's template tags?
I have a CharField called content in my model Address, where people can enter text. Suppose a person entered template tags like {%static '' %} or a template variable, etc in the CharField input. When I try to display the content with {%autoescape on%} {{address.content}} {%endautoescape%} It states that "Invalid block tag on line...". How do I stop the template engine from parsing the template tags in block.content which is stored in the database as it is? -
Django 1.8 migration error with postgres
I am new to Django and I am trying to create table in Postgre using Django(1.8) following is my model class class Student(models.Model): name = models.CharField(max_length = 50) degree = models.CharField(max_length = 50) numofsubs = models.IntegerField() namesofsubs= models.CharField(max_length = 50) details = models.CharField(max_length = 50) class Meta: db_table = "student" views.py def addStudent(request): student = Student(name = request.name, degree = request.degree , numofsubs = request.numofsubs , nameofsubs = request.nameofparams , details = request.details) student.save() print 'data saved' After these changes when I tried to run python manage.py migrate i got django.db.utils.ProgrammingError: permission denied for relation django_migrations following are the stack traces Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/core/management/init.py", line 338, in execute_from_command_line utility.execute() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/core/management/init.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in init self.loader = MigrationLoader(self.connection) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in init self.build_graph() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 180, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 60, in applied_migrations return set(tuple(x) for x in self.migration_qs.values_list("app", "name")) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/django/db/models/query.py", line 162, in iter self._fetch_all() File … -
Load 100k markers on google maps smoothly and fastly
I am working on a Django web application which requires loading of around 50k markers on google map. I have tried marker-clustering but it is too slow for this much number of markers. In my application, data is coming from google places API which is first stored in PostgreSQL, after that, it is being fetched in Django model. I have tried several solutions but none of them are working.As all markers are associated with some data including name, image, and so many other details as well. I have also tried loading markers using PostGIS, in which there is a request to return only markers within a given bounds but it is taking time while zooming and dragging the map and causing the map to freeze. I have read several questions and their solutions also but not working for me: Loading 100-200K markers on google map Best solution for too many pins on google maps I need to get the solution for this, if anyone here can help please comment your ideas. I need smoothness like this link: http://cyrilcherian.github.io/million-points-on-map/myMap.html Including that markers need to be fetched from the database and have associated hover and click function. -
Heroku Stack upgrade on Django App resulting in System crash on wkhtmltopdf
I have recently upgraded the stack from cedar to heroku-16 on a Django application hosted on Heroku. Since the upgrade I'm getting the following error when trying to create a pdf. Traceback: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 136. response = response.render() File "/app/.heroku/python/lib/python2.7/site-packages/django/template/response.py" in render 104. self._set_content(self.rendered_content) File "/app/.heroku/python/lib/python2.7/site-packages/wkhtmltopdf/views.py" in rendered_content 144. footer_filename=footer_filename) File "/app/.heroku/python/lib/python2.7/site-packages/wkhtmltopdf/views.py" in convert_to_pdf 103. return wkhtmltopdf(pages=[filename], **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/wkhtmltopdf/utils.py" in wkhtmltopdf 88. return check_output(args, stderr=sys.stderr, env=env) File "/app/.heroku/python/lib/python2.7/subprocess.py" in check_output 212. process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/app/.heroku/python/lib/python2.7/subprocess.py" in __init__ 390. errread, errwrite) File "/app/.heroku/python/lib/python2.7/subprocess.py" in _execute_child 1024. raise child_exception Exception Type: OSError at /manage/pharmacy/prescriptions/59519/print/ Exception Value: [Errno 2] No such file or directory Since this was working on the previous stack I do not understand what could be the cause of the error. Any help would be most welcome? -
How to use if condition in Django inside {% block content %}
I am trying to apply if condition inside {% block content %} by using the following code: {% for item in execution_log %} {% if item.description == 'Set On' %} #Condition {% elseif item.description == 'Set Off' %} #Condition {% elseif item.description == 'FFMPEG error' %} #Condition {% endif %} {% endfor %} But I am not getting any output. Is the syntax for the if condition correct? -
django url tag, not a valid view function or pattern name
I tried to link an anchor to another page in Django. But I get the error " Reverse for 'animals.all_animals' not found. 'animals.all_animals' is not a valid view function or pattern name." I tried several ways to do it.. no success. I have one app called animals and Im tyring to display the list of animals in the by clicking an anchor on the homepage. I attached here my Django files. from django.shortcuts import render, get_object_or_404 from .models import Animal def animal_list(request): animals = Animal.objects.all() return render(request, 'animals/animal_list.html', {'animals': animals}) // and here is the html {% for animal in animals %} <h1>{{animal.species}}</h1> <p>{{animal.description}}</p> {% endfor %} from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.animal_list, name='all_animals'), url(r'^(?P<pk>\d+)/$', views.animal_detail, name='all_details'), ] {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Animals Site</title> <link href="{% static 'css/base.css'%}" rel="stylesheet"> </head> <body> {% block content %} <nav> <a href="{% url 'animals.all_animals'%}">Animal List</a> </nav> <a></a><h2>I love cats!</h2> {% endblock content %} {% block listbar %} <ul> <li>Sphynx</li> <li>Catto</li> <li>Bengal</li> </ul> {% endblock listbar %} </body> </html> {% block listcolor%} <style> h2{ font-family: 'Calibri'; color: blue; } </style> {% endblock listcolor% -
Getting error while running app over https using Python and Django
I need one help. I need to test my APP over https but here I am getting the below error while running my App using Python. This site can’t provide a secure connection 127.0.0.1 sent an invalid response. ERR_SSL_PROTOCOL_ERROR I am making one APP using Python and Django and wanted to run over the https. My settings.py is given below. settings.py: """ Django settings for carClinic project. """ import os """ Build paths inside the project like this: os.path.join(BASE_DIR, ...) """ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) """ SECURITY WARNING: keep the secret key used in production secret! """ SECRET_KEY = 'e8rq8bj5=w6cyiw&37s2kdys&$mg9m8agh@-%c6_+-jpu-21y=' """ SECURITY WARNING: don't run with debug turned on in production! """ DEBUG = False ALLOWED_HOSTS = ['*'] """ Application definition """ INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bookingservice' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'carClinic.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'carClinic.wsgi.application' """ Database """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } """ Password validation """ AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
Django Models Task
I'm writing a simple to do list whit Django framework. This is the model of Task. class Task(models.Model): title = models.CharField(max_length=250) description=models.CharField(max_length=250) assigned_to = models.ManyToManyField(User) creation_date =models.DateField(auto_now=True) due_date =models.DateField(blank=True, null=True) completed = models.BooleanField(default=False) parent_task=models.ForeignKey(Task) list = models.ForeignKey(List) I want to create subtasks. But when I migrate occurred this error: parent_task=models.ForeignKey(Task) NameError: name 'Task' is not defined -
Django - Calculate Average Score Using Multiple JOINs
I am trying to calculate the average score for each student using Django ORM. Here are my models: class Student(models.Model): name = models.CharField(max_length=2000) birth_date = models.DateField() class Course(models.Model): name = models.CharField(max_length=250) units = models.IntegerField() class StudentScore(models.Model): student = models.ForeignKey(Student) course = models.ForeignKey(Course) score = models.FloatField() For each student, the average score is calculated as: sum(score * course_units) / sum(course_units) I need to get the student ID vs. average score as output. Here is the equivalent SQL query (assuming the Django app name is 'dummy'): select ss.student_id, sum(ss.score * c.units) / sum(c.units) from dummy_studentscore ss join dummy_student s on s.id = ss.student_id join dummy_course c on c.id = ss.course_id group by ss.student_id How can I achieve the same using Django ORM API? -
Django site not working on port 8000 on ubuntu server. using nginx and gunicorn
I have a public server with public ip address: 52.178.148.115 I have a domain (4xcme.com) pointing to this ip address and it works just fine with the following nginx configuration: server { listen 80; server_name 4xcme.com; return 301 $scheme://www.4xcme.com$request_uri; ssl on; ssl_certificate /etc/nginx/ssl/4xcme/ssl-bundle.crt; ssl_certificate_key /etc/nginx/ssl/4xcme/STAR_4xcme_com.key; ssl_prefer_server_ciphers on; } server { listen 80; server_name www.4xcme.com; ssl on; ssl_certificate /etc/nginx/ssl/4xcme/ssl-bundle.crt; ssl_certificate_key /etc/nginx/ssl/4xcme/STAR_4xcme_com.key; ssl_prefer_server_ciphers on; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/fxnetadmin/royalexc; } location / { include proxy_params; proxy_pass http://unix:/home/fxnetadmin/royalexc/royalexc.sock; } } and the following gunicorn config: [Unit] Description=gunicorn daemon After=network.target [Service] User=fxnetadmin Group=www-data WorkingDirectory=/home/fxnetadmin/royalexc ExecStart=/home/fxnetadmin/royalexc/royalenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/fxnetadmin/royalexc/royalexc.sock royalexc.wsgi:application [Install] WantedBy=multi-user.target I developed another website using django which I successfully host on the same server but this time without using a domain. instead i host this site directly on 52.178.148.115 with the following nginx config: server { listen 80; server_name 52.178.148.115; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/fxnetadmin/omefx; } location / { include proxy_params; proxy_pass http://unix:/home/fxnetadmin/omefx/omefx.sock; } } This second site has a similar gunicorn config to the first. both sites work just fine. navigating to 4xcme.com goes to the first site and 52.178.148.115 points … -
Django Unittest run into an error (table does not exist)
I try to run unittests in django. from django.test import TestCase as djangoTestCase class TestStringMethods(djangoTestCase): ... some tests... The app in listed at the settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_jwt', 'heatingControll', 'mainControll', 'authControll' ] If I run the command python manage.py test and I receive the error : django.db.utils.ProgrammingError: (1146, "Table 'test_homecontrolsystem.heatingcontrol_heatingmapping' doesn't exist") I also receive this error by running the command ' python manage.py test heatingControl` How can I fix this? I read the django-doc without success. Stacktrace C:\Users\...\SRC\HomeControllSystem\homeControllSystem>python manage.py test --- STARTUP CONFIG -- RUN --- JETZT SOLLTE DER PROZESS STARTEN UM DIE HEIZUNG NACH DEM RESTART ZU AKTIVIEREN --- STARTUP CONFIG -- FINISH --- Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_homecontrolsystem'; database exists") Type 'yes' if you would like to try deleting the test database 'test_homecontrolsystem', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\Program Files (x86)\Python36-32\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\Program Files … -
django-rest-encrypted-lookup: "Incorrect type. Expected json encoded string value, received str."
I wanted to build a create comment API. The comment model have a friend field, This is field is foreign key from User model. I use django-rest-encrypted-lookup library to encrypt foreign key id to create a comment, but the following error occurred. I need help, thank you! HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "friend": [ "Incorrect type. Expected json encoded string value, received str." ] } curl -X POST -H "Content-Type: application/json" -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6Im15c3lkbmV5bWFybGluQGdtYWlsLmNvbSIsImV4cCI6MTUwMjA5NDgxNywiZW1haWwiOiJteXN5ZG5leW1hcmxpbkBnbWFpbC5jb20iLCJvcmlnX2lhdCI6MTUwMjA5NDUxN30.YdErA8yXvsJD590OmL65XZj8OY_Pb-kSRBWhlC7s0v8" -d '{ "comment": "Test", "principal_investigator": "p7dvdkcokzksrdx5e4epmomnpq" }' http://localhost:8000/api/comment/create/ model.py: comment = models.CharField(max_length=30, verbose_name='Title') owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name='Owner', related_name='owner') friend = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name='friend', related_name='friend') serializer.py class CommentCreateSerializer(EncryptedLookupModelSerializer): class Meta: model = Title fields = ('id', 'comment', 'owner', 'friend') views.py class CommentCreateAPIView(CreateAPIView): serializer_class = CommentCreateSerializer permissions_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(manager=self.request.user) -
Web app based on user authentication and interactive database
This is more a conceptual question rather than a practical question: I need to delevop a website / web application where users sign up and get access to content that's specific for each of them. The content will be stored in a database and they will be able to interact with it, modify it, duplicate it and so on. This content will be then passed to an electronic cpu. Since I'm not an expert by any means but I really need to develop this kind of application so that I can effectively propose my idea at work, I was wondering: do you think the best solution would be to set up a different database for each user who signs up? is it possible to set up a system who automatically creates a database for each user when the user signs up? Is all of the above extremely complicated or rather feasible in Django? Thank you in advance! -
The LOGGING set is not working in django
The django logging document say: django¶ https://docs.djangoproject.com/en/1.11/topics/logging/ django is the catch-all logger. No messages are posted directly to this logger. so I change the django logger in setting.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/var/log/django/access.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } and in my view.py logger = logging.getLogger(__name__) logger.error("hello") But There is no log in /var/log/django/access.log,The log in still on console. Who Can tell me ,why -
How to add Pagination in a Non-Generic DRF View/Viewset
Prologue: I have seen this question arising in more than one posts: Django Rest Framework - APIView Pagination Pagination not working in DRF APIView and can also be applied here: Combine ListModelMixin with APIView to show pagination I have composed an example on SO Documentation to unify my answers in the above questions but since the Documentation will get shutdown on August 8 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and transform my example to a self-answered post. Of course I would be more than happy to see any different approach as well!! Question: I am using a Non Generic View/Viewset (eg: APIView) on a Django Rest Framework project and I cannot add pagination to my get method results. I have tried to override the aforementioned get method as follows: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger class ItemsAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): """ Return a list of all items of this user. """ reply = {} page = request.GET.get('page') print ('page is', page) try: products = BaseItem.objects.owned_items().filter(owner=request.user) reply['data'] = OwnedItemSerializer(products, many=True).data items = BaseItem.objects.filter(owner=request.user) paginator = Paginator(items, 1) items_with_pagination = paginator.page(page) if page is not None: reply['data'].extend( ItemSerializer(items_with_pagination, many=True).data ) … -
How to structure nested categories in django models
I am developing a online shopping cart project, and in product-catalog-app I am little bit stumbled upon how to structure categories, for example, the following sequence: MEN-> FOOTWEAR-> SPORTS SHOES -> SOME BRAND (NIKE)-> ACTUAL PRODUCT. As you can see the depth is 5. Is it a good design to make sub sub sub... categories inside each level class Category: pass class SubCategory: category=models.ForeignKey(Category,...) ... class SubSubCategory: category=models.ForeignKey(SubCategory,...) ... class BrandOrSmthEle: category=models.ForeignKey(SubSubCategory,...) ... class Product: category=models.ForeignKey(BrandOrSmthEle,...) ... -
-Django- Got "Cannot assign "u'Wing'": "Truck.MODEL" must be a "MODEL" instance" when creating new object to database
models.py: class MODEL(models.Model): ModelName = models.CharField(max_length = 128, unique = True) URL_Slug = models.SlugField(unique = True) ... class Maker(models.Model): maker = models.CharField(max_length = 128, unique = True) URL_Slug = models.SlugField(unique = True) ... class Truck(models.Model): MODEL = models.ForeignKey(MODEL) CarID = models.CharField(max_length = 10, unique = True, null = False) Maker = models.ForeignKey(Maker) year = models.IntegerField(default = 0) def __unicode__(self): return self.CarID forms.py: class MODELForm(forms.ModelForm): ModelName = forms.CharField(max_length = 128, help_text = 'Enter the NEW model name') URL_Slug = forms.SlugField(widget = forms.HiddenInput(), required = False) class Meta: model = MODEL fields = ('ModelName', ) class MakerForm(forms.ModelForm): maker = forms.CharField(max_length = 128, help_text = 'Enter the NEW maker') URL_Slug = forms.SlugField(widget = forms.HiddenInput(), required = False) class Meta: model = Maker fields = ('maker', ) class TruckForm(forms.ModelForm): MODEL = forms.CharField(max_length = 128, help_text = 'Enter the NEW model name') CarID = forms.CharField(max_length = 10, help_text = 'Enter the NEW truck ID') Maker = forms.CharField(max_length = 128, help_text = 'Enter the NEW maker') year = forms.IntegerField(help_text = 'Enter the year of production') class Meta: model = Truck fields = ('MODEL', 'CarID', 'Maker', 'year') views.py: def add_Truck(request): form = TruckForm() if request.method == 'POST': form = TruckForm(request.POST) if form.is_valid(): form.save(commit = True) return index(request) … -
How to use django template in AMP
I want to create an AMP version of the web page using Django as backend. The problem that I am facing is that I cannot use Django Template in AMP templates/pages. If anyone has any experience in using Django and AMP together, please enlighten my path. Thanks in advance -
Django datetime displays None with MySQL
I have developed a Django App on Ubuntu server with Apache and MySQL and everything worked fine. Recently, I was said that I need to migrate to Windows because we won't support Ubuntu anymore. I am migrating from Ubuntu 16 .04 to a Windows Server 2012 r2. It was pretty straightforward at first. I export sql file from Ubuntu. On Windows tables were created by importing sql file. Everything it's working fine. Almost everything. Datetime displays None, despite MySQL has a value different of None. I read that you need to import time_zone tables on Windows, so I downloaded and imported it, with no results. I changed the mysql time_zone variable on Windows to the same time_zone I had in the Linux server. No results. Fields are DATETIME(6) on both MySQL servers. The only thing is that Windows Server it's in a different time_zone (Europe/London) while Ubuntu Server was in Europe/Madrid. But I don't know what to do. Any suggestions? Thanks in advance! -
Setting null date field in django JSON API REST from Javascript
I'm trying to clear a date field through a REST API call in Django from Javascript. When running my tests with mock HTTP calls from Django-to-Django it successfully empties the date field: data = { 'data': { 'type': 'items', 'attributes': { 'due_date': None, } } } However attempting to do the same thing from Javascript with a Null does not seem to work. The server returns 200 OK but the item still has the original date. Instead of clearing the date field it's simply ignoring the Null. Is there a different way of doing it through JS? Cheers -
view rendering issue with ajax call in django
I am trying to create a search form in django with ajax.Form is using the GET request.Ajax call is working fine,now main problem is with the Django View.I am unable to display results in django template section. Here is my code: ajax call: $("#search-form").on("submit",function(e){ e.preventDefault(); var form_data = $("#search-form").serialize(); $.ajax({ url : '/url', data : form_data, success : function(data){ $("#results").html(data) } }); }); DJango Template(Search.html) {% block course_nav %} {% include "./navbar.html" with active_link='jobs' %} {% endblock %} {% block SearchForm %} <div class="row"> <form method="GET" id="search-form" action=""> {{ form }} <button class="btn btn-primary search-btn">Search</button> </form> </div> {% endblock %} {% block SearchList %} <div class="row"> <div id="results"> </div> </div> {% endblock %} Views def url(request): query = 'www.api-url.com' values = [request.GET.get(p) for p in ['title', 'location']] params = ['q', 'l'] for i, value in enumerate([v for v in values if v]): query += "{}{}={}".format("&" if i else "", params[i], value) response = urllib.request.urlopen(query).read() context = json.loads(response) return render(request, 'app-name/search.html', {'response': context['results']}) I understand its very small problem but I need some help regarding the rendering of template using ajax in django. -
How can I access dajngo model property from view?
I have a django model: class DebtRequest(models.Model): from_user = models.ForeignKey(User, related_name='debt_requests_from_user') to_user = models.ForeignKey(User, related_name='debt_requests_to_user') paying_user = models.ForeignKey(User, related_name='debt_requests_paying_user') receiving_user = models.ForeignKey(User, related_name='debt_requests_receiving_user') amount = models.FloatField() currency = models.CharField(max_length=10, default="USD") description = models.CharField(max_length=100, blank=True) date_incurred = models.DateTimeField(default=timezone.now) deadline = models.DateTimeField() payed = models.BooleanField(default=False) overdue = models.BooleanField(default=False) created = models.DateTimeField(default=timezone.now) @property def time_since_created(self): return (timezone.now() - self.created).total_seconds() The time_since_created property returns the time in seconds since the model instance was created, however I dont know how to access this from my view. How would I access this from my view? -
where can i get an example using for django logging?
I am learning django logging in django document https://docs.djangoproject.com/en/1.11/topics/logging/ I can see where to setting logging,but I can not find how to use logging in the view.py. This is not effective in the view.py logger = logging.getLogger(name) Who can tell me where can I get a whole example about django logging