Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.6 Logging : Custom name logger propagating to root when set to False
Below is my settings.py import logging custom_logger = logging.getLogger('custom') LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'django.utils.log.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file_log': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/tmp/web_logs.log', 'maxBytes': 1024 * 1024 * 200, 'backupCount': 1, }, 'filtered_log': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/debug_info.log', }, }, 'loggers': { 'django.request': { 'handlers': ['null'], 'level': 'ERROR', 'propagate': False, }, '': { 'handlers': ['console', 'file_log'], 'level': 'DEBUG', 'propogate': True, }, 'custom': { 'handlers': ['filtered_log'], 'propogate': False, }, }, } But every custom_logger.debug('Message') is sent to both custom logger and '' logger. For every logging level the same happens i.e. it is sent to both the loggers despite Propogate flag is set to False. Any suggestions to rectify it. Please ignore the indentation errors and Django version is 1.6. -
Should I get ID the user ID using websockets or REST in Django?
I use in my project REST for registration and user authentication. When the user logs in he can send message to backend using websockets. I save his all messages to my database. At the moment in my database I have columns id and message. I would like to add also id of the user which send message to backend. My model looks in this way: class Message(models.Model): message = models.CharField(max_length=200) I want to achieve this: from django.contrib.auth.models import User class Message(models.Model): user = models.ForeignKey('auth.User') message = models.CharField(max_length=200) My question is how should I add the user ID to my database with his message. ID of this user should be sended using websockets or for instance header in REST? -
Nginx gateway timeout without much load on server
I am using NGINX and UWSGI to power the python/Django based API backend with load balancer attached to AWS auto scale groups, my servers works fine in routine, but sometimes start getting 504 or 502 from server once in a month or two constantly for a day or more. Load on my server is less than routine, memory usage is fine, but still get 502 or 504 Using ubuntu 14.0.4 Here is how my nginx configuration looks user www-data; worker_processes 2; pid /run/nginx.pid; events { worker_connections 2048; multi_accept on; use epoll; } worker_rlimit_nofile 40000; http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 50s; keepalive_requests 1024; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; client_body_timeout 12; client_header_timeout 12; send_timeout 10; limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 20; open_file_cache max=5000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## log_format json '{"method": "$request_method", "uri": "$request_uri", "status": $status, "request_time": $request_time, "upstream_response_time": $upstream_response_time, "body_bytes_sent": $body_bytes_sent, "http_user_agent": "$http_user_agent", "remote": "$remote_addr", "upstream": "$upstream_addr", "proxy": "$proxy_host"}'; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 9; #gzip_buffers 16 8k; #gzip_http_version 1.1; #gzip_types text/plain … -
I want to create a reusable function in Django
I am new to django and have been working on a project where i need to send regular mails to my clients from different modules in my django project. I wanted to know if there is any provision in django using which i can create a reusable component which can be used globally in my project. The purpose is to create a mail sending function using a third party api and to call it from anywhere in my application just by passing the required parameters. -
Django manually render form fields instead of form.as_p
I'm using Django 1.11 I have a CreateView with inlineformset to store associated model record. forms.py class BusinessForm(ModelForm): class Meta: model = Business exclude = () BusinessAddressFormSet = inlineformset_factory( Business, BusinessAddress, form=BusinessForm, extra=1, can_delete=False ) and in the business_form.html, I'm doing is <form method="post"> {% csrf_token %} // render business form {{ form.as_p }} // render business address fields {{ business_address.management_form }} <table class="table"> {{ business_address.management_form }} {% for form in business_address.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> This renders all field of address model as - line_1 - line_2 - city - state - postal The above fields are rendered in table row. Since, I have a separate html template to use with inline form icon for different fields. How can I manually render … -
django.urls.exceptions.NoReverseMatch: Reverse for 'equipmentCheck' not found. 'equipmentCheck' is not a valid view function or pattern name
When I am trying to pull the code from github n my server where python version is 3.4 and Django version is 1.6 it shows the error for NoReverseMatch: Reverse for 'equipmentCheck' not found. 'equipmentCheck' is not a valid view function or pattern name. But the same code is running perfectly in pythonanywhere where I am using Python 3.6 and Django 1.11.4 In urls.py url(r'^reservedequipment/check', views.equipmentCheck, name='equipmentCheck'), In views.py def equipmentCheck(request): pkk = request.GET.get('pkk') pk = request.GET.get('pk') start = request.GET.get('start') end = request.GET.get('end') d = DeviceUsage.objects.filter(equipment__pk=pk, start__lte=start, end__gte=start, status=1) if pkk: d.exclude(pk=pkk) result = {'ok': True} if d: result = {'ok': False} return JsonResponse(result) in template <script> $(document).ready(function() { $('#check-form').on('submit', function(evt){ console.log($('input[name="valid"]').val()); if($('input[name="valid"]').val()==1){ return true; } evt.stopPropagation(); evt.preventDefault(); var elem=this; $.ajax({ url: "{% url 'equipmentCheck' %}", data: { pkk: "{{ booking.pk }}", pk: $('input[name="equipment"]').val(), start: $('input[name="start"]').val(), end: $('input[name="end"]').val() }, success: function(e){ if(!e.ok){ if(confirm('Your reservation time is overlapping with an existing reservation. Do you want to continue your reservation?')){ $('input[name="valid"]').val(1); $(elem).submit(); } }else{ $('input[name="valid"]').val(1); $(elem).submit(); } } }); }); -
How can I redirect to user requested url after login - Django loginrequiredmixin
I am trying to limit the access for a view using Django LoginRequiredMixin. If the user is not logged in it will redirect to the login page. But the problem is that after login it is not redirecting to the user typed url instead it goes to the default page? For example user tries to login to the page site/site-create. If the user is not logged in it goes to the login page. After the login it goes to the default page of login.Here I want to redirect the user to site/site-create page. How can I do that? Thank You -
Invalid source path /_links/source/href - Django
I have a Dwolla api request I am trying to send and I am getting a path invalid path error that I cant figure out. SO the main error is coming from the request body even though I made sure it is similar to the api docs example with the replacement of my information from the database. Can anyone help me figure out what is going on and what is causing the error. Here is the example within the Dwolla api docs: request_body = { '_links': { 'source': { 'href': 'https://api-sandbox.dwolla.com/funding-sources/707177c3-bf15-4e7e-b37c-55c3898d9bf4' }, 'destination': { 'href': 'https://api-sandbox.dwolla.com/customers/07D59716-EF22-4FE6-98E8-F3190233DFB8' } }, 'amount': { 'currency': 'USD', 'value': '1.00' }, 'metadata': { 'paymentId': '12345678', 'note': 'payment for completed work Dec. 1' }, 'clearing': { 'destination': 'next-available' }, 'correlationId': '8a2cdc8d-629d-4a24-98ac-40b735229fe2' } transfer = app_token.post('transfers', request_body) Here is the output I am getting from my example of gather informaiton: { '_links':{ 'source':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..a295c' }, 'destination':{ 'href':'https://api-sandbox.dwolla.com/funding-sources/..ae0fc' } }, 'amount':{ 'currency':'USD', 'value':'15.00' }, 'metadata':{ 'paymentId':'507133793', 'note':'wild night' }, 'clearing':{ 'destination':'next-available' }, 'correlationId':'8a2cdc8d-629d-4a24-98ac-40b735229fe2' } here is the exact error that is occuring: ValidationError at /4/4/add_transaction/ {"code":"ValidationError","message":"Validation error(s) present. See embedded errors list for more details.","_embedded":{"errors":[{"code":"Invalid","message":"Invalid funding source.","path":"/_links/source/href","_links":{}}]}} -
URL expander API
Following is my code to expand my short URL(Note: %s is my short URL). Unfortunately, they didn't seem working as the API is no longer valid now. Please advise a workable API. .Thanks. def expand(url): response = requests.get('http://api.longurl.org/v2/expand?url=%s&format=json' % url) try: response_data = json.loads(response.content) longurl = response_data['long-url'] except: longurl = url return longurl -
Getting 504 with nginx as reverse proxy and uwsgi as app server when $request_time in nginx logs reaches 60s
$request_time in nginx logs is the time taken by the request from when it was first received in nginx and till the response was sent back by nginx to client. In my nginx config, the request is closed by nginx and marked 504 gateway timeout when $request_time reaches 60s I have tried using following location context directives: proxy_connect_timeout 300s; proxy_send_timeout 300s; proxy_read_timeout 300s; send_timeout 300s; uwsgi_read_timeout 300s; uwsgi_send_timeout 300s; But still facing the same issue. Is there some config that i am missing? Here is the location context of my nginx.conf location / { set $uwsgi_script "wsgi"; set $script_name "/"; set $socket "uwsgi.sock"; #client_max_body_size 1000m; keepalive_timeout 0; # host and port to uwsgi server uwsgi_pass unix:///tmp/$socket; uwsgi_param UWSGI_SCRIPT $uwsgi_script; uwsgi_param SCRIPT_NAME $script_name; proxy_connect_timeout 300s; proxy_send_timeout 300s; proxy_read_timeout 300s; send_timeout 300s; uwsgi_pass_header Authorization; include /etc/nginx/uwsgi_params; #fix redirect issue to proxy port uwsgi_param SERVER_PORT 80; #set correct scheme uwsgi_param UWSGI_SCHEME $http_x_forwarded_proto; uwsgi_intercept_errors off; uwsgi_read_timeout 300s; uwsgi_send_timeout 300s; } -
Check if a dictionary contain data true of false, then send a response back
this is a json response, im getting from my web client view, i'd like to check if this list dictionary contains data or not.How can i go on? Thanks [ { "id": 41, "commercialOffice": false, "haveStoreRooms": false, "workFromHome": false, "seperateOffice": false, "receptionArea": false, "standardInsurance": false, "teamAudit": false, "auditReport": false, "receptionist": false, "qualityAssuranceTeam": false, "subContractor": null, "employeeIdentityCard": false, "employeeUniform": false, "insuranceList": "", "company": null }, { "id": 45, "commercialOffice": false, "haveStoreRooms": false, "workFromHome": false, "seperateOffice": false, "receptionArea": false, "standardInsurance": false, "teamAudit": false, "auditReport": false, "receptionist": false, "qualityAssuranceTeam": false, "subContractor": null, "employeeIdentityCard": false, "employeeUniform": false, "insuranceList": "0", "company": 71 }, { "id": 46, "commercialOffice": true, "haveStoreRooms": true, "workFromHome": false, "seperateOffice": false, "receptionArea": false, "standardInsurance": true, "teamAudit": false, "auditReport": false, "receptionist": false, "qualityAssuranceTeam": false, "subContractor": null, "employeeIdentityCard": true, "employeeUniform": false, "insuranceList": "0", "company": 68 }, ] I was thinking about this def (self): dic = {'key1': ['value1', 'value2'], 'key2': 'value77' } values = dic.values() 'value77' in [x for v in values for x in v if type(v)==list] or 'value77' in values -
Django; Querying the Database
I have a Question Model, class Question(models.Model): .... Second I have a Answer Model related to Question Model, same as class Answer(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question, on_delete=models.CASCADE) I wants to filter out all the questions with no Answers. How can I do that in the view? Thank You! -
Not able to get enough tutorial on building a server for storing GIS data using monogdb, pymongo and django
I am setting up a server for a small group to store and retrieve GIS data. And searched about mongodb,pymongo and Django for frontend hence installed the necessary software. Please guide me a good tutorial on pymongo. Am I on the right track of setting up a server? -
Change django csrf token in ajax prefilter
Here are the thing I know - There is @ensure_csrf_cookie over my view method which is loading a template. In the template I need that csrf token, so I get it from the cookie and make a 3rd party API call. From the 3rd party API call I get back that same csrf token. There is ajax prefilter setup which is sending the csrf token from the browser cookie in all the ajax calls from that template. But I want to send the csrf token I got from my 3rd party API call. Let me know if this question seems correct. Or I am understanding this in the wrong way. -
How to mention the empty password rainbow table lookup trick to extract the SALT using Python
I need some help. I am setting the static salt value to has the password using Python. I am explaining my code below. settings.py: SALT = "2Y7xk5vrs5DeCcSdinRVKQ==" views.py: import hashlib from django.conf import settings def signsave(request): """This function helps to save signup data""" if request.method == 'POST': name = request.POST.get('uname') password = request.POST.get('pass') con_pass = request.POST.get('conpass') if password == con_pass: salt = settings.SALT hashed_password = hashlib.sha512(password + salt).hexdigest() passw = User( uname=name, password=hashed_password ) passw.save() message = "Registered successfully" return render(request, 'bookingservice/login.html', {'msg': message}) else: message = "The password did not match " return render(request, 'bookingservice/signup.html', {'msg': message}) Here I am defining the static value for salt but here also I need the empty password rainbow table lookup trick to extract the SALT. Please help me. -
Django InlineFormsets with programm logic or multiple use-Inlines?
In my use-case I have 3 models, a house, room and chair. When I save a house I want to add rooms to it, and for each room the number of chairs that would fit each individual room¸ Once I created the house with its rooms, I want to add chairs to each room, but not more then the number of chairs that would fit into those individual rooms. For convenience I'd like to use Inlines for adding rooms and setting the max number of chairs. I'd then like to use such an Inline to assign chairs to the given house-rooms. Any Ideas on how to achieve that? -
Django how to get values by user_ID
I'm trying to get all of a users reports and pass them to the page template. My question is how do I filter by user_id=1? views.py data = report.objects.values() return render(request,'list.html',data) models.py class user(models.Model): firstname = models.CharField(max_length=250) lastname = models.CharField(max_length=250) email = models.CharField(max_length=250) password = models.CharField(max_length=250) newsletter = models.BooleanField(default=0) accountlevel = models.BigIntegerField(default=1) reportsCreated = models.BigIntegerField(default=0) class report(models.Model): user = models.ForeignKey(user, on_delete=models.CASCADE) name = models.CharField(max_length=250) dateran = models.DateField() fromdate = models.DateField() todate = models.DateField() state = models.IntegerField() graphURL = models.CharField(max_length=1000) reporttype = models.CharField(max_length=250) -
Loading a Static File Within Injected HTML
I am trying to load a static file that is inside of injected html in my Django project: <div class="bottom-box" id="left"> <span id="title">Banks and cards</span> {{ card_info |safe}} </div> And here is the code that is being injected through the card_info variable: """ <p id="pay-card"> <img id="pay-box-img" src="{%% static 'img/payment-card.png' %%}" height="14"> <span id="card-number">%s x-%i %s</span> </p> """ The issue line is: src="{%% static 'img/payment-card.png' %%}". The issue is when I inspect the HTML page, I see this line: src="{% static 'img/payment-card.png' %}" It seems to not be rending and I haven't the slightest clue as to how to get a static file link, inside of a variable, to render. -
How can I skip to a template and render the request data to it using ajax?
This is the first page, in there I can use ajax to request url, and pass request data to it. My ajax code is below: $.ajax({ type:'post', url:'/app_api/server_payment/', contentType:'application/json', data:JSON.stringify({'params':buy_data}), dataType:'json', success:success_func }) function success_func(response){ console.log(response) } In the views.py: def server_payment(request): if request.method == 'POST': is_login = request.session['is_login'] if is_login: print ('server_payment_2 ', is_login) # it prints return render(request, 'app_admin/payment.html') else: return render(request, 'frontend/login.html') In the views.py I want to render the payment.html and skip to it. This is my payment.html. But the server.html page did not skip to the payment.html, and I don't know how to realize it. I tried use the self.location=/app_api/server_payment/ but I can not pass the data with post method. There are some detail information in the first snapshot. -
Django: What is the proper way to include multiple settings.py files (or include a dynamic SITE_ID) using the sites framework?
I'm getting this error on my Django site in production: You're using the Django "sites framework" without having set the SITE_ID setting. Create a site in your database and set the SITE_ID setting or pass a request to Site.objects.get_current() to fix this error. The question has been asked here but the accepted answer suggests using runserver in production. It has also been asked here but the accepted answer is inscrutable. I've tried adding the following to my settings.py file but it throws an error: from django.contrib.sites.models import Site SITE_ID = Site.objects.get_current() the error is: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. ...but I do have the SECRET_KEY setting set. What is the proper way to follow the Django documentation to server multiple sites on the same server? -
Displaying files uploaded to database, to template in django.
Help me plzz....I am trying to display a profile picture and music files uploaded by a user to template. But for some reason my code does not work. app/models.py def get_upload_path(instance, filename): return 'users/{0}/{1}'.format(instance.user.username,filename) class UserProfile(models.Model): user = models.OneToOneField(User) picture=models.ImageField(upload_to='profile_images, blank=True) def __unicode__(self): return self.user.username class MusicCollection(models.Model): user = models.ForeignKey(User, null=True) document = models.FileField(upload_to=get_upload_path) app/forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('picture',) class MusicForm(forms.ModelForm): class Meta: model = MusicCollection fields = ('document', ) app/views.py @login_required def userpage(request): lim =[] lip =[] c_user = request.user music = MusicCollection.objects.filter(Q(user = c_user)) for i in music: lim.append(i) pictures = UserProfile.objects.filter(Q(user = c_user)) for i in pictures: lip.append(i) return render_to_response(request, 'welcome.html',{'lim': lim, 'lip':lip}) templates/welcome.html {% if lip %} <ul> <li> <a href="{{ lip.picture.url }}">hi</a></li> <img src="{{ lip.picture.url }}" href="{{ lip.picture.name }}"width="600" height="400"> </ul> {% else %} <p>No documents.</p> {% endif %} <a class="navbar-brand" href="/">Index</a> {% if lim %} <ul> <li><a href="{{ lim.document.url }}"></a>{{ lim.document.name }}</li> </ul> {% else %} <p>No documents.</p> {% endif %} I tried passing the model objects without making it a list but in either case the welcome.html displays No Document. Thanks in … -
Reverse for 'data_bi_list' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
HELLO,I have googled this problem, but all didn't work.So please help me. url.py: url(r'^file_parse/$', file_parse), url(r'^data_bi/(?P<data_list_id>\d+)/$', data_to_list, name = 'data_to_list'), file_parse.html: {% for item in uploadfile_info %} <tbody> <tr> <td>{{ item.uploaded_at }}</td> <td>{{ item.document }}</td> <td>{{ item.description }}</td> <td> {% csrf_token %} <a href="{% url 'data_bi_list' item.id %}">{{ item.description }} </a> </tr> </tbody> {% endfor %} file_parse.py: def file_parse(request): uploadfile_info = upload_document.objects.all() context = {'uploadfile_info': uploadfile_info} return render(request, 'logfile/file_parse.html', context) data_bi.py: def data_to_list(request, data_list_id): data_list = ES_device.objects.get(device_name=str(data_list_id)) context = {'data_list': data_list} return render(request, 'logfile/data_bi.html', context) -
How can I use the js skip page method to pass params(request data)?
How can I use the self.location or some method to pass data(request) to the views.py? Because in my js, I use self.location=/api/buy_products to skip the page, and in the page, I want to render the data to the skiped template. How to do with that? My code is below: In js: self.location = '/api/buy_product/' In my views.py: def buy_product(request): if request.method == 'GET': return render(request, 'app/buy_products.html' , # there I want to pass the request's data) But how can I use the self.location to pass the data to the buy_product function? -
Elasticbeanstalk Django S3 Storage and Collectstatic Errors
I'm working with Django v1.11.2 setup using Django Storages to host files on S3. I've got the storages configured correctly as far as I can tell. I can successfully deploy and run 'collectstatic' without a problem. The files show up in S3 and the site works as expected. I'm also using the Django Import / Export module and have it set to store files using the MediaStorage option. After I run an import it successfully creates a 'media' folder in my S3 bucket alongside my 'static' bucket. Here's where the problem arises. If I now run an eb deploy and push updates of any kind I receive this error. [Instance: i-037825ca3bdf4a5c5] Command failed on instance. Return code: 1 Output: (TRUNCATED)...(path) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/files/storage.py", line 111, in path raise NotImplementedError("This backend doesn't support absolute paths.") NotImplementedError: This backend doesn't support absolute paths. container_command 03_collectstatic in .ebextensions/02_python.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Ok. Hmmm. That's odd. So now if I go into my S3 bucket. Delete ONLY the 'media' folder and do deploy the application again the error is resolved. Here are the values I have within my settings.py file. AWS_STORAGE_BUCKET_NAME = 'my-s3-bucket' AWS_S3_REGION_NAME = 'us-east-1' AWS_ACCESS_KEY_ID … -
FileNotFoundError: [Errno 2] No such file or directory: 'test_user1_user_id'
I got an error,FileNotFoundError: [Errno 2] No such file or directory: 'test_user1_user_id' . I wrote in tests.py #coding:utf-8 from datetime import datetime from django.test import TestCase from app.models import Companytransaction import xlrd # Create your tests here. class CompanytransactionModelTests(TestCase): def __init__(self, sheet_path): self.book = xlrd.open_workbook(sheet_path) self.sheet = self.book.sheet_by_index(1) def setUp(self): self.book = xlrd.open_workbook('./data/excel1.xlsx') self.sheet = self.book.sheet_by_index(1) num = 0 for row_index in range(2,4): row = self.sheet.row_values(row_index) user = Companytransaction(user_id=row[1], name=row[2], age=row[3]) user.save() if num == 0: self.user1 = Companytransaction.objects.create(user_id=row[1], name=row[2], age=row[3]) num += 1 elif num == 1: self.user2 = Companytransaction.objects.create(user_id=row[1], name=row[2], age=row[3]) num += 1 else: self.user3 = Companytransaction.objects.create(user_id=row[1], name=row[2], age=row[3]) def test_user1_company_id(self): self.assertEqual(self.user1.user_id, '100') def test_user1_corporation_id(self): self.assertEqual(self.user1.name, 'Tom') def test_user1_company_name(self): self.assertEqual(self.user1.age, '29') I run python manage.py test & ./manage.py test app(my application name).tests,but both of them same error happens.I surely made user_id column in models.py,so I really cannot understand why this error happens.How can I fix this?What should I write this?