Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Aligning text when converting from html to pdf in django
After following a tutorial, I successfully was able to convert html to pdf, however, when trying to align text on the same line (half of it to the left and the other half to the right) it would not convert properly. The html file looks as follow: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> <style type="text/css"> body { font-weight: 200; font-size: 14px; } .header { font-size: 20px; font-weight: 100; text-align: center; color: #007cae; } .title { font-size: 22px; font-weight: 100; padding: 10px 20px 0px 20px; } .title span { color: #007cae; } .details { padding: 10px 20px 0px 20px; text-align: left } .hrItem { border: none; height: 1px; color: #333; background-color: #fff; } </style> </head> <body> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # </p> </div> <div> <div class='details'> Bill to: <span style="float:right">some text here</span> <br/> Amount: <br/> Date: <hr class='hrItem' /> </div> </div> </body> </html> The render_to_pdf function: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None The html file looks more than proper, but is not being converted properly in pdf. Aligning on separate lines does,however, convert normally to pdf … -
Running supervisord in AWS Environment
I'm working on adding Django Channels on my elastic beanstalk enviorment, but running into trouble configuring supervisord. Specifically, in /.ebextensions I have a file channels.config with this code: container_commands: 01_copy_supervisord_conf: command: "cp .ebextensions/supervisord/supervisord.conf /opt/python/etc/supervisord.conf" 02_reload_supervisord: command: "supervisorctl -c /opt/python/etc/supervisord.conf reload" This errors on the 2nd command with the following error message, through the elastic beanstalk CLI: Command failed on instance. Return code: 1 Output: error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /opt/python/run/venv/local/lib/python3.4/site- packages/supervisor/xmlrpc.py line: 562. container_command 02_reload_supervisord in .ebextensions/channels.config failed. My guess would be supervisor didn't install correctly, but because command 1 copies the files without an error, that leads me to think supervisor is indeed installed and I have an issue with the container command. Has anyone implemented supervisor in an AWS environment and can see where I'm going wrong? -
How to retrieve form data using AJAX in django
I know to save the form in Django using AJAX but don't know how to retrieve the form data from Django using AJAX. I need to retrieve the form data through return HttpResponse(jhjson, {'content_type' : 'application/json'}) instead of return render(request, 'task/mobileInventory.html', {'form': form}) View.py def get_try(request, sid): print (sid) member = get_object_or_404(TaskMaster, pk=sid) form = CreateTaskMaster(instance=member) return render(request, 'task/mobileInventory.html', {'form': form}) -
How to handle a js request that sends json data to django?
I basically want to implement a simple Form along with js in django. So for that a js request is been sent along with json data containing info from the form filled by the user but I am not able to parse the received json and am getting the following error - Error Traceback - http://dpaste.com/38NXD77 Any help would be appreciated. Thanking you in advance :) script.js function submit_add_participant() { // Retrieve Form Data here var formData = serializeArray(document.getElementById('add-participant-form')); add_name = formData[0].value; add_clgname = formData[1].value; add_sport = formData[5].value; add_city = formData[2].value; add_email = formData[4].value; add_mobile = formData[3].value; var add_gender = ''; if (formData.length > 6) { add_gender = formData[6].value; } if (add_name && add_clgname && add_sport && add_city && add_email && add_mobile && add_gender) { document.getElementById('add-participant-err-msg').style.display = 'none'; // Send Data to Backend // alert('Send'); newParticipant["data"].push({ "name": add_name, "gender": add_gender, "college": add_clgname, "sport": add_sport, "city": add_city, "email": add_email, "mobile": add_mobile }); // var csrf_token = getCSRFToken(); csrf_token = getCookie('csrftoken'); newParticipant["csrftoken"].push({ "csrfmiddlewaretoken": csrf_token }); alert(JSON.stringify(newParticipant)); var ourRequest = new XMLHttpRequest(); var url = "/add_participant/"; ourRequest.open("POST", url, true); ourRequest.setRequestHeader("Content-type", "application/json"); ourRequest.setRequestHeader("X-CSRFToken", csrf_token); // POST var sendParticipant = JSON.stringify(newParticipant); // alert(sendParticipant); // alert(data); ourRequest.send(sendParticipant); footer_display(5); // Obtain ourRequest.onreadystatechange = function() { // alert('Hello'); … -
Django: Message App
I'm trying to create a messaging app. Everything is working fine accept the fact I couldn't re-order users if request.user sends a message or vice versa. Here's what I tried, Here's the model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Here's what I tried in view to filter the User if conversation between any user & request.user occurred, def profiles(request): users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('receiver__first_name', 'receiver__id').annotate(Max('id')).order_by('-id__max') return render(request, 'chat/users.html', {'users': users}) Here's the template, {% for user in users %} <a href="{% url 'chat:messages' user.receiver__id %}">{{ user.receiver__first_name }}</a> {% endfor %} Here I can filter out the users but problem is either I can filter the senders or receivers not both of them depending upon the conversation as we see on social networks. How can I do that? -
I am not able to render existing Django App's in Mezzanine CMS?
Check the code there is main urls.py and there is one more urls.py for the app about us with the code views.py check out this, I am not able to render django app's in mezzanine cms, what I am missing. :- [About us- urls][1] [about us- views][2] [1]: https://i.stack.imgur.com/S3wQS.png [2]: https://i.stack.imgur.com/fEA09.png #URLS.py from __future__ import unicode_literals import mezzanine from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.views.i18n import set_language from aboutus import views from home import views from mezzanine.core.views import direct_to_template from mezzanine.conf import settings admin.autodiscover() # Add the urlpatterns for any custom Django applications here. # You can also change the ``home`` view to add your own functionality # to the project's homepage. urlpatterns = i18n_patterns( # Change the admin prefix here to use an alternate URL for the # admin interface, which would be marginally more secure. url("^admin/", include(admin.site.urls)), ) if settings.USE_MODELTRANSLATION: urlpatterns += [ url('^i18n/$', set_language, name='set_language'), ] urlpatterns += [ # We don't want to presume how your homepage works, so here are a # few patterns you can use to set it up. # HOMEPAGE AS STATIC TEMPLATE # --------------------------- # This pattern simply loads the index.html template. It … -
How to Upload file from ajax to django rest api?
I want to upload file via ajax to api but i couldn't get file url while fetching the file from ajax. Please look at the code below and give me a solution code for ajax call : $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(".add-content").submit(function(event){ event.preventDefault() var this_ = $(this) console.log(this_); var form = this_.serializeArray() // $.each(form, function(key, value){ // // }) var formData = this_.serialize() console.log(form); var fileSelect = document.getElementById('file'); console.log(fileSelect.value); var temp= { "content_name": form[1].value, "content_url": fileSelect.files[0], "employee": {{ id }}, "course": form[2].value } console.log(JSON.stringify(temp)); $.ajax({ url: "/api/content/create", data: JSON.stringify(temp), beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, method: "POST", contentType: "application/json; charset=utf-8", dataType: 'json', success: function(data){ console.log(data) }, error: function(data){ console.log("error") console.log(data.statusText) console.log(data.status) } … -
Django DateTimeField date filter not working
I have a DateTimeField named created_at in my model. I Would like to query the objects which are created today. From this question I have used the following query set, In [70]: today = datetime.datetime.today().date() In [72]: Business.objects.filter(created_at__date=today) Out[72]: <QuerySet []> It returns zero results. I have make sure that there is an entry in the database, which was created today. I know that I can also use Business.objects.filter(created_at__contains=today) But it yields results with a warning: django/db/backends/mysql/base.py:71: Warning: (1292, "Incorrect datetime value: '%2017-12-21%' for column 'created_at' at row 1") I'm using MySQL database. -
NoReverseMatch in Django 1.11
I know there are lot of questions already ask about this error but for some reason none of them work for me. What i am trying to do? I am trying to pass a variable from view ActivateAccount to another view result upon email confirmation. What is the problem? I am doing everything right according to docs and previously posted question about the same error but i still get this error: Reverse for 'result' with keyword arguments '{'test': 'Email confirmed successfully!'}' not found. 1 pattern(s) tried: ['(?P<test>[\\w-]+)/$'] caller view.py: def ActivateAccount(request, uidb64, token): test = '' if uidb64 is not None and token is not None: ... test = "Email confirmed successfully!" return HttpResponseRedirect(reverse('result', kwargs={'test': test})) urls.py: url(r'^(?P<test>[\w-]+)/$', views.result, name='result') receiver view.py: def result(request, test=None, *args, **kargs): data = {'msg': test} return JsonResponse(data) And i would also like to know why is there double backslash \\ in the regex ([\\w-]) instead of single in the error. As in my url i have a single \ ([\w-]). thanks for your time. -
How to go to a specific external URL from your API using Django?
I being new to Django is learning how to go to an external URL from my API, so I made a project and in that project made an app like 'linker' and in the views of app I wrote this code 1 # -*- coding: utf-8 -*- 2 from __future__ import unicode_literals 3 import urllib3 4 from django.shortcuts import render 5 from django.http import HttpResponse 6 # Create your views here. 7 8 def index(request): 9 http = urllib3.PoolManager() 10 r = http.request('GET', 'www.google.com') 11 return HttpResponse(r) Now this is the views.py, is the code right? -
Error when install psycopg2 on mac
When i try to install psycopg2 on mac using pip install -r requirements.txt I got error. Collecting psycopg2==2.6 (from -r requirements.txt (line 30)) Using cached psycopg2-2.6.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: could not determine PostgreSQL version from '10.1' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/r6/0rwq93rx6n59lbn8jrng11gm0000gn/T/pip-build-hat1f3jy/psycopg2/ I could not solve it.python3.4.3 mac10.12 could anyone suggest any solution? -
Custom the `on_delete` param function in Django model fields
I have a IPv4Manage model, in it I have a vlanedipv4network field: class IPv4Manage(models.Model): ... vlanedipv4network = models.ForeignKey( to=VlanedIPv4Network, related_name="ipv4s", on_delete=models.xxx, null=True) As we know, on the on_delete param, we general fill the models.xxx, such as models.CASCADE. Is it possible to custom a function, to fill there? I want to do other logic things there. -
uWSGI won't find a module that exists in all python installations
I am trying to run a Django app through uWSGI on a Raspberry Pi running Raspbian GNU/Linux 9 (stretch), it came with Python 3.5 from the distro and I compiled and installed Python 3.6 as an alternative. These are my current Python installations: Python 2: /usr/bin/python Python 3.5: /usr/bin/python3.5 Python 3.6: /usr/local/bin/python3.6 I also created a virtualenv based on python3.6 for my app located at ~/.virtualenvs. The problem is that the service complains about not being able to get the locale encoding: Fatal Python error: Py_Initialize: Unable to get the locale encoding Because of a missing module: ImportError: No module named 'encodings' However, if I start my virtualenv and issue: import encodings It works completely fine: >>> import encodings >>> encodings <module 'encodings' from '/home/ariel/.virtualenvs/you2ogg/lib/python3.6/encodings/__init__.py'> This is how my service.ini file looks like: [uwsgi] plugins = python3 chdir = /srv/user/app/ module = app.wsgi home = /home/user/.virtualenvs/app/ master = true processes = 10 socket = /srv/user/app/app.sock chmod-socket = 666 vacuum = true uid = 1000 gid = 1000 And this is what the logs say about my service: Wed Dec 20 11:29:51 2017 - *** Starting uWSGI 2.0.14-debian (32bit) on [Wed Dec 20 11:29:49 2017] *** Wed Dec 20 11:29:51 2017 … -
Need to use Django json response an embedded bokeh plot with ColumnDataSource
I need to response a bokeh plot in the way similar to how to embed standalone bokeh graphs into django templates. That is, to response an ajax request from an already loaded page with an embedded bokeh plot from Django server side without reloading the page by rendering the same template again. In my case, the script from bokeh.embed.components contains the stringified ColumnDatasource of a pandas series instead of a simple list as shown in the link. But I got "Object of type 'Series' is not JSON serializable" exception. So far, I have tried using python json encoding the script and had the same exception. Is there anyway to send the script containing a Series? Thank you -
Django Project Architecture Guidance [Beginner] [Detailed]
I'm working on a project and I'm not sure what my next step is to be or how to best achieve the result that I want. What I would like to do Create a quiz-like app where I can add questions and answers, and have users select the right options either through multiple-choice or text input and have the answer validated against the correct question What I currently have I have a Django setup of the following from django.db import models class Exam(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class Question(models.Model): question_text = models.CharField(max_length=256) exam = models.ForeignKey(Exam) class Answer(models.Model): text = models.CharField(max_length=128) question = models.ForeignKey(Question) def __str__(self): return self.text This is what I currently can do I can use the admin panel to add new questions, answers and exams I can pass the new data to render them on a template and therefore the website, so if I add a new question I can have it appear on the website I also know how to create a form that passes data to the server and adds new data to the database without having to use the admin panel I know how to pass data to a template from the … -
Sending EmailMultiAlternatives in mail_admins()
I have the below view code snippet and I would like to send email as EmailMultiAlternatives to the admins, the problem is...it doesn't render the html tags. Kindly assist with some ideas. subject = "A New Feedback" ctx = { 'name': name, 'email': email, 'message': message } message = ('ecoke/includes/email_feedback.html', ctx) if not settings.ADMINS: return mail_admins(subject, message, fail_silently=True, html_message='text/html') -
Updating wagtail page object and keeping revisions intact
HAs the title says how do I update a wagtail page object, with my own custom fields, and keep the revisions intact? Example problem: I have a Page model as follows: class MyPage(Page): paid = models.BooleanField(default=False) cost = .... .... upgrade_only_field = models.CharField(....) .... User edits these page has a bunch of revisions etcetera. They go through an "Upgrade" view which is a checkout causing them to be able to add / edit additional fields on the model. In the post of this view I am doing: self.object = form.save(commit=False) # Handle updated fields self.object.save() Now unless the object is upgraded a revision is saved that goes under moderator approval. Meaning the revision has submitted_for_moderation = True. I want to clear this on the revisions, since they no longer apply, but in my attempts this causes the previously set fields to be reset by publishing the latest revision. Meaning, after the above I'm doing: latest_revision = self.object.get_latest_revision() if latest_revision and latest_revision.submitted_for_moderation: latest_revision.publish() Am I missing something here? Why does publishing the latest revision (and hence removing moderation) cause this since it's just a ForeignKey to the page object? -
MySQL Host in Django/Nginx/Python setup - reverts to localhost
Odd issue here. This setup used to work in the past on our Django / Nginx / Python setup but is causing issues on a new machine. Very standard settings.py: DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql', 'NAME': 'dev_database', 'USER': 'dev_user', 'PASSWORD': 'devuser', 'HOST': '123.123.123.123', 'PORT': '3306', } } In the past, not a problem connecting to that HOST (123.123.123.123) however now Django reports that it's attempting to connect to the localhost (let's call that 192.0.0.1): OperationalError: (1045, "Access denied for user 'dev_user'@'192.0.0.1' (using password: YES)") We've flushed settings, wiped out .pyc files, double checked settings. -
Jenkins keeps running slave operations as root
I have a Jenkins Slave node that is used for DJango builds. Part of the procedure involves taking the most recent repository Django code from Git and then building with it. The problem is that when Jenkins runs on the slave machine, it always runs as "root". The problem is similar to this one: Jenkins runs as root instead of Jenkins but not exactly like it. It checks out repositories from Git as root If I do "ls -lart" on the workspace directory, all of the files there are owned by user: root group : root It runs everything as root (on the slave machine) - even though I have configred it to log in as a specific user. See picture of the slave node defined below. In the job (see picture), I am using the slave node only. Why is it doing this? Is some kind of caching going on? If so, how do I remove the cache? I only mention the cache because when one looks at the log file for a Jenkins run, it looks as though it is accessing some kind of cache for "root" [... snip ...] Downloading idna-2.6-py2.py3-none-any.whl (56kB) Collecting decorator (from ratelim->geocoder==1.33.0->-r requirements.txt … -
Listing tags by ManyToMany relationship in django
I'm learning Django and have gone already through various tutorials. I have created a basic blog site, but wanted to add tagging funcionality. It works - I have posts with assigned tags, but I'm struggling to list those tags in the post now. blog/models.py: class Post(models.Model): title = models.CharField(max_length=50) text = models.CharField(max_length=1000) pub_date = models.DateTimeField('date published') author = models.CharField(max_length=30) mail = models.EmailField() class Tag(models.Model): name = models.CharField(max_length=15) posts = models.ManyToManyField(Post, related_name="tags") I know I would need something like: Tag.objects.filter() but could you please guide me how to list only those related to the specific post? I was trying various combinations, but none of them worked really well... -
creating forms in django - error in output
I have the following code in various places to attempt to produce a form in Django that takes data and writes it to the database views.py from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from .forms import TeacherSignup """def teachers(request): return render(request,'teachers/teachers.html') """ def teachers(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TeacherSignup(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = TeacherSignup() return render(request, 'teachers/teachers.html', {'form': form}) teachers.html (this is the html page that contains the form) <form action="/teachers/" method="post" style="border:1px solid #ccc"> {% csrf_token %} {{ form }} <div class="container"> <label><b>Email</b></label> <input id="email" input type="text" placeholder="Enter Email" name="email" required> <label><b>Centre/School Name</b></label> <input id="school_name" input type="text" placeholder="Enter School or Centre Name" name="school_name" required> <label><b>Password</b></label> <input id="password" input type="password" placeholder="Enter Password" name="password" required> <label><b>Repeat Password</b></label> <input id="password_repeat" input type="password" placeholder="Repeat Password" name="password_repeat" required> <input type="checkbox" checked="checked"> Remember me … -
TypeError: cannot make memory view because object does not have the buffer - django
I am trying to make a post request to mailchimp's api. It works perfectly fine when I am doing it in my local machine but somehow when I push it into the cloud. This error appears and I thought it was because of the python version since it's the only differences between local and the cloud. In cloud it's python 2.7.6 local I am using 2.7.12 I have searched up but a few issues only talks about other lib that's causing the error. I didn't have new requirements installed at all. I can calling a post request by using something like requests.post(MAILCHAMP_API, payload, headers=headers).json() Then I get an error of cannot make memory view because object does not have the buffer interface Exception Location: /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/contrib/pyopenssl.py in sendall, line 216 -
send_email() takes 1 positional argument but 3 were given - Django Python
I am trying to send a test email from my Django python project and following the django docs for that. When the below function is executed I get an error (image attached). What I am doing wrong? https://docs.djangoproject.com/en/2.0/topics/email/ from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect def send_email(request): subject = request.POST.get('subject', 'Test') message = request.POST.get('message', 'Test Message') from_email = request.POST.get('from_email', 'test@example.com') if subject and message and from_email: try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') Error: -
Is it possible to use django generic-class based view with a database view as model?
This is my problem, i'm building a kind of clown of stackoverflow, i have questions, tags, category as models, in the welcome page of the site, i should list all the questions, i've done it using class based views on Question Model but, i don't have all the details i want. So i've created a view in my DB and a model corresponding to it. I've tried to use class based view in other to display questions list but based on that view. But i always obtain an empty list even if the view has data. -
Django error on running server and making migrations:
I get the following error on running my server, following making migrations and migrating: ERROR Warnings: ?:(urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace. Is anyone able to explain the above error and also suggest ways of resolving it?