Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi Guys, i'm trying to link a word (ex: "Pet" ) to a search engine using django
whenever someone click on "Pet", the search engine must search and return all contents in which the word "Pet" is included. "This will allow a user to save some typing time" Any advice please! -
DRF serializer ValidationField / CaptchaField
As the name suggests, I'd like to create a field that has no internal value, has no external representation, and should be input-only however the value of that input will be removed by the end of the validation process (i.e. not included in validated data). My thoughts on how to go about creating this Field: HiddenField is unsuitable because it does not take user input MethodField is unsuitable because it is read-only (whereas I want input-only) serializer.Field requires to_representation and to_internal_value implementations, neither of which make sense to use since the input value for this field does not map to any model field The usage case would be with a snippet similar to the following, where validation passes if the return is True: payload = {'secret': 'YOUR_SECRET_KEY', 'response': request.data.get('g-recaptcha-response')} return requests.post('https://www.google.com/recaptcha/api/siteverify', payload).json().get('success', False) How should I go about creating this field? -
Django: How can I access celery flower page in production mode?
In development mode(local), it is really easy to access flower page (http://localhost:5555) But in production mode, it is difficult to access flower page. I'd like to access flower dashboard page with this url: https://spacegraphy.choislaw.xyz/flower/ (Domain name : choislaw.xyz) I refered http://flower.readthedocs.io/en/latest/reverse-proxy.html#reverse-proxy and this is what I did: nginx.conf http { include mime.types; default_type application/octet-stream; sendfile on; server { listen 80; server_name spacegraphy.choislaw.xyz; client_max_body_size 4G; keepalive_timeout 5; return 301 https://$server_name$request_uri; } # HTTPS server server { listen 443 default_server ssl; server_name spacegraphy.choislaw.xyz; client_max_body_size 4G; keepalive_timeout 5; ssl_certificate /etc/letsencrypt/live/spacegraphy.choislaw.xyz/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/spacegraphy.choislaw.xyz/privkey.pem; location / { proxy_pass_header X-CSRFToken; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Real-IP $remote_addr; proxy_set_header HOST $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:4349; proxy_redirect off; } # Flower location /flower/ { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Real-IP $remote_addr; proxy_set_header HOST $http_host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_http_version 1.1; proxy_pass http://localhost:5555/; proxy_redirect off; } } } And I execute flower server: $ celery --workdir=spacegraphy/ --app=spacegraphy.celery:app flower And I access https://spacegraphy.choislaw.xyz/flower/, it shows like this: And If I click any link, Did I miss something? Do I separate flower server from application server? Btw, Is it usual to run flower server on production server? -
Understanding django channels persistant data
I am trying to grasp the concept of persistant data in django channels. I have searched the reference and other parts but didn't clear my confusion. I would really appreciate if you help me understand better. consumers.py: @channel_session def ws_connect(message): # Work out room name from path (ignore slashes) room = message.content['path'].strip("/") # Save room in session and add us to the group message.channel_session['room'] = room Group("chat-%s" % room).add(message.reply_channel) Q.1 In the above line message.channel_session['room'], is the room another property of the message? Like it tells which session the message belongs to? @channel_session def ws_message(message): Group("chat-%s" % message.channel_session['room']).send({ "text": message['text'], }) Q2. In the line Group("chat-%s" % message.channel_session['room']).send({, why are we not using the room variable like in the ws_connect() function, but instead we are using the channels_session? @channel_session def ws_disconnect(message): Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel) Q3. Same like above, why are we not using the room variable to discard from the group? Also is it not neccesary to remove the room from the session? -
Can celery,celerybeat and django-celery-beat dynamically add/remove tasks in runtime without restart celerybeat?
I tried everything I can found including: stackoverflow How to dynamically add / remove periodic tasks to Celery (celerybeat) Can celery celerybeat dynamically add/remove tasks in runtime? Github issue How to dynamically add or remove tasks to celerybeat? What I got from the above is if I only use celery and celery beat I have to restart the celery beat after I add/remove the tasks. But I don't have to restart it if I combine django-celery-beat. I follow the docs step by step: from celery import Celery from celery.schedules import crontab app = Celery('tasks') app.config_from_object('celeryconfig') app.conf.timezone = 'UTC' @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg) My celeryconfig BROKER_URL = 'amqp://rabbit' CELERY_RESULT_BACKEND = 'rpc://rabbit' CELERY_RESULT_PERSISTENT = True # CELERY_ACKS_LATE = True CELERY_DEFAULT_DELIVERY_MODE = 2 CELERY_TASK_RESULT_EXPIRES = 3600 CELERYBEAT_SCHEDULER ="django_celery_beat.schedulers:DatabaseScheduler" My celery beat run command celery -A tasks beat -l info -S django This works well, The tasks run as expected.After that, I wrote a script to add tasks at the runtime import django django.setup() from … -
OneToThree django model
I have a classic model containing some contact datas (mail, addr, names, ...), and an other wich is supposed to link to three contacts (an admin, an owner, a tech). A contact can be registered as admin and as tech for example. class Contact(django.db.models.Model): user = models.OneToOneField(User) city = models.CharField(max_length=255, blank=True) country = models.CharField(max_length=2, blank=True) email = models.EmailField(max_length=255, blank=True) first_name = models.CharField(max_length=255, blank=True) family_name = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=255, blank=True) class Product(... Some parents) name = models.CharField(max_length=255) contacts ? I don't know how to link 3 contacts to my other Model ... and generate a form with a queryset already existing. Some advices ? Thanks -
Django 1.10 issue with python-social-auth
I am trying to use django-social-auth in one of my project. However migrate command ends with this error: class JSONField(six.with_metaclass(models.SubfieldBase, models.TextField)): AttributeError: 'module' object has no attribute 'SubfieldBase' What could be the solution? -
Should I Use Sqlite or Postgres For a website which checks weather a particular data is in the database
I am Developing a django app where a user inputs a Person's Name Or a Company's Name And the webapp shows if it already exists in the database. Its an internal application for our company. Should I use sqlite or postgres for this particular application ? -
python packages in ~/.local/lib/python2.7/site-packages
I was trying to install the django framework with pip. sudo pip install django And it was installed successfully but the django wasn't running as expected so I tried sudo apt-get install python-django with this django was installed but it was the older version=1.7.6 instead of 1.10.4 After that I came to know that using the pip the django was installed in this location ~/.local/lib/python2.7/site-packages And there are few other packages as well in that directory. Why are these packages in ~/.local/lib ? How can I fix this problem? -
explicit permissions not getting assigned to custom user in Django admin
I have created custom user in Django as like below class ClientEmployeeMaster(AbstractBaseUser,PermissionsMixin): . . some custom fields ... I also have my custom baseuser manager as like below class ClientEmployeeManager(BaseUserManager): def _create_user(self,client_employee_email,password,**extra_fields): """ create and save user with given username and password """ now = datetime.now() if not client_employee_email: raise ValueError(' the given email must be set') email = self.normalize_email(client_employee_email) user = self.model(client_employee_email=email, client_employee_added_date=now, client_employee_last_login=now,**extra_fields) user.set_password(password) user.save() return user def create_user(self,client_employee_email, password=None, **extra_fields): return self._create_user(client_employee_email,password=None,**extra_fields) def create_superuser(self,client_employee_email,password,**extra_fields): return self._create_user(client_employee_email,password, **extra_fields) in admin.py I have registered this custom user @admin.register(ClientEmployeeMaster) In the admin site this form is working and creating custom user, but if I assign some permissions explicitly to new user then this permissions not setting up. If I set is_superuser=True then its assigning all permissions to it -
Reduce display element from choice list Django
I have a question about my project and I think I need some advices in order to get the expected result. I created a individual formulary which works very well and now I want to create my BirthCertificate Form. The second one takes values from the first one as following : But, to my mind the problem is situated with ID Parent1 and ID Parent2. This field displays all values for each row but I would like to make different : First solution : I display all rows but just Lastname Firstname Birthdate Second solution : I try to make a research bar letting to get Parent1 and Parent2 The problem is : How I can do that ? This is my models.py file : 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=1, 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 = models.ForeignKey(Country, related_name='Pays_Naissance', verbose_name='Pays de naissance') fk_parent1 = models.ForeignKey(Identity, related_name='ID_Parent1', verbose_name='ID parent1', null=True) fk_parent2 = models.ForeignKey(Identity, related_name='ID_Parent2', verbose_name='ID parent2', null=True) This is my forms.py file : from django import forms from BirthCertificate.models import * class BirthCertificateForm(forms.ModelForm) … -
Django, query to filter instead of iterating
So I have this database on auctions (WoW) and I update by tables once an hour. Simplified it looks like this: class Auction(models.Model): auction_id = models.IntegerField() item_id = models.IntegerField() owner = models.CharField() buyout = models.IntegerField() The data I get is in the form of a list of dictionaries looking like this: new_auctions = [ { 'auction_id' : <int>, 'item_id' : <int>, 'owner' : <string> , 'buyout' : <int> }, # more auctions ] Now I want to check if an auction has been relisted or not. And now I want to see if: The auction is gone There is another auction by the same owner for the same item The price is less then the former auction Then I will assume the auction was not sold but relisted. My current solution started off by getting all the auctions that have dissapeared: auction_ids = map(lambda d: d['auction_id'], new_auctions) dead_auctions = Auction.objects.exclude(auction_id__in=auction_ids) So now I thought I could iterate over every auction in dead_auctions and see if there's an auction in new_auctions by the same owner for the same item for a lower price. I have this feeling that it's inelegant and possibly inefficient because Just finished a course in algorithms and … -
Overriding the EmailMessage class of Django
I am working on an existing Project which uses Django 1.7 We are integrating our Email services with Amazon Ses. This has raised a problem that we are not able to monitor which email are sent successfully and which one's have failed. So I am thinking of logging the errors where email sending has failed. Currently EmailMessage class of django.core.mail is being used to send the emails and adding the code for logger everywhere will be a dirty solution. So I am thinking of overriding the EmailMessage class and Using my Custom class to send emails and add the logic for logging there. Here's the code for that from django.core.mail import EmailMessage class EmailMessaging(EmailMessage): def send(self): result = super(EmailMessaging, self).send() if(result): print 'success' #do nothing successful else: print 'fail' #failed:- add event to logger | Db | Sentry When I try to consume myClass for sending the email it throws an error:- from email_message import EmailMessaging message = EmailMessaging("this is the subject", "this is the body”, "sender@abc.com", ["myemailaddress@abc.com”]) SMTPException: STARTTLS extension not supported by server However, if I use the EmailMessage class it is working fine. I am not able to understand why is this happening. From what I have … -
how can I extract this and make it a variable? django
I have an output like this. data = <QueryDict: {u'product_name': [u'L4'], u'price': [u''], u'product_description': [u''], u'id': [u"[u'1']"], u'product_status': [u'1']}> honestly I have no idea how the output is like this but if I want to get the id. I used something like this (data['id'][0]) but this isn't getting my anything and if I use (data['id']) this is what I get u'[u\\'1\\'] when I post this kind of data, I would get such error invalid literal for int() with base 10: '[' -
Pass markdown from file to template in Django view
I'm trying to pass the contents of an *.md file from my Django view for rendering using Showdown (JS code below), but I get: Uncaught SyntaxError: Invalid or unexpected token: var converter = new showdown.Converter({ 'github_flavouring': true, 'tables': true }); var convert = function() { $('#preview').html(converter.makeHtml($('{{markdown}}')); }; convert(); -
Django template row alternate for multiple content
I've a template design like this <div class="row"> <div class="col-sm-8"></div> <div class="col-sm-4"></div> </div> <div class="row"> <div class="col-sm-4"></div> <div class="col-sm-8"></div> </div> and I've tried using this article django template rows of multiple items But output doesnt come as required. How can I do as required. -
How to append more data in FormData for django?
My reference is here How to send FormData objects with Ajax-requests in jQuery? The answer on that link worked on my program. My problem is how to append more data in FormData? I'm using python django and I would like to know where I can put the csrfmiddlewaretoken and inputfilename Before, this is what I have in form data var form_data = { inputfilename: $("#filename").val(), inputfile: $("#file").val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), ajax: 1 }; and now, var form_data = new FormData(); form_data.append('file', input.files[0]); -
django1.7 with mongodb issue?
hi i am getting this error when i run python manage.py runserver File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 63, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 17, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 48, in __init__ self.build_graph() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 179, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()): File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 1383, in get_table_list raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_table_list() method') NotImplementedError: subclasses of BaseDatabaseIntrospection may require a get_table_list() method -
ajax to server and then to database in django project
I am writing a code to take data from a form, send to server via ajax(.js file). I want to send the same data from server to database, here my database is mongo db. ajax from .js file: function letsPostIt(data) { console.log(data); $.ajax({ type: 'POST', url: '/gmaps', data: { location: data }, contentType: "application/json", dataType: 'json' }); } Now I cannot write my views.py and models.py file in order to send the data from here to my database. My current views.py file: from django.shortcuts import render from registration.models import POST from django.http import HttpResponse def gmaps(request): post_text = request.POST.get(request.POST) post = POST.objects.get(text=post_text) return render(request,'gmaps.html',{}) post.save() return HttpResponse(post_text) models.py file: from django.db import models from mongoengine import * class POST(Document): text = StringField(max_length=120, required=True) I am new to django and hence have a very less idea about the syntax and terms used. Any help in this would be really appreciated. -
Can I return a response in a function within a view function?
Here's the view function: def bar(request): ... record = get_record_from_model(model, **kwargs) ... return JsonResponse(data_to_response) and here's the function used in view function: def get_record_from_model(model, **kwargs): try: return model.objects.get(**kwargs) except model.DoesNotExist: error_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"]) return JsonResponse(error_data) Can I return JsonResponse(error_data) to the client in get_record_from_model function when exception occur(Something like raise Http404)? -
python html tamplate ternary operator
I've came across with different python ternary operators such as: a if b else 0 but it doesn't work when I tried to include it inside django html template {% a if b else 0 %} here is the exact code that I'll be using but won't work: {% 'error' if form.title.errors else '' %} or {% form.title.errors ? 'error' : '' %} I don't like to do the usual {% if form.title.errors %}error{% endif %} because it looks bulky in my opinion specially if I added an else statement. Any suggestions? or should I just stick with it? -
How to write queries in python scirpt which are connected to djagno, and after that we can import that's queries?
Data : { "Fruit": "Pomegranate", "District": "Nasik", "Taluka": "Nasik", "Revenue circle": "Nasik", "Sum Insured": 28000, "Area": 1200, "Farmer": 183 } { "Fruit": "Pomegranate", "District": "Jalna", "Taluka": "Jalna", "Revenue circle": "Jalna", "Sum Insured": 28000, "Area": 120, "Farmer": 13 } { "Fruit": "Guava", "District": "Pune", "Taluka": "Haveli", "Revenue circle": "Uralikanchan", "Sum Insured": 50000, "Area": 10, "Farmer": 100 } { "Fruit": "Guava", "District": "Nasik", "Taluka": "Girnare", "Revenue circle": "Girnare", "Sum Insured": 50000, "Area": 75, "Farmer": 90 } { "Fruit": "Banana", "District": "Nanded", "Taluka": "Nandurbar", "Revenue circle": "NandedBK", "Sum Insured": 5000, "Area": 2260, "Farmer": 342 } { "Fruit": "Banana", "District": "Jalgaon", "Taluka": "Bhadgaon", "Revenue circle": "Bhadgaon", "Sum Insured": 5000, "Area": 220, "Farmer": 265 } I want to write all types of combination queries, if someone want information only for Fruit which is Guava then output will be exact data for Guava only. also if some one want information only for Fruit which is Banana & Guava then output will be exact data for Banana and Guava. If fruit is equal to Banana output will be data for Bananna If fruit is equal to Guava output will be data for Guava If fruit is equal to Banana and Guava output will be data for Banana … -
django use Case When to compose sql query
I have data format like this: [ { "name":"abc", "number":120, "total":500 }, { "name":"def", "number":30, "total":400 } ] and I have a django query logic like this: Table.objects.update( number = Case( When(name=data[0]['name'], then=Value(data[0]['number'])), When(name=data[1]['name'], then=Value(data[1]['number'])), When(name=data[2]['name'], then = Value(data[2]['number'])), ... When(name=data[499]['name'], then = Value(data[499]['number'])), default=F('number'), ) ) I want to use code to generate the When part so I use list comprehension to generate it, and then use ','.join(query_list) to remove the bracket [ ] But here is problem : it said TypeError: sequence item 0: expected string, When found I can't convert it to string , because When(name=data[499]['name'], then = Value(data[499]['number']) should be a object. How can I do to fix this??? query_list = [When(name=data[i]['name'], then=Value(data[i]['number'])) for i,item in enumerate(data)] part_of_sql= ','.join(query_list) print(part_of_sql) Table.objects.update( number=Case( part_of_sql, default=F('number'), ) ) -
Django templates and "choice_set"- Why not use "context"? What's "best practice"?
The Django tutorial (part 4, https://docs.djangoproject.com/en/1.10/intro/tutorial04/), for the "detail" view, uses the template to generate the "choice_set" rather than passing the "choice_set" through the "context" dict. Isn't this the problem the context dict was supposed to solve? Is there any downside to generating the choice.set data in the view & providing it to the template through the context dict? -
how set MIDDLEWARE_CLASSES in django-nonrel1.5 with mongodb engine?
'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', I am getting this error: Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/handlers.py", line 72, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 236, in __call__ self.load_middleware() File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 55, in load_middleware raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)) ImproperlyConfigured: Middleware module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" class Thanks in advance!