Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run python on a Godaddy shared server with cpanel?
Let me start off by saying that I know this is not the preferred way to run python, but I have had this website for several years and am looking to add additional functionality. If I try to move the site to a new host and server setup, I am afraid I will mess everything up. I am using Godaddy shared server for my website, and I access it using cpanel. The website is a Wordpress blog but also has a few tools I built using PHP and SQL database to store the output. I want to create a chatbot using Python but from what I understand, I can't use Django on a shared Godaddy server. Is there a way for me to run Python scripts given my limitations? Is the best alternative for me to start a second server and build an API to process the conversation and send it back to my current website? -
HTML - Change color of text depending on value with JS
I'm creating a table displayed in HTML with Django. I want to change the number's color to red when the number is negative, and to green when the number is positive. I know I need to use JS for this but I could not make it work. Any help will be greatly appreciated !! Here is my Django HTML template : {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'WalletJournal/style.css' %}" /> <div id="container"> <h1>{{ Transaction.TransactionDateTime }}</h1> <table> <tr> <th>TRANSACTION AMOUNT</th> <th>BALANCE AFTER TRANSACTION</th> <th>TRANSACTION COMMENT</th> </tr><tr> <div id="TransactionAmount"><td style="font-family:'Arial',serif;font-size:10pt">{{ Transaction.TransactionAmount }}</td></div> <td style="font-family:'Arial',serif;font-size:10pt">{{ Transaction.BalanceAfterTransaction }}</td> <td style="color:white">{{ Transaction.TransactionComment }}</td> <script> var el = document.getElementById('TransactionAmount'); if(el<0) { el.addClass += "red"; } else { el.addClass += "green"; } </script> </tr> </table> <h2>Feel free to contact me !</h2> </div> And the classes I created in my CSS : .red { color:#FF0000; } .green { color:#33FF3C; } I tried creating some JS code from examples I found around the web but something must be wrong. My goal is to check if the number TransactionAmount is negative or positive, and adjust the color accordingly. I made the TransactionAmount div to be able to use it with getElementById... <script> var el = document.getElementById('TransactionAmount'); if(el<0) … -
Getting Django to run script with parameters?
I'm having trouble getting Django to run a Tweepy script with parameters. I seem to be able to get the script to run print statements when I start the server and create an instance, but I'm having a hard time getting it to take in a tag from the HTML input. HTML Button: <div class="input-field inline"> <label for="User">Enter a term</label> <form action = "" method = "post"> {% csrf_token %} <input id="Country" type="text" name="Country" maxlength="100" required value="{{ tag }}" /> <button class="btn waves-effect red" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </form> </div> Views.py from django.shortcuts import render from .forms import GetTweets from . import live # Create your views here. #Index by Kenny P def index(request): context = {} return render(request, 'visualize/index.html', context) #Tweets by Kenny P. Tweet will return the tweets def Tweets(request, tag): #Terms we want displayed go here! print 'IN!!!' country = live.GetTweets(tag) if request.method == 'POST': render_data = GetTweets(request.POST) if render_data.is_valid(): info = request.POST['tag'] tw = live.GetTweets(render_data.cleaned_data['Country']) else: render_data = GetTweets(tag) param = 11111 #Placeholder,do we need to return something in this place? return render(request, 'visualize/index.html', param) forms.py from django import forms #Search for the tag class GetTweets(forms.Form): user = forms.CharField(label='User', max_length=30) and finally, the (temporary) … -
Output nested list to xlsx using Django
I have a complex nested list of models that looks like this: hierarchy_tree = ['0000', 'hierarchy' [['0000-22', 'hierarchy2', [['0000-33', 'hiearchy3', [['0000-44-4444', 'hiearchy4', [['0000-55-5555-55', 'hiearchy5', []]]]]]]]]] I am able to easily display this in a template using dot notation - example: {% for hierarchy in hierarchy_tree %} <tr class="item" data-id="{{system.0}}" data-parent=""> <td> {{hierarchy.0}} </td> <td> {{hierarchy.1.genericname}} </td> Now I am trying to output this to an .xlsx file but I cannot figure out how to pass all of the levels of this list? How can I do the same thing that I did in the template to pass this list to excel? I have tried the following which will return the 1st list but throws an error (ValueError at /post/1/export/hierarchy/ - cannot covert(my passed in list)to excel) for the sublists because of the way that they are nested I believe. for r in hierarchy_tree: ws.append(r) I have also tried and failed repeatedly to access the sublists using other methods. So bottom line I need to figure out how to access and pass the values for the sublists - any ideas or help will be greatly appreciated? Thank you -
Should I create a model or just use a string
I'm writing a database (using django) and I can either use a string (max 4 chars) in a few places or I can create a model and reference it in those places. I've looked and I can't find good discussion on the merits of either solution. Because this database is going to be quite large, what solution scales better both in performance and size? Thanks! -
Django filtering AND loop in a Django on M2M field
I have a list of IDs I need to query and filter (using AND) in Django. I would like to use something along the lines of example 2 below but it gives incorrect results 0. The models are simple, Many Products can have Many Tags. What is wrong with example 2? Correct Results Example 1: q = Product.objects.all() for id in _list_of_ids: q.filter(tags__id=id) Example 2: Incorrect results but seems better (edited for brevity) ... for id in _list_of_ids: q = Q(tags__id=id) # apend q here etc # q = (AND: ('tags__id', 1), ('tags__id', 2)) Products.objects.filter(q) -
In Django, how to retrieve user's selection from database?
I am doing a Django project. And here is my view.py def choose_major(request): if request.method == "GET": form = MajorForm(request.GET) if form.is_valid(): major_program = request.GET["major_program"] major_obj = Major.objects.get(major=major_program) major_obj.save() return render(request, "major.html", {"form":form}) My question is: how to retrieve the value of variable major_program outside the function choose_major? Thanks for your help! -
Use wsgi on web service
I create a web service SOAP by soaplib and, it's working fine But I like to add file wsgi on my web service SOAP. This is my File WSGI : #!/usr/bin/env python from wsgiref.simple_server import make_server from cgi import parse_qs, escape html = """ <html> <body> <form method="get" action=""> <p> Age: <input type="text" name="age" value="%(age)s"> </p> <p> Hobbies: <input name="hobbies" type="checkbox" value="software" %(checked-software)s > Software <input name="hobbies" type="checkbox" value="tunning" %(checked-tunning)s > Auto Tunning </p> <p> <input type="submit" value="Submit"> </p> </form> <p> Age: %(age)s<br> Hobbies: %(hobbies)s </p> </body> </html> """ def application (environ, start_response): # Returns a dictionary in which the values are lists d = parse_qs(environ['QUERY_STRING']) # As there can be more than one value for a variable then # a list is provided as a default value. age = d.get('age', [''])[0] # Returns the first age value hobbies = d.get('hobbies', []) # Returns a list of hobbies # Always escape user input to avoid script injection age = escape(age) hobbies = [escape(hobby) for hobby in hobbies] response_body = html % { # Fill the above html template in 'checked-software': ('', 'checked')['software' in hobbies], 'checked-tunning': ('', 'checked')['tunning' in hobbies], 'age': age or 'Empty', 'hobbies': ', '.join(hobbies or ['No Hobbies?']) } … -
Why jquery change method don't works well?
I have a problem with two checkbox, the problem is that I have two categories Venta and Renta So if I check Venta or Renta or both the method works fine, but if I uncheck for example Renta the method don't work correctly, So I uncheck the two categories and the code works fine, but I don't understand Why or Where is my problem This is my jquery code: $(".venta").change(function () { if (this.checked) { $(this).val('1'); Visualizar_Unidades(0,0,0); } else{ $(this).val('0'); Eliminar_Unidades(); } }); $(".renta").change(function () { if (this.checked) { $(this).val('1'); Visualizar_Unidades(0,0,0); } else{ $(this).val('0'); Eliminar_Unidades(); } }); -
Ajax call in Django Rest Framework using array
I'm new to Django Rest Framework,running v. 3.5.4 (Django 1.10.6) and I have implemented a simple model (Test) and its ModelSerializer. This model has a manyTomany relationship with another one, but this is not the problem right now. The thing is that I need to pass an array of ids from my ajax call, to add to my manytomany relationship. Ajax call is like this: data = { address: 'foo' owner: [1,2] } ajax = $.ajax({ type: "POST", url: url, data: data, dataType: "json", success: function(res){ console.log(res) }, error: function(error) { console.log(error,'erro') } }) My view is like this: class Test(APIView): def post(self, request, format=None): print(request.data) print([(x,y) for x,y in request.data.items()]) serializer = TestSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So, the print outputs from my view are the problem: Output from print(request.data) is <QueryDict: {'address': ['foo'], 'owner[]': ['1', '2']}> So far so good! Output from print([(x,y) for x,y in request.data.items()]) is [('address', 'foo'), ('owner[]', '2')] Whaaaaat? So, the array became a string with the last item only. What happened? Apart from that, the is.valid() method seems to erase the array. I made a custom create method in my serializer: class TestSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() owner = … -
Association of new records with a particular object
I have 'project_list' and 'project_detail' pages. Inside 'project_detail' page I have button which redirect user to 'project_members' page where they can add new members to current project. How to associate a new created members with the current project. I am little bit confused with view. Whats the best way to realise it? models.py: class Project(models.Model): ***FIELDS*** members = models.ManyToManyField(User, through='Membership',) ROLE_CHOICES = ( ('manager', 'Manager'), ('developer', 'Developer'), ('business_analyst', 'Business analyst'), ('system_analysts', 'System analysts'), ) class Membership (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) project = models.ForeignKey(Project, on_delete=models.CASCADE) role = models.CharField(max_length=20, choices=ROLE_CHOICES,) forms.py: class ProjectMembersForm(forms.ModelForm): class Meta: model = Membership exclude = ('project',) def __init__(self, *args, **kwargs): super(ProjectMembersForm, self).__init__(*args, **kwargs) self.fields['role'].choices = tuple(choice for choice in ROLE_CHOICES if choice[0] not in ['manager']) urls.py: urlpatterns = [ url(r'^project/(?P<slug>[-\w]+)/$', project_detail, name='project_detail'), url(r'^project/(?P<slug>[-\w]+)/members$', project_members, name='project_members'), ] view.py: def project_members(request, slug): if slug: if request.method == 'POST': members_form = ProjectMembersForm(request.POST) if members_form.is_valid(): members_form.save() else: members_form = ProjectMembersForm(instance=request.user) return render(request, 'project/project_members.html', {'members_form': members_form,}) -
Django regex catching empty or space character
Why is the following regular expression in Python in Django? (r'^(?P<p>[a-zA-Z]+)/$') Anybody knows? -
Django: Template Doesn't Display Views Field
I'm having a problem with a template not displaying model fields sent from a view. The url.py correctly directs to the right html template. The view debug correctly prints the field contents (title and body) to the terminal, but the template is blank. The base.html works, displaying the bootstrap header and container. The page source is blank. If I replace the for...loop with Hi the text prints. Here are the files: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'), ] def detail(request, pk): story = Article.objects.get(pk=pk) print(story) print(story.body) print(request) context = {'story': story} return render(request, 'articles/detail.html', context) {% extends "base.html" %} {% block content %} <div> {% for story in stories %} <h1>{{ story.title }}</h1> {% endfor %} </div> {% endblock %} -
django frontend and backend seperation for security
I have written a web app in Django with usual Django project structure. At my company, they want to separate front end and backend on different servers. Frontend server will have internet access and backend will have a strong firewall and no net access. What I understand from this concept is, they want to separate back-end (view.py) from Django project to shared folder (shared with the back-end server). Is it possible to separate view.py file to the different folder and then import it to project? Also another question on the same topic. Does Django have good security or security ideas like this are required to protect against hacking? What measures should I take to ensure protecting my backend against hacking if I can't separate backend? (I have already implemented LDAP authentication, using CSRF tokens and all pages are protected by @login_required) -
How can i properly change the assigned secret key in a Django Web Application
So, I'm trying to deploy a Django Web App to production, but I want to change the secret key before doing so. I've attempted to generate a new key using a randomizing function and insert that new key in place of the old one. When I do so, I get an error that says the following: AttributeError 'module' object has no attribute 'JSONEncoder' ... Exception Location .../django/contrib/messages/storage/cookie.py in , line 9 I've deleted the browser cache and restarted the server, but the error persists. I've also attempted to change the key back, after deleting the browser cache and restarting, the error still persists. Any idea how to resolve this issue? -
Django filter using two conditions
I am developing a web app using django. Among with other tables, I have a table called GeneralContract, which has issueDate and Expiration Date as date fields. I want to find out the profit of an insurance agent in my case would get from these contracts between a period. For example, if the date range is 15 January 2015 - 25 February 2015 I would like to filter all GeneralContract objects who are issued ANY year between this period. (i.e. issueDate__month = Date1.month AND IssueDate.day_gte= Date1.day) AND (IssueDate__month = Date2.month AND IssueDate.day_lte = Date2.day) ?? I tried the following but it is not giving me the results I wanted and I am not sure if I am writing this in the correct syntax or if my logic is wrong. criterion1 = Q(issuedate__month=date1.month) criterion2 = Q(issuedate__day__gte=date1.day) criterion3 = Q(issuedate__month=date2.month) criterion4 = Q(issuedate__day__lte=date2.day) criterionA = criterion1 & criterion2 criterionB = criterion3 & criterion4 criterionC = criterionA & criterionB currentGenProfits = GeneralContract.objects.filter(criterionC, cancelled=False) Is this the right way of doing this filtering logic? -
heroku django fail at update_contenttypes
after 1st version of python/django application working on Heroku I realease 2nd version with some changes in db structures. I did migration form console, so it is not the problem. I suppose it is about python 3.6.0. 2017-03-10T19:35:11.562098+00:00 app[release.3161]: self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, 2017-03-10T19:35:11.562100+00:00 app[release.3161]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal 2017-03-10T19:35:11.562207+00:00 app[release.3161]: File "/app/.heroku/python/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 191, in send 2017-03-10T19:35:11.562203+00:00 app[release.3161]: **kwargs 2017-03-10T19:35:11.562337+00:00 app[release.3161]: response = receiver(signal=self, sender=sender, **named) 2017-03-10T19:35:11.562338+00:00 app[release.3161]: File "/app/.heroku/python/lib/python3.6/site- packages/django/contrib/contenttypes/management.py", line 158, in update_contenttypes 2017-03-10T19:35:11.562469+00:00 app[release.3161]: Type 'yes' to continue, or 'no' to cancel: """ % content_type_display) 2017-03-10T19:35:11.562477+00:00 app[release.3161]: EOFError: EOF when reading a line 2017-03-10T19:35:11.639589+00:00 heroku[release.3161]: Process exited with status 1 2017-03-10T19:35:11.645326+00:00 heroku[release.3161]: State changed from up to complete 2017-03-10T19:35:13.732917+00:00 app[api]: Release v18 command failed -
Trying to get Django running on a VPS but I keep running into "Invalid option to WSGI daemon process definition"
So, as the question says, I am trying to deploy Django onto a VPS, but I keep getting the error "Invalid option to WSGI daemon process definition". I have tried going to the mod_wsgi website and looking at the example code for daemon deployment but that doesn't help. I also tried using the Django website, but the instructions are not specific enough to my problem. The error logs also don't really show anything helpful, because they don't specify which part of the code has a syntax error, just which line! Here is the error message I get when I try to restart my apache server: Syntax error on line 34 of /etc/apache2/sites-enabled/example.com: Invalid option to WSGI daemon process definition. Action 'restart' failed. The Apache error log may have more information. Here is some relevant version information: Apache Version: 2.2.22 Ubuntu Version: 12.02 Python Version: 2.7.3 If there is anything else I should add, please let me know. I am also running python and Django in a virtual environment. Here is my apach2.conf file without comments: LockFile ${APACHE_LOCK_DIR}/accept.lock PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 <IfModule mpm_prefork_module> StartServers 1 MinSpareServers 1 MaxSpareServers 5 MaxClients 10 MaxRequestsPerChild 0 </IfModule> … -
Column with render_* method in django-tables2 not working
I have a table defined like this using django-tables2: class MyTable(tables.Table): action = tables.Column() class Meta: model = User fields = ['name', 'email'] def render_action(self, record): return 'Foo' But the render_action method is ignored and a -- is printed for every row instead. What am I missing? -
How to add a form by the HTML to a web service?
I create a web service SOAP by soaplib and everything, it's work fine. But I need to create a form by the page HTML to integrate on my web service and to submit the information from this form and adding on the database ..If it's possible then Can I do this (I need an example)? -
How to represent initial_dict in template when use django-formtool
I am using django-formtools, I've got the form data in previous page. def get_form_initial(self, step): if step == '1': prev_data = self.storage.get_step_data('0') first_name = prev_data.get('first_name','') logger.error("*** OUTPUT - prev_first_name *** : " + first_name) return self.initial_dict.get(step, {'first_name':first_name}) The log shows get first_name has succeeded. But I don't know how to show the 'first_name'. Please help me to show the previous data on next page. -
How in Django/Python can I ensure safety from WYSIWYG-entered HTML?
I would like to remove vulnerabilities to XSS / JavaScript injection in a web application where users are allowed to use an editor like CKEditor which allows arbitrary HTML (and whether my specific choice of editor allows arbitrary HTML or not, blackhats will be able to submit arbitrary HTML anyway). So no JavaScript, whether SCRIPT tags, ONCLICK and family, or whatever else. The target platform is Python and Django. What are my best options here? I am open to an implementation that would whitelist tags and attributes; that is to say I don't see it as necessary to allow a user to submit everything that you can build in HTML while only JavaScript gets removed. I am happy to have rich text with supported tag availability that can allow fairly expressive rich text. I would also be open to an editor that produces Markdown, and strip all HTML tags before the data is saved. (HTML manipulation seems simpler, but I would also consider Markdown-implemented solutions.) I also don't consider it necessary to produce a sanitized text if instead an exception is thrown that says that a submission has failed testing. (Ergo, lowercasing the string, and searching for '<script', 'onclick', etc. … -
Setting up logging and using it
I swiped from this stack over flow post: Simple Log to File example for django 1.3+ My logging settings: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'logging.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': "/var/tmp/swsite_logfile2", 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'swsite': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, } } But I must be doing something wrong in my views.py I did get the logger: import logging logger = logging.getLogger(__name__) And in my various methods I have: def globe(request): """Handles retrieving items to be displayed on the virtual globe.""" #print >>sys.stderror, ' WE ARE IN GLOBE' logger.debug('HELLLL') logger.debug('in globe! G') if request.method == 'POST': logger.debug('in globe post!') form = EntityGlobeForm(request.POST) .... .. .. . But I swear this works randomly and the file swsite_logfile2 is thrown not in var/tmp but this funky folder: sudo tail -f /var/tmp/systemd-private-92dfe35cbbca45a6a60e3450acd0d8d5-httpd.service-zUw75Q/tmp/swsite_logfile2 Additionally it only shows the two outputs HELL and in globe! G If I change what … -
return render_to_response on my development server
I am developing an app locally works fine under runserver. I deployed it to my main development server for testing. Which lives on a different ip under a /development url from my production server something like this: https://myprod-server.com now development: https://myprod-server.com/development I swear this is causing hell in my django urls and routes. I am testing code that works great on my local box but up there it returns the wrong json completely. So I turned on logging in my views.py (created a logger in settings.py) and couldn't find anything (really this logger just doesn't seem to be working great in general). Then got to wondering if it was my render_to_response. Under my local box and prod server I have a line in my views.py return render_to_response('swsite/sw_nga_globe.html', {'form':form }, context_instance=RequestContext(request)) I am wondering if this needs to be: return render_to_response('development/swsite/sw_nga_globe.html', {'form':form }, context_instance=RequestContext(request)) I did change it to development and got a template issue, so I am guessing this is relative to path and not url, but wondering if this is something causing that the complete wrong json object is returned after my views.py is the same on local box and was working right there and is not any different … -
Django - AngularJs Project Structure
After researching for the days I'm yet to decide what's the best structure for the AngularJs with Django.Many projects available on GitHub and tutorials on the net using angular files in Django project's static folder.This below structure is mostly followed in Angular 1 with Django. Project Name app project name templates static angular_app app1 app1.component.js app1.module.js app.js angular_templates (static templates for rendering in routes) manage.py In Angular 2 we have to use node server and mostly as far I saw with experienced angular developers who also worked with other backend technologies, they use this structure AngularJs Project app1 app1.component.js app1.module.js angular_templates (static templates for rendering in routes) app.js Django Project ( or any other backend project) app project name templates static manage.py Advantage of this project structure: We can use any other backend technology by replacing our backend project folder. Only API is dependent on backend project.The frontend is completely independent of the backend. So, the question is what's the best structure for the Django-Angular project? if the second option is good, we have to deploy our angular and Django code separately on the same domain? If yes how to do it ?