Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Profiling functions in python
I would like to know if there is anyway to profile only a function in a python script which does not have a main(). I have a script which will be called by another one. But i want to know the loopholes in it. -
How to get base64 encoded string of an image in django?
from html page user uploads a image, i want to convert it to base64 encoded string, i am not using any forms, using just <input type="file" name="galleryImage" class="filestyle" data-buttonText="Select a Image"> -
How can i gget current user's id in forms.py in django?
I want current user's id on my forms.py because i am trying to compare user's wallet balance and user's entered amount if balance is less i want to show error message otherwise success message so how can i get current user's id on forms.py in django -
Neo4j closes session unexpectedly when accessed locally
Hello everyone and thank you for taking the time to read my question. I am currently experiencing some unexpected behavior from neo4j used via the neo4j python driver. I have a neo4j database deployed on a server (Ubuntu 16.04) as well as a django-server with an instance running on the same server and one instance running locally on my machine (Windows 7). If I connect to the neo4j database with the django-instance on my local machine everything is working as expected. If I connect to the neo4j database with the instance running on the ubuntu server the connection closes after a very short time. Example: records = Searcher.neo.run( 'MATCH (s:Skill {{name:"e e"}})-[r:related]-(n) RETURN s, r, n') for idx, record in enumerate(records) : print('{} - {}'.format(idx, record['n']['name']) This code snippet produces 151 lines when run from my local instance (as there are 151 results). When I execute it from the instance running on the ubuntu server I only get 8-10 results. The following error is written to the neo4j logfile. 2017-02-14 10:29:07.212+0000 ERROR [o.n.b.v.r.ErrorReporter] Client triggered an unexpected error [UnknownError]: Cannot write to buffer when closed. See debug.log for more details, reference b7cede40-c4aa-409c-a40b-e5582ea25c8d. 2017-02-14 10:29:07.212+0000 ERROR [o.n.b.v.r.ErrorReporter] Client triggered an unexpected … -
Access denied when connecting Django to RDS via SSL
I'm trying to connect Django to AWS Aurora server(RDS Aurora 5.6.10a) but I'm getting django.db.utils.OperationalError: (1045, "Access denied for user 'admin'@'xx.xx.xx.xx' (using password: YES) In Django settings.py, I've used the following settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': MYSQL_DATABASE, 'USER': MYSQL_USER, 'PASSWORD': MYSQL_PASSWORD, 'HOST': MYSQL_SERVER, 'PORT': '3306', 'OPTIONS': { 'ssl': { 'ca': '/Users/mac-user/workspace/project/settings/rds-combined-ca-bundle.pem', } } } } I've also looked at similar questions like this but didn't work I've also tried to connect to using mysql-connector-python and mysql.connector.django as database engine, and ensured that I'm setting the right configuration (setting OPTIONS's ssl_ca and ssl_verify_cert) but I've also got a similar error: mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'admin'@'xx.xx.xx.xx' (using password: YES) I've tried to connect to the database using PHP and command line and it worked fine: mysql -h '<host>' -u '<username>' -p'<password>' --ssl-ca='<SSL_certificate_absolute_path>' Am I missing any configuration for Django? -
Django: serve static section of a web-app
I have: a Django web app a separate static HTML site (blog) The static site is a separate directory tree. I want the static site to be served as a sub-section of the web app. For example, the app is at http://app.com/ and the static is site served from http://app.com/blog -
Django: How to list all field name of model along with @property decorated class method
I have following model: class PaymentRecord(models.Model): entry = models.ForeignKey(PayrollEntry, related_name='entry_rows') paid_employee = models.ForeignKey(Employee) designation = models.ForeignKey(Designation) paid_from_date = HRBSDateField() paid_to_date = HRBSDateField() paid_amount = models.FloatField() @property def get_designation_name(self): return designation.name Here I want to list all fields object. For that I used PaymentRecord._meta.get_fields() and its output is: (<django.db.models.fields.AutoField: id>, <django.db.models.fields.related.ForeignKey: entry>, <django.db.models.fields.related.ForeignKey: paid_employee>, <django.db.models.fields.related.ForeignKey: designation>, <hr.fields.HRBSDateField: paid_from_date>, <hr.fields.HRBSDateField: paid_to_date>, <django.db.models.fields.FloatField: paid_amount>) Including the obtained output i also want to list @property decorated methods. What can be done to achieve so. Please help. -
Compare datetime with Django birthday objects
I have a question about my script. I want to know all people who have more than 16 years from my Database. I want to check this when user triggers the function. I have this function : def Recensement_array(request) : date = datetime.now().year print date # I get year from now birthday = Identity.objects.values_list('birthday', flat=True) # Return list with all birthday values for element in birthday : if date - element < 117 : print "ok < 117" else : print "ok > 117" From print date I get : 2017 From print birthday I get : <QuerySet [datetime.date(1991, 12, 23), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1900, 9, 12), datetime.date(1900, 9, 12), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1089, 9, 22), datetime.date(1990, 12, 12)]> So my goal is to substract date with birthday and compare if date - birthday = 16 years, I print element, else nothing. I get two problems : How extract only year from birthday ? Then the comparison method is between int and tuple up to now. If I could extract only year from birthday, it should work right ? Thank you -
Django templates directory not found
I'm running Django 1.10 with python 3.4 on Windows 10. I migrated to a new system, and nothing has changed in the directory structure or my settings, but when I try to load my home page I get TemplateDoesNotExist. PyCharm is flagging all templates as not found. The only thing that's different between this system and the previous one is that I'm using a newer version of WAMPServer. I couldn't find anything in the settings that would explain this. -
in django signals creating new user and alongwith filelds also from django models(by default add cash_amount and data)
This my models: class UserBillingHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=False, default="Free 100Mb on sign-up and Buy $40 and get 100Mb" ) cash_amount = models.DecimalField(max_digits=9, decimal_places=2) data = models.IntegerField(null=False, blank=False) date = models.DateTimeField(default=timezone.now, blank=False, null=False) is_confirmed = models.BooleanField(default=False) job = models.ForeignKey("Job", on_delete=models.SET_NULL, null=True) @property def user_can_view(self, user): return (self.user == user) def user_can_edit(self, user): return (self.user == user) def user_can_delete(self, user): return (self.user == user) def get_absolute_url(self): return "/userbillinghistorys/%s/" % self.id def cash_amount(self): return "$%s" % 0 def data(self): return 100 * 1024 * 1024 This my signals: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): """Receiver to create authoriasation tokens for users""" if kwargs.get('raw'): return # ignore for loading fixtures if created: Token.objects.create(user=instance) UserBillingHistory.objects.create(user=instance) if settings.NEW_USER_EMAIL is not None: send_email( "Spotless data - new user", "New user with email %s has signed up" % instance.email, "Spotless Data<team@spotlessdata.com>", settings.NEW_USER_EMAIL ) By above code i am able to see by default cash_amount=0 and data=1978344 But i am getting below error. CAn you please suggest regards it. unicodeencodeerror 'charmap' codec can't encode character u' u2019' in position enter image description here -
CSRF not set when making an ajax call from jquery to Django
I am getting a CSRF cookie not set when making an ajax call from jquery to django views.index (I have tried everything i have seen on other stackoverflow posts, see list at bottom of post) My ajax call: board.delete_comment = function(){ $(this).closest("div").slideUp() $.ajax("http://localhost:8000/"+$(this).val(),{ type: "POST", beforeSend: function(xhr, settings) { var csrftoken = getCookie('csrftoken') if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, success: function (data) { console.log(data) } }); }; My views.index function: @csrf_exempt def delete_me(comment_id): comment = get_object_or_404(Comment, pk=comment_id) comment.delete() return "success" My URL pattern: url(r'^(?P<comment_id>[0-9]+)/$', views.delete_me, name='delete'), Upon calling the delete_comment function in javascript a 403 forbidden error is triggered. I have tried everything i have seen on existing stack overflow boards: -installing and adding corsheaders to settings -including a @csrfexempt decorator in views.index -setting CSRF_COOKIE_SECURE to false in settings -adding the csrftoken header to the request (per django documentation) -setting a CSRF_TOKEN on the window in my html Nothing seems to work... Anyone have a suggestion on how to resolve this issue? Or what the issue may be. -
Django REST Framework: Browser Enhancement Forms
I'm trying to enable forms to be able to send PUT and DELETE responses to the server. I'm using the ajax form library specified here: http://www.django-rest-framework.org/topics/browser-enhancements/ The issue I'm running into is that the PUT and DELETE requests require CSRF token, which is not provided using the library. I keep getting CSRF token is missing or incorrect error. How do I provide the token using the ajax form library? -
Add CharField to the search index in haystack
I use in my django app (1.8), haystack (2.4.1) to search. And I want to be able to serach words with autocomplete (EdgeNgramField) and words when I put only the part of name, for example 'zo-zo on' (this isn't working with EdgeNgramField) Below I tired added: text_sec = indexes.CharField(use_template=True) but this isn't working for me. Here is my code, but he doesn't works: class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) text_sec = indexes.CharField(use_template=True) id = indexes.CharField(model_attr='id') get_absolute_url = indexes.CharField(model_attr='get_absolute_url') description = indexes.CharField(model_attr='description', null=True) is_past = indexes.CharField(model_attr='is_past', default='false') date_start = indexes.DateTimeField(model_attr='date_start') -
Django DateInput Forms calculation and disable Saturday & Sunday been picked
forms.py code: class dateForm(ModelForm): model = dateCalculation fields = ['from_date', 'to_date', 'number_of_day'] widgets = {'from_date': DateInput(), 'to_date': DateInput()} models.py code: class dateCalculation(models.Model): from_date = models.DateField() to_date = models.DateField() number_of_day = models.PositiveSmallIntegerField() Question: How do i do a subtraction with from_date and to_date. Example from_date = 14-feb-2017, to_date = 15-feb-2017. After calculation, can the difference between the 2 dates showed in number_of_day ? Is it possible to disable days from pick by user from Django ? Example, 17-feb and 18-feb is Saturday and Sunday and user shouldn't be able to select this two dates. -
Django Registration form, anonymous user?
I'm trying to create a registration form with information added to the Profile model, but it keeps giving me an anonymous user when I submit it. What am I doing wrong here? My forms.py: class RegisterForm(forms.ModelForm): Gebruikersnaam = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Gebruikersnaam'}), max_length=20, label="") Wachtwoord = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Wachtwoord'}), label="") Emailadres = forms.EmailField(required=False, widget=forms.TextInput(attrs={'placeholder': 'E-mailadres'}), label="") Profielfoto = forms.ImageField(required=False, label="") Biografie = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Biografie'}), max_length=150, label="") class Meta: model = Profiel fields = ['Gebruikersnaam', 'Wachtwoord', 'Emailadres', 'Profielfoto', 'Biografie'] My models.py: class Profiel(models.Model): user = models.OneToOneField(User, primary_key=True) Profielfoto = models.ImageField() Biografie = models.CharField(max_length=150) and my Views.py: def step3(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): Registratieform = form.save(commit=False) username = form.cleaned_data['Gebruikersnaam'] password = form.cleaned_data['Wachtwoord'] user = authenticate(username=username, password=password) Registratieform.user = request.user # Set the user object here Registratieform.save() # Now you can send it to DB if Registratieform.user is not None: if Registratieform.user.is_active: login(request, Registratieform.user) return redirect('/Dashboard/') return render_to_response("Home/index.html", {'form': form}) else: form = RegisterForm() return render(request, 'Home/index.html', {'form': form}) -
Caret in regular expression
The quick reference to regular expressions in the book "Mastering Django: Core" by Nigel George (as well as Django Book site) states the following: [^/]+ One or more characters until (and not including) a forward slash Is it an error? Should it be "Any character(s) except forward slash"? Because the caret placed as the first character inside the brackets negates the characters in the group. Am I wrong? -
Nested router not working
I'm new to Django and am struggling to get nested routers working. Basically, I'm trying to model the endpoint /api/v1/organizers/1/events/1, where I have Event and Organizer models as follows: class Event(models.Model): class Meta: db_table = 'events' STATUS_CHOICES = ( ('scheduled', 'Scheduled'), ('completed', 'Completed'), ('cancelled', 'Cancelled') ) name = models.TextField() purpose = models.TextField() date_time = models.DateTimeField() description = models.TextField() programme = models.TextField() entry_fee = models.DecimalField(max_digits=6, decimal_places=2) status = models.TextField(choices=STATUS_CHOICES) comments = models.TextField(null=True) people_invited = models.ManyToManyField('Contact', through='EventInvitation') organizer = models.ForeignKey('Organizer', on_delete=models.CASCADE) class Organizer(models.Model): STATUS_CHOICES = ( ('inactive', 'Inactive'), ('active', 'Active'), ) class Meta: db_table = 'organizers' first_name = models.TextField() middle_name = models.TextField(null=True) last_name = models.TextField(null=True) email = models.OneToOneField('Email', on_delete=models.CASCADE) company_name = models.TextField(null=True) company_description = models.TextField(null=True) password = models.TextField() login_token = models.TextField(null=True) registered_on = models.DateTimeField(null=True) status = models.TextField(choices = STATUS_CHOICES, default='inactive') I created another app called rest_api to handle the API. The models are stored in an app called shared_stuff. Anyway, here's the project-level urls.py (don't mind the front_end app for now): from django.conf.urls import include, url urlpatterns = [ url(r'^api/v1/', include('rest_api.urls')), url(r'^', include('frontend.urls')), ] And here's the urls.py from the app rest_api: from django.conf.urls import url, include from rest_framework_nested import routers from .views import * router = routers.SimpleRouter() # /organizers/12/events/1 router.register(r'organizers', OrganizerViewSet) … -
Django : How can I prepare datasets in database before deploying web application?
I created e-commerce web application using Django. Before I deploy my application ver2, I have to create items (datas) to sell. (ver1 is running now) Because of one-to-many, many-to-many relations among the models, it is much easier to create item datas via django-admin page than other methods. Problem is though, if I run this application on production server, it can be accessed through internet even though all items are not ready!! How can I deal with it? -
Unable to import json objects from json file in DJANGO
I am unable to create json objects from json file in Django. Here is the code. I have a file called out.json with json objects in it. I want to send those objects as response. I am getting an error saying FileNotFoundError at /projectboard/random [Errno 2] No such file or directory: 'out.json' views.py from django.shortcuts import render, HttpResponseRedirect import sys, os import json from django.http import JsonResponse from tempfile import * import subprocess # Create your views here. from django.http import HttpResponse def random(request): os.system('python pypy.py') with open('out.json') as json_data: data = json.load(json_data) print(data) return JsonResponse(data) urls.py from rest_framework.routers import DefaultRouter from django.views.generic import TemplateView from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^random$', views.random, name='random'), url(r'^view/(?P<id_remedio>\w+)/$', views.view, name='view'), url(r'^view/$', views.view, name='view') ] -
How can I return the result of celery task to the client in Django template?
I making the DB searching web application. I made the progress-bar with "celery + ajax + Django". But I don't know how to return the results of celery task to the client... I want to show the results in the template. I know that celery has the ".get()" methods for returning result. Then how can I use with ajax??? I don't know how to code celery-python for this work... Do I have to use celery mysql as backend ? Please share some ideas or recommend other things..!! -
Downgrade virtualenv to 2.7 from 3.5.3
My virtualenv is currently configured to python 3.5.0 while the package I need to use only supports 2.7. I need a way of downgrading my python runtime to 2.7 within my virtualenv. I do have both versions available to use: First one is in my virtualenv, second is computer-wide. (project) me-Air:element me$ python -V Python 3.5.0 me-Air:element me$ python -V Python 2.7.10 -
Why the customized delete() function of the model may not be executed in Django?
How to understand following statements in Django's official documents? Keep in mind that this will, whenever possible, be executed purely in SQL, and so the delete() methods of individual object instances will not necessarily be called during the process. If you’ve provided a custom delete() method on a model class and want to ensure that it is called, you will need to “manually” delete instances of that model (e.g., by iterating over a QuerySet and calling delete() on each object individually) rather than using the bulk delete() method of a QuerySet. In most cases, we still need to call the original delete() functions in the superclasses in our customized delete() function. Why the customized version of delete() function may not be executed due to the underlying SQL? What does it mean by mentioning the bulk operation? -
Django Rest Framework - Using Reverse Relationships with __all__
So, I completely get the use of reverse relationships in the serializer for Django Rest Framework. And I've successfully implemented a solution that gives me what I want to see in the data output. However, the final implementation makes me a little unhappy. Essentially, I wanted to have an API result that gave me complete nested information of my related model - so Modules with all its fields and then its reverse relationship, SubModules, with all its fields. So, in my example, in order we have Modules which in turn have many SubModules. The SubModules models.py has a relationship like: module = models.ForeignKey(Module, related_name='sub_modules') Obviously, there is no direct sub_modules property defined in the Modules models.py. So, in the Modules serializer.py, I wanted to make sure that the full sub_modules objects were returned in the API call to /api/modules - not URLs or IDs. So, my initial implementation (not what I wanted) was something like: class ModuleSerializer(serializers.ModelSerializer): class Meta: model = Module fields = '__all__' depth = 1 However, this returns the following (notice, no sub_modules): { "id": 1, "created_at": "2017-02-13T11:19:28.665000Z", "updated_at": "2017-02-13T11:19:28.665000Z", "order": 1, "inactive": null, "name": "Module 1", "description": "Module 1", "price": "100.0000000000" }, The implementation that eventually … -
Django ImportError: No module named wyat.settings
I am trying to run python manage.py makemigrations and I get this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/zacmwa/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/zacmwa/.virtualenvs/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/home/zacmwa/.virtualenvs/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/zacmwa/.virtualenvs/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/zacmwa/.virtualenvs/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named wyat.settings I have used the command before in this project and it was working but now I am getting this error. I have followed the debugging procedure here:https://help.pythonanywhere.com/pages/DebuggingImportError and I can't find any error. """ WSGI config for wyat project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os import sys path = '/home/zacmwa/env/wyat/wyat' if path not in sys.path: sys.path.append(path) os.environ["DJANGO_SETTINGS_MODULE"] = "wyat.settings" # ## then, for django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Changing the path name in the wsgi file does not change the error message it still says ImportError: No module named wyat.settings -
get domain name from django request
I had a website with domain www.example1.com, and recently i have pointed another domain dns www.example2.com to same server that contains www.example1.com, so both www.example1.com and www.example2.com serves the same code but domain name should be different, and I want to get domain names from django request as below def homepage(request): domain = request.META['HTTP_HOST'] if domain == 'www.example1.com': return HTTPResponseReredirect('/new/') elif domain == 'www.example2.com': return HTTPResponseReredirect('/old/') So based on the domain name i want to redirect user to different web pages, but each and every time i used request.META['HTTP_HOST'] the output was an IP address 127.0.0.1:8001 as below META:{'HTTP_ACCEPT': ‘text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8’, 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, sdch, br', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_CONNECTION': 'close', 'HTTP_COOKIE': 'sessionid=xxxxxxxxxxxxxxxx; ', 'HTTP_HOST': '127.0.0.1:8001', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', 'PATH_INFO': u'/', 'QUERY_STRING': '', 'RAW_URI': '/', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '41280', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': u'', 'SERVER_NAME': '127.0.0.1', 'SERVER_PORT': '8001', 'SERVER_PROTOCOL': 'HTTP/1.0', 'SERVER_SOFTWARE': 'gunicorn/19.0.0', But how to get the actual domain name ?