Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django/SQL double entry table for template
I have the following models in my django app: from django.contrib.auth.models import User class Poll(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User) class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) text = models.CharField(max_length=200) class Vote(models.Model): poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) user = models.ForeignKey(User) For a given Poll, I need to display in the template a double-entry table like the following, listing all Users who have voted in this Poll and placing an 'x' for each Choice that the user has voted: [choice1] [choice2] [choice3] [user1] x [user2] x x [user3] x [user4] x x What would be the optimal way to implement this using the django ORM in order to minimize the database hits when populating the table? Which object should be passed to the template in the context variable, in order conduct the logic in the view instead of the template? -
Best approach to extensibility/modularity of your OOP Python web app
I'm considering undertaking a really ambitious project. The main part of its concept will be "open-sourceness" and easy extensibility, sort of "hot-plug" kind. As project will be complex and huge, I'll have to employ OOP to make it readable/manageable, thus easy for anybody to jump in and extend it on demand. As title says, it will be a web app, and I'm planning to use Django as a framework. But I'm a bit uncertain what will be the best, the only effective way to approach it. Here is my [possibly wrong] understanding of the situation. Let's suppose I have my basic, core functionality implemented. It's a bunch of classes, they are instantiated into objects, some functions of those objects are called, objects are being passed into other functions - things are humming and sun shines above :) Now, I need to implement sort of addon, or plugin, or whatever, which can be easily attached to existing code, preferably without changing anything at all in it, except for adding some includes - and will basically change how certain functions work and objects behave. Still doesn't seem like a too complex task, right? I know that functions can be re-loaded etc. But … -
How to avoid overwriting a SQL UPDATE statement when looping through list in Python?
I would like to iterate through my 2D list in python and make the elements similar. I want to update my database (mySQL) with IDs of index 0 to be like index 1. list_one = [ [1,3], [2,5], [3,1], [4,5], [5,2] ] loop 1: UPDATE 1 with 3 >> list_one[0] == 3 loop 2: UPDATE 2 with 5 >> list_one[1] == 5 loop 3: UPDATE 3 with 1 >> list_one[2] == 1 ## if you look closely, the first loop will be re-updated by the third loop because list_one[0] is currently == 3. ## So loop 1 will also output as 1 along with loop 3. list_one[0] is overwritten. >> list_one[0] == 1 How can I avoid this from happening? Is there a query in mySQL I can write to update everything at once? If there is, I don't know how many arrays I will have. I am using python, django and mysql. Please help, thank you! -
NameError: name 'order_vals' is not defined. - Python, Django
Alright I know this question title looks EXTREMELY familiar to many on this site but I swear I reviewed quite a few and almost all were issues with indentation and variable scope. That does not appear to be the case here so I'm hoping someone can help out. So I'm writing a function in my models.py to parse out a dataframe into a list of objects to send to my views.py function and I get the NameError referenced in the title, despite declaring the offending variable immediately before it is used. The code is shown below # Setting some default values for our order records. order_vals = { 'site': 'WH30-123', 'sale_type': 'CUST', 'sales_rep': 'JOHN DOE', 'customer_number': "123456789", 'cust_po_number': '{}-{}'.format(self.start_date.strftime(d_form),self.end_date.strftime(d_form)), 'fob': 'ORIGIN' } # Using a helper function to generate a list of orders. orders=helpers.order_parse(ords,order_vals) Okay, not only can I see nothing wrong with typing up a little dictionary and passing it to a function, when I step through this code using import pdb; pdb.set_trace() I can execute order_vals and it returns all the values exactly as I've written them out. I'm at a total loss here. If it helps, here is the function I am passing the dictionary to. def …