Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fail to send email via django
settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.exmail.qq.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'admin@gushijielong.cn' EMAIL_HOST_PASSWORD = 'p@ssword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER and I execute following commands in Pycharm's Console: In[2]: from django.core.mail import send_mail In[3]: send_mail('Subject here', 'Here is the message.','admin@gushijielong.cn',['sea3@qq.com'], fail_silently=False) and nothing happened. It just stuck and if I try to put another command the console only prompts "Previous command is still running.Please wait or press Ctrl C in console to interrupt." and nothing at all. It's not the smtp server problem, neither the authorization problem. Because I success send emails via Outlook with the same configuration. -
Django Apache html template css switch button not updating
I have a problem with an Apache production server not displaying a checkbox based css switch button checked state. It is being displayed correctly in the dev server. The strange thing about it is it only affects the first check button, if I put another button in front of it it works fine. If I put it into the same div the first button is hidden. This trick allows for correct displaying of the page, but it's an ugly hack and unreliable, since I don't know what's causing the issue. Any ideas why this is happening would be appreciated. Here is an screenshot of the displayed page: Screenshot of the displayed page Here is the html template: {% load static %} <head> <link rel="stylesheet" type="text/css" href="{% static 'VoltageShow/style.css' %}" /> <script src="{% static 'VoltageShow/jquery-3.1.0.min.js' %}" type="text/javascript" ></script> <script src="{% static 'VoltageShow/moment-with-locales.min.js' %}" type="text/javascript" ></script> <script src="{% static 'VoltageShow/Chart.min.js' %}" type="text/javascript" ></script> </head> <body> <h1>Voltage Page</h1> <!-- Rounded switch --> <div> <input type="checkbox"> <-- STACKOVERFLOW COMMENT: inserting this line results in correct switching of the css checkbox below --> <span style="float:left; position:relative; left:40px; height: 30px; line-height: 32px;">Record Voltage</span> <label class="switch" style="float:left; left:80px;"> <input type="checkbox" class="switch-input" checked/> <span class="switch-label" data-on="On" data-off="Off"></span> <span … -
Pulling data from a server and updating graphs dynamically on a website using Python
How would I go about creating graphs on a webpage that displays data from a server and automatically updates on its own using Python? I am not really familiar with web programming in Python. I did some googling and frameworks such as Django, Flask and Tornado popped up. Which one should I dive deep into and what reading sources should I make use of to solve this type of problem ? Also, what are some recommended/best suited languages to use to solve problems like these? -
Remove or expire cache from Django queryset
I have a Django project that have a large amount of transactions. Much queries. When using Django querysets they get cached, if I have understood it correctly. I need to remove this cache, but have not found any information regarding it. My users would like to get the latest objects as fast as possible (60 seconds would work at least). -
Django AUTH_USER_MODEL not registering custom User class
I've got this setup in my models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class AccountManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): . . . def create_superuser(self, email, password, **kwargs): . . . class Account(AbstractBaseUser): . . . In settings, I have done this: AUTH_USER_MODEL = 'authentication.Account' but I continue to get this error: AttributeError: Manager isn't available; 'auth.User' has been swapped for 'authentication.Account' Please I would like to know why and how to fix this -
creating admin restricted urls
so in my urls.py (outside django default admin section ) i want to restrict some urls only to admin so if i have this for logged users from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'^a1$',login_required( views.admin_area1 ), name='a1'), url(r'^a2$', login_required(views.admin_area2) , name='a2'), url(r'^a3', login_required(views.admin_area3) , name='a3'), ] is there enyway torestrict these links to logged admins not just any logged user ? there is but according to this i can use user_passes_test but i have to use it in view -
failed: django.db.utils.ProgrammingError: relation "users_userprofile" does not exist
Using django 10 and postgres 9.4. After the website full setup I noticed that I cannot create new objects from my applications, default django apps like users are OK. ran makemigrations and migrate afterwords, and when re trying it says nothing to migrate. To make it simple: When entering django shell and typing from users.models import * User.objects.all() Out[3]: [<User: root>] but : UserProfile.objects.all() Out[4]: <repr(<django.db.models.query.QuerySet at 0x39b4610>) failed: django.db.utils.ProgrammingError: relation "users_userprofile" does not exist LINE 1: ...."is_superuser", "users_userprofile"."wight" FROM "users_use... ^ UserProfile is my site users with onetoone to django.contrib.auth class UserProfile(models.Model): user = models.OneToOneField(User) Thanks -
DJANGO - Pass Table Name In Function
I'm trying to learn how I can pass a table variable name through a function. So for example lets say I have a model like below Bio(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) country = models.CharField(max_length=200) now I want to be able to pass the table name through the function. So normally I would do a people = Bio.objects.all() for x in people: print x.name I want to be able to pass the "name" variable through the function something like this... def print_name(variable): people = Bio.objects.all() for x in everyone: print x.variable print_name(name) I'm not sure exactly what I should be looking into. Thanks. -
How to use Django URLs in React JSX
I have an existing Django project. I want to use ReactJS within this as React makes handling states really really easy. The issue I am facing is how to re-use the URL templates that are already defined in Django? Example: Home/urls.py urlpatterns=[ url(r'plot/api/(?P<plot_id>[0-9]+)?$', views.LivePlot.as_view(), name='livePlot'), ] If i use just Django i can refer to the above url by {% url 'Home:livePlot' plot_id %} where plot_id is a parameter passed by the server. i am unable to leverage the same technique when using React. Any suggestions? I have access to the plot_id within my React code. React example: render: function() { return(<div className="plot"><a href=''></a></div>); } Ideally in the above example i would like to have a method to place {% url 'Home:livePlot' plot_id %} or something similar within the href attribute of anchor tag, so that the link points to example.com/plot/{plot_id}. Right now the workaround i was using involved building the url myself. So if i place this react component in example.com/sub/sub2 i would build the url as '../../plot' + plot_id. This approach fails miserably when i place the same react component in multiple pages like example.com/sub and example.com/sub/sub2 which is exactly the use-case i have. -
Django admin custom message management in admin panel
I have an admin panel for managing some Orders and I want to be able to see simultaneously manage messages displayed to a client informing him about conditions. Currently person managing Orders has to go to another view to change this message, which is not very convenient. Is it possible to have such a view: Message option 1 Message option 2 Order id | Order price | order content 1 | 10.00 | Apples 2 | 20.00 | Oranges I don't want any inlines, just to have this bullet list or something alike to make administrator work more efficient. -
Update a Foreign Key using PUT in Django Rest Framework
I am basically a new entrant into Rest framework and relatively new to Django. I am working on an Employee Rest API and I created Employee - Department tables using below Django models. I assigned a foreign key relationship between Employee's-department ID and Department-department ID. Now I want to update the Employee table using PUT operation. But when i update Employee.dept_id, it is not updated with the new value. I understand that since its a read only field, am not able to update it. How to change it to write field? so that i can update the department id in the employee table. models.py class Department(models.Model): dept_id = models.IntegerField(primary_key=True) dept_name = models.CharField(max_length=30) def __str__(self): return self.dept_id class Meta: ordering = ('dept_id',) class Employee(models.Model): first_name = models.CharField(max_length=30,blank=True) last_name = models.CharField(max_length=30,null=True,blank=True) emp_id = models.AutoField(primary_key=True) hire_date = models.DateField(default=datetime.date.today) email_id = models.EmailField(blank=True) dept = models.ForeignKey(Department, null=True,blank=True,related_name="dept") def __str__(self): return '%s %s' % (self.first_name, self.last_name) class Meta: ordering = ('emp_id',) My serializers for the above models are serializers.py class DepartmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Department fields = ('dept_id','dept_name') class EmployeeSerializer(serializers.ModelSerializer): dept_id = DepartmentSerializer().get_fields() class Meta: model = Employee fields = ('emp_id','last_name','first_name','hire_date','email_id', 'dept_id') views.py @api_view(['GET','POST']) def employee_list(request, format=None): """ List all employees, or create a new … -
Deploy with Apache2, mod_wgi and django 1.9 on ubuntu server 16.04
I am trying to set up a deployment enviroment for my django website on ubuntu server 16.04. When try to connect to the server I get an internal server error message. The content of my /var/apache2/site-available/000-default.conf is as follows: <VirtualHost *:80> ServerAdmin mymailaddress@pippo.com DocumentRoot /var/www/MySite Alias /static /var/www/MySite/static <Directory /var/www/MySite/static> Require all granted </Directory> Alias /media /var/www/MySite/media <Directory /var/www/MySite/media> Require all granted </Directory> WSGIScriptAlias / /var/www/MySite/MySite/wsgy.py <Directory /var/www/MySite/MySite> <Files wsgy.py> Require all granted </Files> </Directory> WSGIDaemonProcess MySite python-path=/var/www/MySite:/usr/lib/python3.5/dist-packages WSGIProcessGroup MySite ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log </VirtualHost> the django website is in /var/www/MySite and the folder has the following permissions: drwxr-xr-x 10 root www-data 4096 Aug 29 17:39 MySite Inner permissions are as follows: total 44 drwxr-xr-x 10 root www-data 4096 Aug 29 17:39 . drwxr-xr-x 4 root root 4096 Aug 29 17:44 .. drwxr-xr-x 3 root www-data 4096 Aug 30 04:44 MySite -rw-r--r-- 1 root www-data 0 Aug 29 17:39 __init__.py -rwxr-xr-x 1 root www-data 251 Aug 29 17:39 manage.py drwxr-xr-x 3 root www-data 4096 Aug 29 17:39 media drwxr-xr-x 4 root www-data 4096 Aug 29 18:28 navigation drwxr-xr-x 5 root www-data 4096 Aug 29 18:28 projects drwxr-xr-x 4 root www-data 4096 Aug 29 18:28 public_interfaces drwxr-xr-x 6 root www-data 4096 … -
passing a dictionary to all templates using context_processors
so i want to show my notification to all my templates so in my settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'helper.views.notification' ], }, }, ] helper/views.py from django.template import RequestContext def notifications(request): if( request.user.is_authenticated ) : notifications = { 'account': {'count' : Accounts.objects.filter(admin_seen=0).count() , 'title' : '' , 'link' : ''}, 'transaction':{'count' :Transactions.objects.filter(admin_seen=0).count() , 'title' : '' , 'link' : ''}, 'gateway':{'count' :Gateways.objects.filter(confirm=0).count() , 'title' : '' , 'link' : ''}, 'ticket':{'count' :Tickets.objects.filter(newdialog_user=0).count() , 'title' : '' , 'link' : ''} , } else : notifications = {'default':''} request_context = RequestContext(request) request_context.push({'notifications' : notifications}) but i get nothing n my template what im doing wrong ? -
How to open remote MySQL connection at a LAMP(Python) stack
I am developing a django application where my MySQL database is present. My django application and database setup is on one machine. Now I have 2 other machines running a script which need to remotely connect to my MySQL database present in my main machine. So in my main machine. I have done this: sudo nano /etc/mysql/my.cnf Then changed bind-address = 127.0.0.1 to bind-address = [my public ip address] After that, I opened remote access to my database port through my firewall by running: sudo ufw allow 3306/tcp sudo service ufw restart After that, I ran my mysql and ran the following command: CREATE USER newuser@[main machine ip address] IDENTIFIED BY 'my password'; GRANT ALL PRIVILEGES ON * . * TO newuser@[main machine ip address]; FLUSH PRIVILEGES; Now when I try to connect to my database remotely from a desktop application using: username: newuser@[my public ip address] password: my_password port: 3306 database: my database name host: [my public ip address] It doesn't connect and gives our the error 'access denied'. Is there anything else that I need to do to make it working? Any idea? -
NoReverseMatch at URL, error during template rendering, etc
I am trying to incorporate an export button into my Django admin site. Able to get the button to show in admin, but every time I click the button it breaks and I get the following error: NoReverseMatch at /admin/emarshalapp/attorney/export/ Reverse for 'app_list' with arguments '()' and keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?Pfiler|emarshalapp|auth)/$'] I am trying to follow this tutorial to do the export logic, but I obviously must be doing something wrong, just not sure what. I have tried all the solutions recommended for NoReverseMatch on SO and elsewhere but no fix in sight. I am stumped, please help! The part of my change-list.html template that adds the button: {% block object-tools-items %} {{ block.super }} <li> <a href="export/" class="grp-state-focus addlink">Export</a> </li> {% endblock %} admin.py: def my_view(self, request): # custom view which should return an HttpResponse if request.method == 'POST': if 'export' in request.POST: response = HttpResponse( content_type='application/vnd.ms-excel') response['Content-Disposition'] = \ 'attachment; filename=Report.xlsx' xlsx_data = WriteToExcel(attorney_range, attorney) response.write(xlsx_data) return response else: return render(request, "change_list.html", context_instance=RequestContext(request)) def get_urls(self): urls = super(AttorneyAdmin, self).get_urls() my_urls = patterns('', url(r'^export/$', self.my_view, name='export/')) return my_urls + urls views.py: def attorney_history(request): attorney_range = Attorney.objects.all().filter(active=True) attorney = None if request.method == 'POST': … -
Join list from specific index
I have a list like below: ingredients = ['apple','cream','salt','sugar','cider'] I want to join this list to get a string but I want to join from 2nd index till the last one. to get this : "salt sugar cider" Length of list may vary. Is it possible to do this with join function or I have to do it by looping over elements? -
django nginx, turn off cache for html?
When I run collectstatic, hash value is attached to js/css file name. I expect users to download new version of js/css files. But my nginx is serving the old js/css files sometimes. How do I prevent that happen? -
edit django's generated javascript files
i'm not actually sure that want i want to do is doable, so i'm asking to people with more experience in Python/Django than me: what i have is a local instance of a django web app, i don't have the django files but only the css/js generated from that (specifically, is an Reviewboard instance). I'd like to change some frontend behavior, like not giving the possibility to the users to put themself as reviewer. What i want to do is simply not to show the option in the frontend (i don't care about backend). I tried to edit some js files (only adding console.log) but seems that the code that i'm editing is never running, so i guess that django use some built method to link the files in the app. Anyone can give me a clue if what i want to do is possible (and how)? Cheers -
How to access directory file outside django project?
I have my Django project running on RHEL 7 OS. The project is in path /root/project. And project is hosted on httpd server. Now iam trying to access a file out side the directory like /root/data/info/test.txt How should I access this path in views.py so that I can read and write file which is outside the project directory ? I tried to add the path in sys.path but it didn't work. Read and write permission are also give to the file. -
How can I break my html table up into chunks django python
So for example I have a table with 3 rows and 100 columns. What I would like to do is split it up by tens so the first table has 3 rows then 10 columns and so on until I have 10 tables all with equal 3 rows and 10 columns. The catch is I dont want repeats so in table one it should be 1-10 then table 2 it should be 11-20 and so on and so on... Any help would be greatly appreciated. I would like to do this using a python way and not css. Here is my view. @login_required def shipping_pdf(request, id): sheet_data = Sheet.objects.get(pk=id) work_order = sheet_data.work_order purchase_order = sheet_data.purchase_order drawing = sheet_data.drawing_number draw_rev = sheet_data.drawing_revision part = sheet_data.part_number part_rev = sheet_data.part_revision customer_data = Customer.objects.get(id=sheet_data.customer_id) customer_name = customer_data.customer_name title_head = 'Shipping-%s' % sheet_data.work_order complete_data = Sheet.objects.raw("""select s.id, d.id d_id, s.work_order, d.target, i.reading, d.description, i.serial_number from app_sheet s left join app_dimension d on s.id = d.sheet_id left join app_inspection_vals i on d.id = i.dimension_id where s.id = %s""" % id) for c_d in complete_data: dim_description = Dimension.objects.filter(sheet_id=c_d.id).values_list('description', flat=True).distinct() dim_id = Dimension.objects.filter(sheet_id=c_d.id)[:1] for d_i in dim_id: dim_data = Inspection_vals.objects.filter(dimension_id=d_i.id) reading_data = Inspection_vals.objects.filter(dimension_id=d_i.id) key_list = [] vals_list = … -
Django redirect to url with post data
I am in my views.py and I need to go to a url with post request along with post data. I tried HttpResponseRedirect but it does not take post data as param. class WebPaymentView(FormView): template_name = "payment/payment.html" form_class = NameForm def form_valid(self, form): # code return HttpResponseRedirect(url, data=data, content_type="application/x-www-form-urlencoded") Last line gives error: TypeError: __init __() got an unexpected keyword argument 'data' I want to post to this url as well as redirect to it. Any idea how? -
Image models with django-ckeditor and django-ckeditor-uploader
In a django project a client has requested a WYSIWYG editor and I went for django-ckeditor along with the uploader plugin. Everything works fine, no problem with that. In the previous implementation however, images were uploaded as Image model instances and were related with the text in the database (many-to-many relationships). In order to provide a more unified experience and a smoother transition to the new system, I am looking for ways to combine the previous and current implementations. In specific, the ideal scenario would be that the images uploaded via the CKEditor would be Image model instances and the image browser would make full use of the available Image models and their files. Is there an easier way to combine Image models and django-ckeditor or is a totally custom solution the only option? -
Dockerized Nginx and Django, how to serve static files
Im using Docker to containerize my Django environment, which looks like this (simplified a bit): A Nginx (official image) docker container An Ubuntu docker container with uwsgi and Django The Nginx container are serving the uwsgi just fine, but I have not found a way to serve static files. upstream proceed { server proceed:8000; } server { listen 80; server_name mydomain.com; location /static { alias /srv/www/proceed/static/; # What to do here? } location / { uwsgi_pass proceed; include uwsgi_params; } } Question: Whats the best way to serve static files from another container? A solution not involving volumes are preferable. -
Configured SSL on Ubuntu server running apache but "https://(domain-name)/path/to/function is not being processed in Django
Recently I installed SSL on my Apache Server, And changed SSLCertificateFile and SSLCertificateKeyFile and SSLCertificateChainFile file path in the /etc/apache2/sites-available/default-ssl.config <VirtualHost 192.168.0.1:443> DocumentRoot /var/www/html2 ServerName www.yourdomain.com SSLEngine on SSLCertificateFile /path/to/your_domain_name.crt SSLCertificateKeyFile /path/to/your_private.key SSLCertificateChainFile /path/to/DigiCertCA.crt </VirtualHost> Everything is working fine, it's loading https connection But the URL which I want to access at that moment it gives error! For example - my domain name is https://example.com and the url which I am trying to access is https://example.com/example_page When I just enter https://example.com It gives Apache Default page giving a success message and this url https://example.com/path/to/example_page gives error :The Requested URL was not found on this server. And I have written code in django which is used to access webpages So Is there a problem in django code or some settings in Apache server ?? Am I missing some steps? Any help would be appreciated Thanks -
How can I implement editable choice field in Django?
I want to make category, where I can add new category or edit existing category in admin page. I just thinking about implementing this with Django choice field but have some problem finding exact solution. Is there any good way to do this? or any other ideas?