Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Full stack technologies to build python web/apps today ?
I am planning to build a python based webapp. What are the best python backend, JS and CSS frameworks I can use ? The webapp should render on the mobile too. This also opens up avenues for me to build hybrid mobile apps later (using mobile rendering) From my research, I am planning to use Django, Bootstrap and React JS. I haven't used React JS and bootstrap that much and wanted to know if my choices were correct or if there are better alternatives and if all of them work well together ? Also, what would make development fast ? I don't want to manually spin up EC2 machines and manage servers, any other alternatives there (I have heard of AWS Lambda, but not sure if its a good fit here) ? Any other resources that could help ? Thanks ! -
django 404 not found for URI with unicode characters on nginx and passenger
I'm trying to deploy a django app with phusion passenger and nginx. I use this combination because the server the app is hosted on runs plesk. I followed this article from the plesk support: https://support.plesk.com/hc/en-us/articles/115002701209-How-to-configure-Django-application-in-Plesk- The app is up and running but when i try to access an uri that contains a special character django returns a 404 error. http://example.com/kontakt/rückrufservice/ Request Method: GET Request URL: http://example.com/kontakt/r%25C3%25BCckrufservice/ I can't figure out if passenger or nginx escapes the characters but I think django expects the real unicode characters. How can I prevent this behaviour? -
why ' from. ' is a wrong syntax in django
how to import views succesfully without any synatax error i have already tried adding * , . my code is : from django.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), ]  please help me i want to run a simple poll app in django plz help with regards farman -
Linear chart distribute data according to hour
I have a Line Chart that has the following tags: Labels: ['0:00','1:00','2:00','3:00','4:00','5:00','6:00','7:00','8:00','9:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'] On the view, I retrieve information from a Model that gives Data from a User. This data has the following model: class Data(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.IntegerField(default=0) x = models.IntegerField(default=0) y = models.IntegerField(default=0) z = models.IntegerField(default=0) And on the view I prepare this information to be drawn on the Line Chart: variables = {'x': [], 'y': [], 'z': [], 'labels': []} for elem in Data.objects.filter(user=id): variables['x'].append(elem.x) variables['y'].append(elem.y) variables['z'].append(elem.z) variables['labels'].append(time.strftime("%H:%M:%S", time.localtime(elem.timestamp))) return render(request, 'interface/data.html', {'user_id': id, 'data': variables}) The problem is that I need to put that x,y,z information on the correct hour, because it only draws lines between both dots, and the points aren't on the correct hour. How I can put the x,y,z on the correct label? The Data model has a timestamp that provides the hour when this data was inserted. The idea is if a x,y,z was on 12:30, draw it between 12:00 and 13:00. -
Django and populating the JSONField
I'm having trouble using the JSONField. class Post(models.Model): json_d = JSONField() def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute('SELECT "Cltname" As Name, * FROM [dbo].[changes]') self.json_d = cursor.fetchall() This is what I'm working with and it's a bit hard to work with. Ideally I'd like some flexibility to control how the jsonfield is populated. Something like this for key in cursor.fetchall(): self.json_d2={key.Name:{"a": Key.1, "b":Key.2}} || self.json_d2={key.Name:[Key]} which would go row by row, associating the contents of the row in the form of a list or dictionary, with a primary key. Essentially I'm trying to customize a json object that I will pass to Vue.Js to organize the GUI. Is this approach sane? -
Server is working, but not able open in browser
I am working on a Django project where I am trying to use Jquery, I used a command-: python -m HTTP.server on my Windows PowerShell, server is started but when I trying to use the address http://0.0.0.0:8000 in my browser it is showing an error as follow- This site can’t be reached The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID my firewall is allowing access. please help. -
Passing django request object as arg or kwarg?
I'm not sure if this is a django/drf question or just a simple Python question with handling args/kwaargs.. I created a function that alters some fields on incoming JSON and I am trying to call it from a POST method in my views.py The issue is I need the function to handle a variable number of variables as well as the django request object and I am not sure how to handle this without getting an error. Here is my current code: in views.py def post(self, request, person, city, format=None): request = PreSerializer(request, person, city) serializer = CreateRecordSerializer(data=request.data) if serializer.is_valid(): PreSerializer function def PreSerializer(request, *args): if person = "david": person = 1: # Converts strings in JSON to foreignkey ID's if 'name' in request.data: person_record = get_object_or_404(Person, name=[request.data['person']) request.data["person"] = person_record.id if 'city' in request.data: city_record = get_object_or_404(City, name=request.data['city]) request.data["city"] = city_record.id return request I believe the issue is related to (request, *args) Error if person UnboundLocalError: local variable 'person' referenced before assignment -
How to use a custom context processor?
I have written my index action: def index(request): return render_to_response('app/index.html', { 'title': None, 'questions': build_questions(), 'blocks': build_blocks() }) But I need to pass an app name for all actions, so I have decided to move it in the context processor: context_processor.py: from asknow.settings import APP_NAME def global_processor(request): return {'app_name': APP_NAME} And in settings.py I connected it to all context processors: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', 'asknow.context_processor.global_processor' ], }, }, ] But it doesn't work, of course... What am I doing wrong? P.S. I use Django 1.11.6. -
Django Rest Framework - Test Client Post list of integers
I'm doing an app using django and I want to unit test my viewsets. I can test almost everything but, everytime I send an integer or a list to the viewset via API Client, in the viewset, the integer is converted to a string, therefore, that's a big fail for me :( Example - test file: body = { "age": 60 } client = APIClient() res = client.post(url, body, **headers, type='json') In the ViewSet: request.data { "age" "60" } -
How to query Django db from multiple columns
I have a django model to save financial data by year and month: Class Year(models.Model): year = models.IntegerField(choices=YEARS_CHOICE, blank=True, null=True) class Month(models.Model): financial_year = models.ForeignKey(Year, on_delete=models.CASCADE, default=2017) month = models.IntegerField(choices=MONTHS.items(), blank=True, null=True) Class FinancialData(models.Model): financial_year = models.ForeignKey(Year, on_delete=models.CASCADE) financial_month = models.ForeignKey(Month, on_delete=models.CASCADE) revenue = models.DecimalField(max_digits=7, decimal_places=2) costs = models.DecimalField(max_digits=7, decimal_places=2) So I have revenue and costs saved in db by year (2015-2017) and by month (Jan-Dec). I understad I can query db to get information for like march 2017: march_2017_data = FinancialData.objects.filter(financial_year = 2017, financial_month = 3) But how can I query data for multiple months like what if I want data from Jan-17 to March-17? jan_to_march_2017_data = FinancialData.objects.filter(financial_year = 2017, financial_month = 3) -
comment django errno 22
Hi i try add comment to my django blog procject and i get OSError: [Errno 22] Invalid argument: "C:\Users\marci\PycharmProjects\08.04\blog\templates\" so my urls path('<int:a_id>/addcomment', views.addcomment, name='addcomment'), views.py def addcomment(request, a_id): article = get_object_or_404(Articles,id=a_id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.article = article comment.save() return HttpResponseRedirect('/article/%s' % a_id) else: form = CommentForm() template = 'addcomment.html' context = {'form': form} return render_to_response(request,template,context) addcomment.html {% extends 'main.html' %} {% block article %} <form action="/article/{{ article.id }}/addcomment/" method="post" class="form-horizontal well">{% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-inverse" name="submit" value="Dodaj komentarz" /> </form> {% endblock %} thx -
Could not parse the remainder: Django + JS
I have a view, that transmits information from the database to the JC (the JC is in the HTML document) With the help of a loop, I add the elements to HTML while(i<ques){ if(x < max_fields){ x++; $(wrapper).append( ...value={{ teach.4' + i + '.0 }}... } i++; } In the first iteration, I should have {{teach.4.0.0}}, which is a value, but I get an error Could not parse the remainder: '' + i + '.0' from 'teach.4' + i + '.0' I've tried other options: break into several parts, assemble into a variable and substitute for the value var t1 = "{{ teach.4"; var t2 = ".0}}"; while(i<ques){ var link = t1 + i + t2; if(x < max_fields){ x++; $(wrapper).append( ...value='+link+'... } i++; } But in this case I was just text, instead of a variable -
Save data from form to Django admin database
>>> django.__version__ '2.0.4' I'm trying to create a simple form with name and email. I read this link - https://docs.djangoproject.com/en/2.0/topics/forms/ But I can't figure out how to save data from the form. forms.py class SubscribeForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) your_email = forms.EmailField(label='Your email', max_length=100) views.py def subscribe(request): """ View for form subscribe """ if request.method == 'POST': form = SubscribeForm(request.POST) if form.is_valid(): data_sub = form.save(commit=False) data_sub.save() else: form = SubscribeForm() return render(request, 'subscribe/subscribe.html', {'form': form}) But, data_sub = form.save is not right, if I right understand it because I use forms.Form. form.cleaned_data - I have to use to save data, but I don't understand how to do it. I hope for your help, thank you. -
Array content malformed when used on html
I have the following loop: for elem in Data.objects.filter(user=id): variables['labels'].append(time.strftime("%H%M%S", time.localtime(elem.timestamp))) This produces the following result: ['000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000', '000000'] But when I inspect the html this is the result: labels: [&#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;, &#39;000000&#39;] Why this happens? -
Ubuntu Nginx uwsgi socket not work
I am trying to set up my Django(2.0) project with nginx and uwsgi, but it just fails when running: uwsgi --socket :8001 --wsgi-file test.py which follows https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html it's failed, can not connect server , but uwsgi --http :8000 --wsgi-file test.py is ok here is my uwsgi log: (venv) ubuntu@VM-49-116-ubuntu:~/code/blog/mmxy$ uwsgi --socket :8001 --wsgi-file test.py *** Starting uWSGI 2.0.17 (64bit) on [Wed Apr 11 02:19:40 2018] *** compiled with version: 5.4.0 20160609 on 09 April 2018 17:37:14 os: Linux-4.4.0-91-generic #114-Ubuntu SMP Tue Aug 8 11:56:56 UTC 2017 nodename: VM-49-116-ubuntu machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/ubuntu/code/blog/mmxy detected binary path: /home/ubuntu/code/blog/venv/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3306 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address :8001 fd 3 Python version: 3.6.4 (default, Apr 10 2018, 00:02:46) [GCC 5.4.0 20160609] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized … -
Django add instance to QuerySet and randomise order
I'm using Django 2.0 I have following query string question = ChapterQuestion.objects.filter(chapter__course=course_learn.course).first() options = ChapterQuestion.objects.filter( chapter__course=course_learn.course ).exclude( pk=question.pk ).order_by('?').all()[:3] Now I want to merge question instance into options QuerySet and randoze their order to generate 4 options. How to add the instance to QuerySet of same model? -
mod_wsgi error with Django: Timeout when reading response headers from daemon process
I'm running Django 2.0.4 with mod_wsgi 4.5.20. I'm getting an error when I try to deploy a site to our dev environment at /parature. What's weird is that the site deployed at the root of the VirtualHost is responding as normal: [Tue Apr 10 13:34:08.998704 2018] [wsgi:error] [pid 65245] [client xx.yy.zz:65390] Timeout when reading response headers from daemon process 'parature-develop-https': /var/django/html/parature-develop/config/wsgi.py I can run the site via runserver with the virtualenv activated. It shouldn't be timing out, as I'm just trying to bring up the Django admin site. <VirtualHost *:443> SSLEngine On ServerName wrds-pub1-dev.example.com ErrorLog "|/usr/sbin/cronolog /var/log/httpd/errorlog/%Y/%Y-%m-wrds-pub1-dev-error.log" LogLevel info WSGIApplicationGroup %{GLOBAL} # The site I'm adding, which isn't working WSGIDaemonProcess parature-develop-https python-home=/var/django/virtualenvs/parature-develop request-timeout=600 WSGIProcessGroup parature-develop-https WSGIScriptAlias /parature /var/django/html/parature-develop/config/wsgi.py process-group=parature-develop-https <Directory /var/django/html/parature-develop/config> Require all granted </Directory> Alias /parature/static/ /var/django/html/parature-develop/static/ <Directory /var/django/html/parature-develop/static> Require all granted </Directory> # The site which has been and continues to work WSGIDaemonProcess django-wrds-dev-https python-home=/var/django/virtualenvs/django-wrds-dev request-timeout=600 WSGIScriptAlias / /var/django/html/django-wrds-dev/config/wsgi.py process-group=django-wrds-dev-https <Directory /var/django/html/django-wrds-dev/config> Require all granted </Directory> Alias /static/ /var/django/html/django-wrds-dev/static/ <Directory /var/django/html/django-wrds-dev/static> Require all granted </Directory> Alias /media/ /var/media/wrds-www/ <Directory /var/media/wrds-www> Require all granted </Directory> </VirtualHost> I feel like I'm missing something obvious, but can't see it. I've got a similar configuration in another VirtualHost with multiple Django projects … -
Sharing information in Django application
I have a very simple model that has data in it that I need to use in various places in my application: class Setting(models.Model): name = models.CharField() value = models.TextField() I'd like to be able to load this information into a dictionary once, then ship that data around my application, so I don't have to make duplicate calls to the database. My attempt at doing so was wrapping the logic in a module like so (the print statement is there for debugging): my_settings.py from myapp import models class Settings: __settings = {} def __init__(self): if(not self.__class__.__settings): print("===== Loading settings from table =====") qs = b_models.Setting.objects.all() for x in qs: self.__class__.__settings[x.name] = x.value def get(self, key, default=None): return self.__class__.__settings.get(key, default) def getint(self, key, default=0): return int(self.__class__.__settings.get(key, default)) Using this module would then look like the following: from my_settings import Settings settings = Settings() data = settings.get("some_key") This seems to work fine, but it has the drawback that the data is loaded once (and only once) at the initial instantiation. If any of the data in the settings database table should change, those changes won't be reflected in the corresponding dictionary held by this class. Is there a better approach here? I … -
Can't get Django to send me debug mail
I have a Django site that I have deployed to Heroku, and I'm having trouble getting it to send me error notifications via email. I've logged into the Heroku console and used django.core.mail.send_mail() to send emails, so I know it's configured to send correctly. I've got ADMINS and MANAGERS configured, and the django.middleware.common.BrokenLinkEmailsMiddleware Middleware so I should be getting emails whenever someone gets a 404 error on the page. I have the following Logging configuration in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' + 'pathname=%(pathname)s lineno=%(lineno)s ' + 'funcname=%(funcName)s %(message)s'), 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'simple': { 'format': '%(levelname)s %(message)s' } }, 'handlers': { 'mail_admins': { 'level': 'DEBUG', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, }, 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'testlogger': { 'handlers': ['console'], 'level': 'INFO', } } } What am I missing? -
Django Middleware keeps redirecting, visiting admin-site not possible
I followed a Django tutorial and wrote a Middleware class, to be precise its a "Login-Required"-Middleware so Users are just allowed to do some things on the website when they are logged in. The problem is that the middleware works as it should be but I can not visit the Django-Admin website anymore. Even after adding the admin-url to the exception list. He keeps redirecting me to the "normal login site". This is my middleware import re from django.conf import settings from django.shortcuts import redirect from django.contrib.auth import logout from django.urls import reverse EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') print (path) # if not request.user.is_authenticated(): # if not any(url.match(path) for url in EXEMPT_URLS): # return redirect(settings.LOGIN_URL) url_is_exempt = any(url.match(path) for url in EXEMPT_URLS) if path == reverse('logout').lstrip('/'): logout(request) if request.user.is_authenticated() and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated() or url_is_exempt: return None else: return redirect(settings.LOGIN_URL) This is the Login_EXEMPT_URLS in settings.py LOGIN_EXEMPT_URLS = ( r'^kalender/login/$', r'^kalender/logout/$', r'^kalender/reset-password/$', r'^kalender/reset-password/done/$', r'^kalender/reset-password/complete/$', r'^kalender/reset-password/$', r'^/admin/$', r'^admin/$', r'^/admin/login/?next=/admin/$', ) I also tried … -
Create Line Chart and populate with database information
I want to create a line chart on my html, and the information has to be from the database. This is the view: def data(request, id): return render(request, 'interface/data.html', {'user_id': id}) This user_id, is the primary key of the model User. This user has multiple 'Data'. The data model is the following: class Data(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.IntegerField(default=0) x = models.IntegerField(default=0) y = models.IntegerField(default=0) z = models.IntegerField(default=0) And this is the html: {% extends './default.html' %} {% block child_content %} <body> <h2 class="square_margin" style="text-align:center"> Información paciente: <strong> {{ user_id }} </strong> </h2> <!-- HERE GOES THE LINE CHART --> <form class="square square_margin"> <button class="btn btn-warning btn-md btn-block" formaction="{% url 'interface:modify' user_id %}"> Modificar Ajustes Paciente </button></form> </body> {% endblock %} I want to populate that line chart with the Data information of that User. On the X axis is going to be the time (Data has a timestamp). And the Y axis the acceleration, that is represented by x,y,z from the Data model. How I can do that with chart.js I need something like the following: -
show selected option when render posted form in django
I have tried to render a form with a ChoiceField like bellow : <div class="col-25"> <label for="category">Subcategory</label> </div> <div class="col-75"> <select name="category" id="id_category"> {% for x in FilterbyCategory.fields.category.choices %} <option value="{{ x.0 }}"{% if FilterbyCategory.fields.category.value == x.1 %}selected{% endif %}> {{ x.1 }} </option> {% endfor %} </select> </div> When I submit the form, I don't get the initial option selected. DO I have a problem here ? -
How to achieve wildcard search using haystack in django
I am currently working on haystack search in django. I met 2 problems, first, when I use 'Whoosh' engine, the search can only return the result that match exactly the same with my search key, for example if I type 'ABC', it cannot match 'ABCD' Secondly, how can I achieve wildcard search using haystack? For example, if I type'A*C', it can return 'ABC', 'ABCCC' 'AC' and so one. Or other method just to achieve the same result(Basically, return the result that contains the key word in same order) -
Django: disable error messages for required field on initial form view?
I've got a Django form that looks like this and allows users to make a choice: class ChoiceForm(forms.Form): candidate = forms.CharField(widget=forms.HiddenInput) CHOICES = ((True, 'Yes',), (False, 'No',)) choice_field = forms.ChoiceField(choices=CHOICES, required=True, widget=forms.RadioSelect) The template looks like this: <form id="pledge" action="/pledge" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.choice_field.errors }} {{ form.choice_field }} </div> {{ form.candidate }} <div class="form-actions"> <button type="submit" class="btn btn-primary" value="Submit">Submit your response</button> </div> </form> My view is like this: def pledge(request, candidate_hashkey=None): candidate = None if request.method == 'POST': # process input else: candidate = get_object_or_404(Candidate, pledge_hashkey=candidate_hashkey) form = PledgeForm({'candidate': candidate_hashkey}) context = { 'form': form, 'candidate': candidate } return render(request, 'frontend/pledge.html', context) The problem is that on the initial GET view, before the user chooses anything, the form appears with an error at the top: "This value is required". How can I disable this for the initial view? -
IIS Allow access to API only from mobile device
My API is django and running on IIS and the clients are either an android or ios device. From IIS logcats i can see that each request call has connection info like below : 2018-04-10 07:21:46 127.0.0.1 POST /login/ - 8080 - 123.45.678.910 Dalvik/1.6.0+(Linux;+U;+Android+4.3;+Google+Nexus+4+-+4.3+-+API+18+-+768x1280_1+Build/JLS36G) - 200 0 0 109 How can i restrict access from browsers or only allow request from mobile devices in IIS?