Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoCMS: disable login via http, force https
Our DjangoCMS site is accessible via http and https. Anonymous usage via http is ok. But I want to disable logins via http. Is there a way to force the usage of https as soon as the user wants to login? Even the login-page (with username and password fields) should not be available via http. Background: I don't want the password to go over the wire unencrypted. -
How to set variables to supervisor and gunicorn config from os variables?
Hi i have set up some variables to Linux(have added them to ~/.bashrc). I know that it is possible to set variables to supervisor environment= KEY=value and to gunicorn i may simple add in config export KEY1='value' Is any way to add variables only to ~/.bashrc and take them to all configs? Thx for any help. -
Django object not iterable, why?
I want display username if he click on i want join button using ajax. I have html that look like this : <div class="who_come"> <form class="form-inline" role="form" method="post" id="joinToEventForm"> {% csrf_token %} <p align="left"><b ><button type="submit">I want join</button></b></p></b></p> </form> {% for u in who_come %} <p><a href="profile/{{u.visiter}}">{{u.visiter}}</a></p> {% endfor %} </div> i use this code to produce my ajax : $('#joinToEventForm').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check $.ajax({ type:'POST', data:{ csrfmiddlewaretoken:'{{ csrf_token }}' }, success : function () { alert("You are on Envent") } }); }); it code works, and write to database what i need, but it return to me 500 error code with TypeError: 'WhoComeOnEvent' object is not iterable. I can't understand what is a problem it is my model: class WhoComeOnEvent(models.Model): visiter = models.ForeignKey(User, related_name='WhoComeOnEvent') which_event = models.ForeignKey(Topic, related_name='WhoComeOnEvent') def __str__(self): return '%s go to %s' % (self.visiter.username, self.which_event.subject) it is my view : def p(request, pk): user = request.user topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) comment = Comments.objects.filter(pk=pk) who_come = WhoComeOnEvent.objects.filter(pk=pk) if request.is_ajax(): who_come = WhoComeOnEvent.objects.create( visiter=user, which_event=post.topic ) if request.method == 'POST': form = CustomCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.creator = user comment.save() comment = Comments.objects.create( body=form.cleaned_data.get('body'), creator=user, … -
Django-Allauth how to check if the user is authenticated with twitter or facebook python2.7
I have created an application through which I can authorize user with Facebook or twitter. Here is the code: {% if user.is_authenticated %} <a href="/accounts/logout/" title="Log out from the website"> <button type="button" class="fb__submit"> <i class="fa fa-facebook" style="font-size: 250%" aria-hidden="true"></i> Log out </button> </a> <!--<a href="/accounts/logout/"><div>Sign Out</div></a>--> {% else %} <a href="{% provider_login_url "facebook" %}" title="Login with Facebook"> <button type="button" class="fb__submit btn-space">Login in with <i class="fa fa-facebook" style="font-size: 250%" aria-hidden="true"> </i> </button> </a> <!--You are not logged in--> <!--<a href="{% provider_login_url "facebook" method="js_sdk" %}">Facebook Connect</a>--> {% endif %} {% if user.is_authenticated %} <a id="twitter_login" href="/accounts/logout"><button type="button" class="twitter__submit"> Log out<i class="fa fa-twitter" aria-hidden="true" style="font-size: 255%"></i></button></a> <!--<a href="/accounts/logout/"><div>Sign Out</div></a>--> {% else %} <a id="twitter_login" href="/accounts/twitter/login"><button type="button" class="twitter__submit btn-space"> Log in with<i class="fa fa-twitter" aria-hidden="true" style="font-size: 255%"></i></button></a> <!--You are not logged in--> <!--<a href="{% provider_login_url "facebook" method="js_sdk" %}">Facebook Connect</a>--> {% endif %} I am using Django-Allauth for the authentication in Django 1.11.5 with Python 2.7 I am not able to authenticate user with twitter as the program redirects to teh facebook link. Kindly, suggest me the improvement in my code so that the authentication will work separately. -
How to change letters in text to other letters | Python 2.7?
In my Django project I have form with field ("title"). In this field user need to write in Russian language but user can by mistake write some Latin letters. I want to change them. I use PYTHON 2.7. Next code raise error. How to fix this error? from string import maketrans eng = 'ETOPAHKXCBMetopahkxcbm' # English letters rus = 'ЕТОРАНКХСВМеторанкхсвм' # Russian letters def form_valid(self, form): form.cleaned_data['title'].translate(maketrans(dict(zip(eng, rus)))) form.save() ERROR: Traceback (most recent call last): File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 217, in post return super(BaseCreateView, self).post(request, *args, **kwargs) File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/nurzhan/dashboard.kase.kz/static_pages/views.py", line 54, in form_valid form.cleaned_data['title'].translate(maketrans(dict(zip(eng, rus)))) TypeError: maketrans() takes exactly 2 arguments (1 given) -
how to integrate project in django + vue + webpack
I am very new in django frontend stuff. I want to make a front end in django + Vue js + Webpack. i follow this website https://ariera.github.io/2017/09/26/django-webpack-vue-js-setting-up-a-new-project-that-s-easy-to-develop-and-deploy-part-1.html to write but at the end i got this errors " url(r'^$', TemplateView.as_view(template_name='my_project/spa.html'), name='home'), NameError: name 'url' is not defined". I don't understand the problem. Could you please help me or give me suggestion on how to make a new project in django + vueJs+ Webpack with path and Directory. -
Python Class routing on data-flow processing
What is the most correct and "pythonic" way to deal with a class routing for many different type of objects. I have a data flow of many different json events that have to be processed, but every kind of event has a different json structure corresponding on a different class created to deal with it, what i want to do is to catch the event, read the descriptive field that identify the type e create a corresponding object with correct class, and with a wrapper catch all the values in the json structure, but not with an infinite series of " if....elif.........else". Any advice? Thank you PS it is inside a django project -
Django import issue when updating models
I have a problem when using import after updating one of my models I get the error ImportError: cannot import name 'Team' This was my actual model from django.db import models from registration.models import MyUser from django.core.urlresolvers import reverse # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) and I wanted to add the candidat_answer to the Project model from the Response model so I imported the models to be able to use it which gave me that actual code : from django.db import models from registration.models import MyUser from survey.models.response import Response from django.core.urlresolvers import reverse # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) candidat_answers = models.ForeignKey(Response) However now I get an import error from my registration import views .. from website.models import Team, Project ImportError: cannot import name 'Team' -
Is Django test Client can work with different domains?
Can i use Client for testing functional with, for example, different regional domains of project? I try: response = client.post(reverse('uri'), data={}, HTTP_HOST='domain1') response = client.post(reverse('uri'), data={}, HTTP_HOST='domain2') And i expected, that Client get different cookies for different domains, but in fact client get single cookie. Is any way to get different cookies in this case? Or only way use CI with silenium? -
Is there any way to run unittest from button click on django sites?
I have written unit tests as well the django documentation. I can run tests from python manage.py test. That's good. But, I want to run test from a button click. This button can be anywhere in my UI. Also I want to generate a simple report on passed or failed. Is it possible with Python/Django unittest module? -
How would you make an Excel-like user interface with Django?
I am currently working on a project where the user wants the user interface to look like an Excel document. This is because the user normally writes data into an Excel document, and wants to switch to writing data straight into the user-interface instead. It should look something like this: In this project, so far, I have only used Django, and there was no need for using Bootstrap, for example. However, I would be willing to use a front-end framework in order to create this Exel-like user interface. Trying to make html-tables have been unsuccessful so far. Does anyone have suggestions on how it might be done? Thank you! -
Convert datetime to local time from Django Query to Openpyxl
Django converts the date time (I use timezone.now() to store in database) to local time in templates fine. What I need help on is when it is written to a cell in openpyxl. Right now, I simply assign the attribute of the query to the cell. query = SomeModel.objects.latest() date_recorded = query.date_recorded In templates, date_recorded is already converted to local time. No problem there. ws.cell(row=rows, column=cols).value = date_recorded The above code results to UTC. Please help me convert it to local time. Thank you. -
Linear Scale Django form widget
I am looking for some guidance in order to create a widget that is not documented at all in the django documentation but is an evident part of forms. And I am talking about Linear Scales widgets for forms. Giving the ability to a user to choose on a scale between 1-100 a score If you have any idea on how to do it, any direction I would be please to get it ;) thx you very much -
Not able to access server when invoking gunicorn via .bash file
I am not able to access server when starting gunicorn via a .bash file I made. It works when I do it manually with this command $ gunicorn project.wsgi:application --bind 192.168.1.130:8000 Created a gunicorn.bash file from tutorials. I looks like this and runs without fault. #!/bin/bash NAME="project" # Name of the application DJANGODIR=/home/username/projects/project # Django project directory SOCKFILE=/home/username/.venvs/project/run/gunicorn.sock # We will communicate using this unix socket USER=username # the user to run as GROUP=username # the group to run as NUM_WORKERS=1 # how many worker processes shoul Gunicorn spawn DJANGO_SETTINGS_MODULE=project.settings.production # which settings file should Django use DJANGO_WSGI_MODULE=project.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/username/.venvs/project/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exsist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start yout Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use daemon) exec gunicorn ${DJANGO_WSGI_UNICORN}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- I don't know how to troubleshoot this? Maybe some command to see what differs in running settings from manually starting gunicorn and from … -
Getting status of task from Django Background Tasks
I am working with Django and i want to start some background tasks. I found the library "Django Background Tasks". It has almost everything I need but I can not find how to get the status of the task (pending/running/completed) anywhere in the documentation (http://django-background-tasks.readthedocs.io/en/latest/). It would be cery helpful for me if someone could tell me how to get the status of the task. -
facebook app can not find my localserver redirected url
I working on third party social login facebook by using django-social-authpackage. But when try to login bellow error show . I also use django-allauth package and for that i use answerme facebook app.But same problem shown there also. -
Django web app: how to save thousands of variables per user
There is a website driven by Django where the user logs in and can answer thousands of questions. I want to persistently save whether a given user has answered a given question or not. My approach so far is for the User table to have thousands of columns in the PostgreSQL database - a column for each question. I read there is a 1,600 column limit in PostgreSQL, which I haven't reached yet, but would reach eventually. What is a viable architecture for this kind of functionality in a web app? -
Django database error when running tests
I have been trying to solve a database related error for a long time which prevents me from running tests unless I disable migrations temporarily before launching the task. I am getting a ProgrammingError, specifically: django.db.utils.ProgrammingError: relation "django_facebook_open_graph_share" does not exist LINE 1: ...ango_facebook_open_graph_share"."created_at" FROM "django_fa... when running test someapp --verbosity=2. This is the displayed output: Creating test database for alias 'default' ('test_dbname')... Type 'yes' if you would like to try deleting the test database 'test_dbname', or 'no' to cancel: Got an error creating the test database: database "test_dbname" already exists yes Destroying old test database 'default'... Operations to perform: Synchronize unmigrated apps: app1, app2, app3 Apply all migrations: appx, appy, appz Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying app1.0001_initial... OK ...many more lines line the one above... Applying appn.000x_someapp... OK Traceback (most recent call last): ..trace... django.db.utils.ProgrammingError: relation "django_facebook_open_graph_share" does not exist LINE 1: ...ango_facebook_open_graph_share"."created_at" FROM "django_fa... I am having trouble figuring out what migration is causing that error because the log doesn't point it out. I assume it is the one being executed right after appn.000x_someapp but it just doesn't say which one it is, so … -
How to allow access only for kubernetes pods in postgresql?
I have a Django app running in Kubernetes in GKE. And that django app connects to a static (non-containerized) postgresql server. As both of them are located in one zone, my django app uses internal IP to connect to database. I want only my django app to request a connection to the postgresql database and deny connection for requests coming from other IPs. To do that, in pg_hba.conf I did this: host all all 14.133.0.0/24 md5 Because all internal IPs start with 14.133. However, the requests are coming from pod IPs and thus requests for connection are denied. An example for a Pod IP can be 14.4.123.32. So, if I do the following in pg_hba.conf, the problem will be fixed: host all all 14.0.0.0/8 md5 Another thing to note is that Pod IPs always change. So, this solution will break once the pod is updated. What is the best practice to go about this? -
Test asc for arg which is self
Test should give 400 status code, but it ascs for self as argument, but isn't it a mistake? This is test: def test_cab_number_does_not_exist(self): data = {"cab_number": "0"} self.client = self.Client url = reverse('api:orders') response = self.client.post(url, data) response_content = json.loads(response.content) cab_number = response_content['cab_number'] self.assertEqual(response.status_code, 400) This function gives mistake like: TypeError: test_cab_number_does_not_exist() takes exactly 1 argument (0 given) . I don't know how to fix it. -
Celery is constantly starting with supervisor
How to run celery in Supervisor? This is my .conf file: [program:celery_worker] command=celery -A urlextractor worker -l info process_name=%(program_name)s ; process_name expr numprocs=1 directory=/home/omuntean/Django/urlextractor /urlextractor ; directory to cwd to before exec (def no cwd) autostart=true ; start at supervisord start (default: true) autorestart=unexpected ; when to restart if exited after running user=root stopasgroup=true stopsignal=QUIT stdout_logfile=/var/log/urlextractor /celery_w_out.log stderr_logfile=/var/log/urlextractor /celery_w_err.log priority=100 If I run the celery command normally it works fine without any errors, however, when I type: sudo service supervisor start Then see the status with: supervisorctl status It gives me: celery_worker RUNNING pid 10651, uptime 0:00:02 urlextractor RUNNING pid 9761, uptime 0:08:08 And then after I type again it gives me: celery_worker STARTING urlextractor RUNNING pid 9761, uptime 0:08:09 Why is this happening and how can I make it work? -
Organizing a one-to-one relationships for checksums
Django==1.11.6 I'd like to collect checksums for uploaded files. I have done it via GenericRelation. This is clumsy. Because it is one-to-many relationship whereas a checksum is definitely one-to-one. Could you help me understand whether this can be rewritten as a one-to-one relationship case? @receiver(post_save, sender=ItemFile) @receiver(post_save, sender=Image) def save_file_checksum(sender, instance, **kwargs): """ Save a ckecksum for a file. """ checksum = get_checksum(instance.file.path) existing_checksum = instance.checksum.first() if existing_checksum: existing_checksum.checksum = checksum existing_checksum.save() else: FileChecksum.objects.create(content_object=instance, checksum=checksum) class ItemFile(models.Model): file = models.FileField(blank=False, max_length=255, upload_to=get_item_path, verbose_name=_("file")) checksum = GenericRelation(FileChecksum) class Image(models.Model): file = models.ImageField(blank=False, verbose_name=_("Image"), max_length=255, upload_to=get_sheet_path) checksum = GenericRelation(FileChecksum) class FileChecksum(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') checksum = models.CharField(blank=True, null=False, max_length=255, verbose_name=_("checksum")) def __str__(self): return "{} {}: {}".format(self.content_type, self.content_object, self.checksum) -
Running multiple instances of daphne behind a load balancer: django-channels
I am using django-channels to add HTTP2 & WebSocket support for my application. I could not find a lot of documentation as to how to scale channels. Below is my nginx configuration that load balances multiple instances of daphne running on the same machine but different ports. Is this the correct way to do it? upstream socket { least_conn; server 127.0.0.1:9000; server 127.0.0.1:9001; server 127.0.0.1:9002; server 127.0.0.1:9003; } server { listen 80; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/niscp/home-screen; } location /nicons/ { root /home/niscp/home-screen; } location / { include uwsgi_params; uwsgi_pass unix:/home/niscp/home-screen/home-screen.sock; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://socket; } } Along with that, I am running individual instances of workers to listen to individual channels in the following manner: python manage.py runworker --only-channels=websocket.connect python manage.py runworker --only-channels=websocket.receive python manage.py runworker --only-channels=websocket.disconnect I have got uwsgi to handle all http requests the way django normally handles them. All daphne and workers do is handle WebSocket requests. Is this a viable method to scale django-channels, or is there something I could do better? -
'Authorization: Bearer token' vs 'Authorization: token' (Can't use Bearer header in Oauth2)
I'm using Oauth2. And somehow I can't attach Bearer header. It only work without Bearer Header. (But header Token header works) Is there any advantage of using Bearer? Should I use it? def get_queryset(self): # signing self.request.user header_token = self.request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: try: token = sub('Token ', '', self.request.META.get('HTTP_AUTHORIZATION', None)) token_obj = Token.objects.get(key = token) self.request.user = token_obj.user except Token.DoesNotExist: pass qs = Outfit.objects.all(user=self.request.user) return qs Can I do this with Bearer header? -
Leverage Browser caching django-nginx not working
I prepare a django project with server engine nginx using gunicorn for that. I am trying to work out page insights and I want to leverage browser caching in my nginx settings. My directory layout of project is: mainprojectfolder --mainproject ----static manage.py --media_cdn --static_cdn In my settings.py I arranged static files : STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = "/home/ytsejam/public_html/ozkansimple/static_cdn/" MEDIA_ROOT = "/home/ytsejam/public_html/ozkansimple/media_cdn/" My nginx settings are server { listen 80; server_name www.ozkandurakoglu.com; client_max_body_size 4G; root /home/ytsejam/public_html/ozkansimple/; access_log /home/ytsejam/public_html/ozkansimple/logs/nginx-access.log; location /static/ { autoindex on; alias /home/ytsejam/public_html/ozkansimple/ozkand/static/; } location /media/ { autoindex on; alias /home/ytsejam/public_html/ozkansimple/media_cdn/; expires 365d; } #location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { # expires 365d; # } } when I comment out cache , all my static and media files gets 404 and nothing is shown. can you help me ? Thanks