Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery routing not working
default_exchange = Exchange('default', type='direct') ALL_QUEUES = ( Queue("sms", default_exchange, routing_key="sms_key"), Queue("email", default_exchange, routing_key="email_key")) ALL_ROUTES = {"tasks.email_task": {"queue": "email", "routing_key": "email_key"}, "tasks.sms_task": {"queue": "sms", "routing_key": "sms_key"}} app = Celery("mysite", broker='amqp://guest:guest@localhost:5672//') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.task_queues = ALL_QUEUES app.conf.task_routes = ALL_ROUTES app.conf.task_default_exchange = 'default' app.conf.task_default_exchange_type = 'direct' app.autodiscover_tasks() Following call sends the email but routing/queueing is not happening which i can confirm by seeing the web-ui view of rabbitmq. email_task.apply_async("abc@gmail.com", "xyz@gmail.com", "sub", "body") I tried above call with exchange and routing_key with no success. -
Django Web Pages
I have created some web pages using Django. I have used Django Login feature. I am facing an issue.When user is login to some page say xyz.html using user Id and password.If user copies the link of "xyz.html" and copy it to some other search bar and paste it "xyz.html" page will open without any authentication. I want to restrict the user so the page can not be opened without user authentication. Regards NMahale -
distribution of application on the cloud (not SaaS)
I want to distribute my software with cloud account . Ideally I want cloud provider to sell the app for me and to handle the transaction. Currently I work with Heroku and Heroku does not provide such an option. What are my options with other providers(ideally similar to Heroku)? -
Preload data on Heroku first time creation
I create a new deployment for every new customer on Heroku platform. However as my app gets deployed to HEroku some default data should be uploaded. What is my best option? Each time I redeploy - existing data should remain. -
Django validated_data type hint
I am studying type hints and would like to follow because it can help me troubleshoot the bug during development. If validated_data is single type of key and value for example mydict = { "age": 123 } def read_mydict(mydict: typing.dict[str, int]): # do something Question: (Pdb) validated_data {'type': 2, 'file': <InMemoryUploadedFile: cmoc_import_file.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>, 'description': 'Test again validated_data'} Then I have to write function to read that validated_data. def add_d_records(validated_data: Dict[?,?]): """ Take validated_data and put it to UserProfile :param validated_data: :return: """ import pdb; pdb.set_trace() How to write the type hint? Or I have to write my own class to handle this? -
Django + SSL + mysql: TypeError: __init__() got an unexpected keyword argument 'server_hostname'
I used Djano to build a simple restful API server. SSL has been introduced to the communication between the server and the remote database to enforce security. When the API server tried to write to the database, I got the following error: File "/app/anaconda/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/app/anaconda/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/app/anaconda/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/anaconda/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/app/anaconda/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/app/anaconda/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = self.handle_exception(exc) File "/app/anaconda/lib/python2.7/site-packages/rest_framework/views.py", line 434, in handle_exception self.raise_uncaught_exception(exc) File "/app/anaconda/lib/python2.7/site-packages/rest_framework/views.py", line 471, in dispatch response = handler(request, *args, **kwargs) File "/app/anaconda/lib/python2.7/site-packages/rest_framework/decorators.py", line 52, in handler return func(*args, **kwargs) File "/app/mobile/mpq_backup_response/mpq_backup_response/backup_response/views.py", line 39, in sms q.save() File "/app/anaconda/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/app/anaconda/lib/python2.7/site-packages/django/db/models/base.py", line 821, in save_base with transaction.atomic(using=using, savepoint=False): File "/app/anaconda/lib/python2.7/site-packages/django/db/transaction.py", line 158, in __enter__ if not connection.get_autocommit(): File "/app/anaconda/lib/python2.7/site-packages/django/db/backends/base/base.py", line 365, in get_autocommit self.ensure_connection() File "/app/anaconda/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/app/anaconda/lib/python2.7/site-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/app/anaconda/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 265, in get_new_connection conn = Database.connect(**conn_params) File "/app/anaconda/lib/python2.7/site-packages/pymysql/__init__.py", line 90, in Connect return Connection(*args, … -
Django Integrity Error when adding post in a form that excludes a foreign key
the cause of the error is simple. The admin site asks me to select or browse user when I am logged in. So, I excluded the field to hide it in the admin form. It generates the integrity error. How do I tell django to attach the currently logged in user (in the admin area) as the creator of the object? I have seen a few posts that require me to make use of forms.py but I want to use the default admin template. Where do I make the edits at least? -
Check if user is online and notify to the connected user in Django
I am writing a chat module for my project using Django and stomp protocol (with ActiveMQ). When a user logs in, his connected user will be able to chat with him. This is the model to represent the connection class Connection(AppModel): connection_host = models.ForeignKey(Member, related_name="connection_host") connector = models.ForeignKey(Member, related_name="connector") accepted = models.BooleanField(default=False) def __unicode__(self): return "%s - %s" % (self.original_member.nickname, self.target_member.nickname) I can actually know who are online when the page is refreshed, thank to this; however, I don't know how to auto-publish those information to the page through the ActiveMQ. For example, when a user in the chatbox, he posts something and then on the server, it will send the message to the broker to broadcast back to the other end. However, when the user is online, there is no event in order to trigger the message. The only solution I can think of is making a Celery periodic task every 10 seconds to broadcast back to the all the online users their online connections; however, this is a bit tedious. Is there any better way to do so ? -
Error 404 getting static directory
I have a a problem in running my project on vbs server on the cloud "Ubunut machine" the code is working just fine on my local but in the server it seems that it can't access the static directory i don't know why Here is my project structue : |-- blogango | |-- __init__.py | |-- __init__.pyc | |-- admin.py | |-- admin.pyc | |-- akismet.py | |-- akismet.pyc | |-- conf | | |-- __init__.py | | |-- __init__.pyc | | |-- settings.py | | `-- settings.pyc | |-- feeds.py | |-- feeds.pyc | |-- forms.py | |-- forms.pyc | |-- management | | |-- __init__.py | | `-- commands | | |-- __init__.py | | |-- comment_notify.py | | `-- update_reactions.py | |-- migrations | | |-- 0001_initial.py | | |-- 0002_add_reactions.py | | |-- 0003_add_rendered_html.py | | |-- 0004_add_comment_moderation.py | | |-- 0005_added_reaction_url.py | | |-- 0006_auto__chg_field_comment_user_url__chg_field_reaction_user_url__add_fie.py | | |-- 0007_auto__chg_field_blogentry_publish_date.py | | |-- 0008_auto__chg_field_comment_user_url__chg_field_reaction_user_url.py | | |-- 0008_auto__chg_field_comment_user_url__chg_field_reaction_user_url.pyc | | |-- 0009_auto__chg_field_comment_user_url__chg_field_reaction_user_url.py | | |-- 0010_auto__add_field_comment_user_ip__add_field_comment_user_agent.py | | |-- 0011_auto__chg_field_blogentry_slug.py | | |-- __init__.py | | `-- __init__.pyc | |-- models.py | |-- models.pyc | |-- search.py | |-- search_indexes.py | |-- static | | `-- … -
Testing apps.py in django
How can I write a test to cover my apps.py files for each model in a django application? I need 100% code coverage and cannot figure out how to test these files. Example of one of my apps.py files: from django.apps import AppConfig class ReportsConfig(AppConfig): name = 'reports' -
Return dictionary from AJAX call using Django
I am making an AJAX call and would like it to return a dictionary of objects. No matter how I try to return the data, it throws an exception. As far as I can tell, it can only be because the response data is not in JSON format. Any help would be really appreciated def populateSources(request): if request.is_ajax(): try: org = Organization.objects.get(pk=int(request.GET.get('org_id'))) std_source_columns = StandardizedSourceColumn.objects.all() std_sources = StandardizedSource.objects.all() # Standardized Tables API Client std_tables_api_client = standardizedtablescli.ApiClient() std_tables_api_client.host = os.environ.get('STANDARDIZED_ENDPOINT') std_tables_api = standardizedtablescli.StandardizedtablesApi(std_tables_api_client) org_std_sources = std_tables_api.get_standardized_tables_by_id(org.id) ready_tables = std_tables_api.get_ready_raw_tables(org.id) ready_table_mapping = dict() ready_table_names = [] for table in ready_tables: ready_table_names.append(table) for key, value in org_std_sources.iteritems(): curr_source = StandardizedSource.objects.filter(name=key) if len(value['standard_mappings']) == 0: if key in ready_table_names: ready_table_mapping[curr_source] = False else: ready_table_mapping[curr_source] = True json_response = {} json_response['result'] = ready_table_mapping return HttpResponse( json.dumps(json_response), content_type="application/json" ) except: return HttpResponse( json.dumps("error"), content_type="application/json" ) -
How would I get an invited user to submit a reference about a user on the site? Django
If you could point me in some directions, that would be great. Goal: -I'd like to get a user's friend to submit a reference about the user on the site. -i'd like that reference to appear on the user's profile -the goal is to help verify how good the user is as a person One possible flow -send friend a link to a form that is specific to a user -friend fills out form -user decides to approve or decline that comment -if approved, that info gets added to the database associated with the user -that info appears on user's profile -
Filter and return dates with datetime
I'm on django 1.8 and i have a problem in filtering and return months from an object with date-time field and here is my code : Expense.objects.filter(is_done=True).dates('created_date','month',order='DESC') The error is so confusing -
Django gunicorn with MySQLdb module package
I'm using Django with MySQL (mysql-python 1.2.5) and I can run python manage.py runserver 0.0.0.0:8000 fine. I would like to deploy my Django app with Gunicorn by running gunicorn -b 0.0.0.0:8000 wsgi:application. However, Django's throwing error with MySQLdb: File "/Library/Python/2.7/site-packages/django/db/backends/mysql/base.py", line 28, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb Any idea why it has this error? Thanks. -
For loop to create Scatter chart with CanvasJs using Django data as input
I found that I can create nice scatter plot with CanvasJS into my HTML templates (see the link: http://canvasjs.com/docs/charts/chart-types/html5-scatter-chart/) I am creating a website using Django and a MySQL database. In one of my tables (models) I have 3 fields VARCHAR containing different values: - the 1st field contains values for X axis. - The 2nd field contains values for Y axis. - The 3rd field contains one letter labels. Here is an example for one entry if it is not clear: 1st field: 999.99;-89.01;-60.29;-145.83;-140.76;-148.24;-88.70;56.92;69.08;-121.37 2nd field: 143.12;146.51;143.73;177.58;121.68;116.45;-14.05;20.77;15.82;168.20 3rd field: CPPEEECTTE As you can see, values are separated by ";" in fields 1 and 2. there are 10 values in field 1, 10 values in field 2, and 10 corresponding letter labels. All fields are 1 long string. So my question is simple, I don't know how to make a for loop in javascript so that those coordinates will be taken in the scatter chart. Here is the example of the canvasjs for scatter chart I want to obtain: <!DOCTYPE HTML> <html> <head> <script type="text/javascript"> window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { title:{ text: "Title of my scatter chart" }, data: [ { type: "scatter", dataPoints: … -
Nginx config error error:2006D080:BIO routines:BIO_new_file:no such file)
Hello all I am new to nginx and am in serious need of help I am configuring my setup based on Digital Oceans guide. I know I messed up somewhere I have read countless docs and maybe I missed something. I believe it is where my root directory is pointed to or how I set it up. Here is my code: server { listen 80 default_server; listen [::]:80 default_server; listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name www.xxx.com; include snippets/ssl-xxx.com.conf; include snippets/ssl-params.conf; root /home/sammy/myproject/profiles/templates; index index.html index.htm home home.html; root /var/www/html; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/expo/static/; } location /static/admin/ { #default_type text/javascript; alias /home/sammy/static/static-only/admin/; } location /media/ { alias /home/sammy/static/media/; } location / { include proxy_params; proxy_pass http://unix:/tmp/myproject.sock; } } Any and all help is greatly appreciated. Thank you in advance. -
Passing additional login params to custom django auth backend
I want to set up a login form where I use 2 different authentication servers at login. forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm GROUP = ( ('', '--------------'), ('red_server'), ('blue_server'), ) class LoginForm(AuthenticationForm): group = forms.ChoiceField(choices=GROUP, required=True, help_text="Choose one of the groups to login." ) field_order = ['group', 'username', 'password'] How do I pass the "group" variable into the custom backend? The following code does not work, because the "group" variable can not be found. backends.py (doesn't work): from django.contrib.auth.models import User from django.conf import settings def client_for(username, password=None, group=None): """ Get a connection for the given user. """ auth_server = settings.AUTH_SERVER[group] # here goes the server authentication code class UnixBackend(object): """ Authenticate the given user as a Unix account on a remote host. """ def authenticate(self, username=None, password=None): try: client_for(username, password, group) except paramiko.AuthenticationException: return None try: user = User.objects.get(username=username) except User.DoesNotExist: # Create a new user if the user does not exist yet user = User(username=username) user.is_staff = False user.is_active = True user.save() return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None -
How to send data from form to pdf template using Django easy_pdf
I try to this code. When I try to click submit button, I want to send data via 'POST' method. But I am seeing white screen, not pdf. But When I write the Pdf's url on browser directly, Code is working. class ProductOfferPdfView(PDFTemplateView): template_name = 'hotels/product_offer-pdf.html' def get_context_data(self, **kwargs): data = product_offer_pdf(self.request) print data return super(ProductOfferPdfView, self).get_context_data(data) -
How can I import template tags provided in an external package into a Django tag library?
I have a module thirdparty_lib.contrib.django.tags.foo - which is not part of a Django app - that contains about this code: from django import template register = template.Library() @register.filter def transform(obj, arg): pass I'd like to use the filters and tags from it in an actual Django app and tried this naive approach in mydjangoapp/templatetags/foo.py: from thirdparty_lib.contrib.django.tags.foo import * However this yields a TemplateSyntaxError, stating that foo isn't a registered tag library. The app does work when the contents of the prior are copy-pasted in bulk into the latter. -
python django models request.user
I am trying to implement a model that automatically filters data based on the user. I was able to modify the user model and add a value for "company" that references a table of companies. I have a table that has a company value as well (call it data_table). Ideally when ANY user logs into the system, the data filtered to match company value on user to company value on data_table. So far I have it working, but I want to overwrite the get_query method to incorporate what I have and I can't figure out how to get the current logged in user into the model without passing it from the view. I would think that in the below I could just use in models.py: current_user = request.user cid = current_user.company.id The advantage being I don't have to remember to put the filter in when I use the model. The error that gets thrown is: Exception Value: global name 'request' is not defined Here is what works: models.py: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser class Company(models.Model): name = models.CharField(max_length=40, blank=True) def __str__(self): return self.name class User(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, default=1) class data_tableManager(models.Manager): def … -
How to save user from non class based view in django?
I am trying to create new users to the admin and to the app from NON Classe Based View in my django project, I have the model, the view and the template where I am getting the form as it goes in the next code I´m going to show.. models.py class Users(models.Model): # Fields username = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=12, blank=True, null=True) organization_id = models.ForeignKey('ip_cam.Organizations', editable=True, null=True, blank=True) slug = extension_fields.AutoSlugField(populate_from='created', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) # Relationship Fields user_id = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ('-created',) def __str__(self): return u'%s' % self.user_id def get_absolute_url(self): return reverse('ip_cam_users_detail', args=(self.slug,)) def get_update_url(self): return reverse('ip_cam_users_update', args=(self.slug,)) def __unicode__(self): # __str__ self.organization_id=self.request.POST.get('organization_id') return unicode(self.user_id, self.organization_id) # This overrides the standard save method for a user, creating a new user in the admin and getting it to the template at the same time def save(self, *args, **kwargs): self.password = make_password(self.password) self.user_id, created = User.objects.get_or_create(username=self.username, password=self.password, is_staff=True) self.user_id.groups.add(Group.objects.get(name='admin')) self.id = self.user_id.id super(Users, self).save(*args, **kwargs) views.py def UsersCreate(request): model = Users var = {} var = user_group_validation(request) userInc = Users.objects.get(id=request.user.id).organization_id.pk request.session['userInc'] = userInc if var['grupo'] == 'superuser': object_list = Users.objects.all() organization = Organizations.objects.all() roles_choice = DefaultLandingPage.objects.all() if var['grupo'] … -
Django RAW SQL, named parameters
I have a complex query, with some inner joins, a little where clause and HAVING clause too, this is for a report. In this case, I can't use Model.objects.raw, so instead, I'm using cursor.execute(sql). My question is with my parameters. I have 20 parameters and some of them are repeated (company_id in every inner join). Using a dict and %(key)s don't work here when using cursor.execute, it only works with Model.object.raw. How can I name parameter, to just pass it once? Or is there a method to sanitize my entire query, avoiding SQL injection? Pass all the 20 parameters and repeating them in order in a list is not readable. -
Lines in a django's template
In django, I have a line <th class="indigo"> <a href="{{ req_url }}?state__iexact=validation" data-turbolinks="false"> <b v-text="dashboard.requests.state.daily.validation">0</b> {% trans "Notice 7 days" %} </a> </th> which gave me the following image I would like move the number 0 bellow Notice 7 days and increase the size of the writting. Could anyone be able to tell me how could I proceed? -
showing micro µ symbol in a python django template
I have some data I am working with i.e displaying it using django on a template. So, the data (NOT from a db) looks like so: <td>{{obj.var1}}</td> and this displays: 1.54 \xb5 The \xb5 here is for the micro symbol. To display the micro symbol, I wrote a little template tag, which looks like so: .... def search_replace_filter(query): return query.replace("\\xb5",r'''&micro;''') ... and this stupidly now displays: 1.54 &micro; .. which is not what I want... Any help would be greatly appreciated :(( -
Django Error:Not a valid url
I am fairly new in matching regex in Url. Can Someone tell me regex for this? pid/ref/result/checksum where pid=1 ref=2000 result=succeed checksum=adssad41c2c0e04fb45adac6552faf7adasdsaddas