Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pip install Django on python3.6
If I run pip install Django I get Requirement already satisfied: Django in /usr/local/lib/python2.7/dist-packages I'd like to use python3.6 instead (which is already installed in /usr/bin/python3.6). What's the correct pip syntax to install the last version of Django on python 3.6? -
Fetch not giving me the responce
I have a login form with username and password field. I am trying to send the username and password to my django api. But nothing shows up in console. I am trying to print response in console. THis is my code export default class LogInComponent extends Component { handleLoginButtonClick() { fetch('https://myname-backend.appspot.com',{ method: "POST", type: 'json', data: {password:document.getElementById("username").value, username:document.getElementById("password").value } }) .then(function(response) { // We get a JWT back. let jwt = response.auth_token; // We trigger the LoginAction with that JWT. console(response); //LoginActions.loginUser(jwt); return response; }); } render() { return ( <div className="LoginPage"> <div className="login-page"> <div className="form"> <form className="register-form"> <input type="text" placeholder="name"/> <input type="password" placeholder="password"/> <input type="text" placeholder="email address"/> <button>create</button> <p className="message">Already registered? <a href="#">Sign In</a></p> </form> <form className="login-form"> <input id="username" type="username" placeholder="username"/> <input id="password" type="password" placeholder="password"/> <button onClick={this.handleLoginButtonClick}>login</button> <p className="message">Not registered? <a href="#">Request Username and Password</a></p> </form> </div> </div> <img className="Logo_Tessact_White" src="./dev/js/images/TESSACT_logo_white.png"/> </div> ); } } This my api call guide What am I doing wrong? -
Python (developent environment): Install Python 3.5.2, pip, and virtualenv on Windows
I'm having a problem trying to get the PowerShell virtualenvwrapper installed. Bellow is the process I'm going through: /****** Experienced Python/Django developers often choose to instead run their Python apps within independent Python virtual environments. These allow developers to have multiple different Django environments on a single computer, allowing them to create new websites (using the latest version of Django)while still maintaining websites that rely on older versions. The Django developer team itself recommends that you use Python virtual environments. ******/ 1. Access cmd as admin cd C:\ mkdir Django cd Django 2. Get Python 3.5.2 (32 bits is the one I suggest) - https://www.python.org/downloads/release/python-352/ Customize the location: C:\Python35-32 (make sure is installed in your path) Once you’ve installed Python, open up a PowerShell window and python This is what you will see: Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ------------------- (CTRL + C to exit the Python prompt) 3. Get Pip Save the following script as get-pip.py: https://bootstrap.pypa.io/get-pip.py (if you can not find it, ask me for a copy) python get-pip.py To check if everything is working, just type pip at the … -
how to translate this English
enter image description here I dont know how how to find the APPLICATION's direction in the code.please help me description this. -
Django project with Google Calendars API
I have been working on a Django application which uses the Google Calendars API to manage meetings (add meetings to a user's calendar, send meeting invitations to people etc). There were some inconsistencies however with calendar events not appearing in some users calendars. I started looking into this, and having not had the Google Calendars API running within my development environment previously (although I had access to the code used for the calendars on the application in the status that it was in prior to when I started working on it), I followed parts of the tutorials at developers.google.com to try and get the existing Calendar API up and running on my development machine, but have somehow managed to break the working code when trying to add the Calendars API to it. When I now try to browse to my website by typing www.mysite.co.uk in the browser, I get an error page which says: NameError at /projects/my-projects/ global name 'h_user' is not defined Request Method: GET Request URL: http://www.mysite.co.uk/projects/my-projects/ Django Version: 1.9.1 Exception Type: NameError Exception Value: global name 'h_user' is not defined Exception Location: /code/moon/core/templatetags/getters.py in get_invite_details, line 153 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/code/moon', '/usr/local/bin', … -
Location Django App on Google Cloud
What is the correct way to deploy local Django Application into Google Cloud (GC). So far, GC provides a lot of samples, Django hosting, but including a lot of other services. What if I want to deploy fresh Django Web App with Google App Engine. What is the simplest way to do this? -
no such table: member_membership in DigitalOcean but worked fine in local server
My django project worked fine both in localhost and Ubuntu Server 16.04. But when I deployed it in digitalocean it gives OperationalError: In template /home/ohid/alumni/member/templates/member/index.html, error at line 1 no such table: member_membership 1 : {% extends parent_template|default: "member/base_member.html" %} 2 : 3 : {% load staticfiles %} 4 : 5 : {% load right_block_tags %} 6 : {% load left_block_tags %} 7 : 8 : {% block title_block %} 9 : Index 10 : {% endblock %} 11 : The traceback is: Traceback: File "/home/ohid/lib/python3.5/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/home/ohid/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute 337. return Database.Cursor.execute(self, query, params) The above exception (no such table: member_membership) was the direct cause of the following exception: File "/home/ohid/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/ohid/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/home/ohid/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/home/ohid/lib/python3.5/site-packages/django/template/response.py" in render 109. self.content = self.rendered_content File "/home/ohid/lib/python3.5/site-packages/django/template/response.py" in rendered_content 86. content = template.render(context, self._request) File "/home/ohid/lib/python3.5/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/home/ohid/lib/python3.5/site-packages/django/template/base.py" in render 208. return self._render(context) File "/home/ohid/lib/python3.5/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File "/home/ohid/lib/python3.5/site-packages/django/template/base.py" in render 994. bit = node.render_annotated(context) File "/home/ohid/lib/python3.5/site-packages/django/template/base.py" in render_annotated 961. return self.render(context) File "/home/ohid/lib/python3.5/site-packages/django/template/loader_tags.py" in render 174. return … -
Retrieve all reverse foreign keys in Django
Given a specific Placerating object, which points to a ThePlace object, how to retrieve all ThePlace objects which points to this ThePlace object. Please note that ThePlace has a recursive relationship to itself. Model: class ThePlace(models.Model): author = models.ForeignKey('auth.User') upperlevelplace = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, related_name='upperlevelplaces') class Placerating(models.Model): theplace = models.ForeignKey('ThePlace', on_delete=models.CASCADE, null=True, related_name='placeratings') I have tried this View: placerating = Placerating.objects.get(pk=15) qs = placerating.theplace.upperlevelplaces() print(qs) But I get the following error: qs = placerating.theplace.upperlevelplaces() File "C:\aa\aa\env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 505, in __call__manager = getattr(self.model, kwargs.pop('manager')) KeyError: u'manager' -
Ordering dictionary in context Django
I looked at this thread, with an example of sorting dictionaries. I have a dictionary of programme objects where the key is a programme object and the value is a lookup of the number of related Project objects. def DepartmentDetail(request, pk): department = Department.objects.get(pk=pk) programmes = Programme.objects.all().filter(department=department).exclude(active=False).order_by('long_name') matrix = {} for p in programmes: prj = Project.objects.all().filter(programme=p) matrix[p] = str(len(prj)) return render(request, 'sysadmin/department.html',{'department': department, 'programmes': programmes, 'matrix': sorted(matrix.items())}) In the model, Programme returns a string 'long_name', so I believe that I am trying to sort a string key and a string value. In the template I get to the keys and values as so, {% for programme, n in matrix %} This gives me the error.. unorderable types: Programme() < Programme() I don't really understand the error, in the python 3 documentation it states that the sorted() method accepts any iterable - So why does this happen? I'm looking at collections.OrderedDict to solve the problem, but I want to know why this doesn't work. Thanx. -
After celery delay() called, it takes almost 5 to 10 seconds for the tasks to start executing in worker
I'm currently working on an app with following configuration: Django 1.8 Python 2.7 Celery 3.1.x (Amazon SQS as borker url) I'm currently running multiple celery each with concurrency = 4. So my question is when I call celery delay() in my code, it takes almost 5 to 10 seconds for the tasks to start executing in my worker. I want to know why I'm getting this delay and how can I reduce it so that my takes the task immediately as I call delay(). I have checked the same using RabbitMQ and I can see that the tasks starts executing as soon as I call delay(). Thanks In Advance -
Django matching a CharField
I'm trying to create a table in Django using a subset of data from my Model but when I try to filter it I get the following error. Unsupported lookup 'like' for CharField or join on the field not permitted. models.py class Opps(models.Model): Rec_ID = models.IntegerField(default=0) name = models.CharField(max_length=500) notes = models.CharField(max_length=10000) company = models.CharField(max_length=400) owner = models.CharField(max_length=100) status = models.CharField(max_length=100) revenue = models.DecimalField(max_digits=20, decimal_places=2) cost = models.DecimalField(max_digits=20, decimal_places=2) profit = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.name tables.py part of django_tables2 class Opps_Table(tables.Table): class Meta: model = Opps attrs = {'class': 'paleblue'} views.py def sales(request): Data_User = Opps.objects.filter(owner__contains='name') table = Opps_Table(Data_User) RequestConfig(request).configure(table) return render(request, 'graphs/sales.html', {'table': table} ) Should I be using a different type of data in my Model or trying to filter it a different way? -
Django widgets don't work : Country flags
I'm adding a new library : Django_countries on my Django Project and I get a little problem with my form. I get correctly my countries list inside my form, but I don't display flags with widgets beside each country. This is my models.py file from BirthCertificate application : #-*- coding: utf-8 -*- from django.db import models from Identity.models import Country, Identity from django.utils.encoding import force_text from django_countries.fields import CountryField ###################################### # Choix à l'utilisateur pour le sexe # ###################################### SEX_CHOICES = ( ('Masculin', 'Masculin'), ('Feminin', 'Feminin') ) #################################################################################### # Création d'une table permettant de renseigner toutes les informations concernant # # l'enfant et reprise des champs pour les parents # #################################################################################### class BirthCertificate(models.Model): lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') birthday = models.DateField(null=False, verbose_name='Date de naissance') birthhour = models.TimeField(null=True, verbose_name='Heure de naissance') birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance') birthcountry = CountryField(blank_label='(Pays de naissance)') fk_parent1 = models.ForeignKey(Identity, related_name='ID_Parent1', verbose_name='ID parent1', null=False) fk_parent2 = models.ForeignKey(Identity, related_name='ID_Parent2', verbose_name='ID parent2', null=False) This is my forms.py file : #-*- coding: utf-8 -*- from django import forms from BirthCertificate.models import * from django_countries.widgets import CountrySelectWidget class CustomLabelModelChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): self._label_from_instance = kwargs.pop('label_func', force_text) … -
Django CMS Previous link history
I need to make a link, that directs me to the previous Page. Now i did it with a href="{% page_url 'xyz' %}" but thats not dynamic and a realy bad idea. Does anyone knows how to make that dynamic like request the previous link ? -
Terminate celery task within task
Need your help. How can I run the celery task from the code with given time interval (every 3 min), max retries (after 5 attempts task should be terminated), in the given time period (task can work only from 9 a.m to 6 p.m.) and task has to terminate yourself when some condition occured within task (ordinal if-else statement) -
What is the best format for contacts for importing and exporting to iphones, androids and desktop pc's
I need to build a small website (Python/Django) for administrate contacts (like: name, phone number, email). It should be possible to export the data from this website to phones and PCs. Is there a standard/format/protocol/lib which I should use? -
add link to Actions in Django Admin
In Django admin I have a print button that sends information to the template. I want to add to the Action dropdown link where I checkboxes select the desired entries and in Action dropdown choose Print. But when I added a link to the Aсtion dropdown I get an error about getting the third argument. I can not understand that this is the third argument. admin.py @admin.register(Salary) class SalaryAdmin (admin.ModelAdmin): list_display = ('worker', 'salary_uah', 'dates', 'button') search_fields = ('worker', 'salary_uah', 'dates') list_filter = ('worker', 'date') actions = ['button'] def button(self, obj): return '<a class="button" href="{}">Print</a>'.format(reverse('act', args=[obj.pk])) button.short_description = 'Actions' button.allow_tags = True urls.py urlpatterns = [ url(r'^$',home, name='home'), url(r'^add/$',add_worker, name='add'), url(r'^act/(?P<obj>[\w-]+)$',acts, name='act') ] models.py class Salary (models.Model): worker = models.ForeignKey(Worker) salary_uah = models.IntegerField ('Salary') date = models.DateTimeField('Date', default=datetime.datetime.utcnow()) views.py def acts (request, obj): if not request.user.is_authenticated(): return redirect('admin:login') salary = Salary.objects.get(id=obj) workers = Worker.objects.filter(id=salary.worker.pk).values() salary = Salary.objects.filter(id=obj).values() return render(request, 'zpapp/act.html', {'workers':workers, 'salary':salary }) error TypeError at /admin/zpapp/salary/ button() takes 2 positional arguments but 3 were given Help me add a link in Aktion -
CSRF Failed: CSRF token missing or incorrect after upgrading to django 1.10 from 1.8
I am sending a post request via AJAX to api (both the current page and api are under the same host). I am getting csrf failed: csrf token missing or incorrect error. This happened when I upgraded to django 1.10 from 1.8. I checked with django 1.9 as well and error persists on 1.9. Here is the detail curl : curl 'https://tru-staging.com/pagemaker/api/v1/carousel/slide/' -H 'Pragma: no-cache' -H 'Origin: https://tru-staging.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.8,ar;q=0.6' -H 'Authorization: Token undefined' -H 'Content-Type: application/json;charset=UTF-8' -H 'Accept: application/json, text/plain, */*' -H 'Cache-Control: no-cache' -H 'X-CSRFToken: UMQPAIb1OTl7MyiQLJttdKE8xOLz35pMaHeNGMMDqy0Jn3x8SpbaEUmzOQk7Fppr' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36' -H 'Cookie: _ga=GA1.2.2131330908.1484113382; sessionid=nnxqi67j18tblt985vayyz4ssyhdnfjm; csrftoken=o6gjW1Sxb1X23hI9RurDIAXjSuEbbgbMQJtMQyS2gT1yTnCGF80rmmB8pwSOSKKj' -H 'Connection: keep-alive' -H 'Referer: https://tru-staging.com/68/school_landing/' --data-binary '{"order":4,"carousel":736}' —compressed -
centos7 server with Django can't intersection other computers
i'm using linux server(centos7) with Django but when i start server, for example "python manage.py runserver 0.0.0.0:8000" then localhost is allow Django web server but other computers don't connect to Django web server i'm already checked /etc/hosts.deny and /etc/hosts.allow and server computer ping is intersection with other computer well what is the main problem.... -
python watchdog module doesn't work with django/mod_wsgi under redhat server
We use django (1.7.5) with mod_wsgi under apache2 in redhat server, and try to use watchdog to monitor the files. It works fine locally using python manager.py runserver command, while the event is not triggerred in wsgi mode when I deploy it into product environment # wsgi.py from django.core.wsgi import get_wsgi_application application = get_wsgi_application() LOGGER.debug("Starting to watch for config file changes.") fw = FileWatcher() # filewatcher path = settings.PROJECT_ROOT filename = 'config.json' class ConfigHandler(FileSystemEventHandler): def on_modified(self, event): if not event.is_directory and event.src_path.endswith(filename): LOGGER.debug("The config has changed!, Reloading") class FileWatcher(object): _instance = None _watching = False def __new__(cls, *args, **kwargs): if not cls._instance: LOGGER.debug("Creating new FileWatcher") cls._instance = super(FileWatcher, cls).__new__(cls, *args, **kwargs) cls.start_watching() return cls._instance @classmethod def start_watching(cls): if not cls._watching: LOGGER.debug("Starting to monitor the file: %s", os.path.join(path, filename)) event_handler = ConfigHandler() observer = Observer() observer.schedule(event_handler, path=path, recursive=False) observer.start() cls._watching = True -
Recursion error in sphinx
root@assassin-VirtualBox:~/mysite/myWebsite/site/docs# make html Running Sphinx v1.5.1 Recursion error: maximum recursion depth exceeded This can happen with very large or deeply nested source files. You can carefully increase the default Python recursion limit of 1000 in conf.py with e.g.: import sys; sys.setrecursionlimit(1500) make: *** [html] Error 1 -
dumpdata for django from postgres
Encountered an issue with dumpdata with django CommandError: Unable to serialize database: cannot import name simplejson likely from old django code that tries to import simplejson from django.utils. I've removed every instance I could find but the error persists. Looking for an alternative dump similar to this from postgresql commands that I can later import. -
coding UTF8 python
I don't understand. I have created django project on my laptop. And siccesfully run this on heroku. And I clone github of this project on another laptop (the same version Ubuntu as on the first). And I have error now. I should specify ' # -- coding: utf-8 --' on other laptop and wtite var as 'text = u"какой-то текст"' But I needn't do this on the first laptop. What is different? The same Ubuntu 14.04 on both. Thank you. Have a nice day. -
How to choose between Django and LAMP(P: Python) for building a website?
I just started to learn web development. It seems Django framework is more popular and convenient for development, but LAMP sounds more comprehensive. -
Making simultaneous AJAX calls to separate Django views
I have a Django view that runs a particular function when a POST request is received. Snippet: def run_function(request): if request.method == 'POST': run_some_function() This is called via AJAX as follows: $.ajax({ 'type' : 'POST', 'url' : '/run_function/', 'data' : data, 'success' : function(json) { // Display results to user } }); This works as expected. However, this particular function can take a while to run, so I want to display progress information to the user. Luckily, I have another function that can return the progress (an integer between 0-100) of the task. Snippet: def get_progress(request): progress = calculate_progress() return HttpResponse(json.dumps(progress), content_type="application/json") I can then make an AJAX call every X seconds to get the progress and update my progress bar: function check_progress() { $.ajax({ 'type' : 'POST', 'url' : '/get_progress/', 'success' : function(response) { if (response >= 100) { // Update progress bar to 100% and clearInterval } else { // Update the progress bar based on the value returned by get_progress } } }); } var check = setInterval(check_progress, 500); The problem is...how can I do both simultaneously? I need to be able to make the AJAX call to run the function and make the AJAX calls to … -
How to create Create for ManyToMany relation with through?
I have models like: class Playlist(models.Model): key = models.CharField(max_length=255, blank=True, unique=True) user = models.ForeignKey(User) title = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now_add=True) videos = models.ManyToManyField(Video, through='PlaylistVideo') class PlaylistVideo(models.Model): playlist = models.ForeignKey(Playlist) video = models.ForeignKey(Video) position = models.IntegerField() class Video(models.Model): title = models.CharField(max_length=255,blank=True) description = models.TextField(blank=True) thumb = models.URLField(blank=True) duration = models.IntegerField(default=0) I want to write POST (create) for Playlist an API. Not sure how to handle videos field. How to send values for videos field? Thanks