Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve '[Errno 111] Connection Refused' in Django app on Heroku?
I have just added a new app to my Django application, and everything was working fine locally. When I push it Heroku however, I get the following error when trying to access views from the new app, or admin pages related to it. The rest of the site is working fine. 2017-02-15T10:14:13.305769+00:00 app[web.1]: self.connection = connection_class(self.host, self.port, **connection_params) 2017-02-15T10:14:13.305769+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/smtplib.py", line 256, in __init__ 2017-02-15T10:14:13.305770+00:00 app[web.1]: (code, msg) = self.connect(host, port) 2017-02-15T10:14:13.305770+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/smtplib.py", line 316, in connect 2017-02-15T10:14:13.305771+00:00 app[web.1]: self.sock = self._get_socket(host, port, self.timeout) 2017-02-15T10:14:13.305771+00:00 app[web.1]: return socket.create_connection((host, port), timeout) 2017-02-15T10:14:13.305771+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/smtplib.py", line 291, in _get_socket 2017-02-15T10:14:13.305772+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/socket.py", line 575, in create_connection 2017-02-15T10:14:13.305772+00:00 app[web.1]: raise err 2017-02-15T10:14:13.305773+00:00 app[web.1]: error: [Errno 111] Connection refused I couldn't find much documentation for this particular error, so any help would be much appreciated. What's going wrong? Let me know if there's any more information I can provide that would help. -
Django - get model object attributes from ModelForm
I have a ModelFormSet: TransactionFormSet = modelformset_factory(Transaction, exclude=("",)) With this model: class Transaction(models.Model): account = models.ForeignKey(Account) date = models.DateField() payee = models.CharField(max_length = 100) categories = models.ManyToManyField(Category) comment = models.CharField(max_length = 1000) outflow = models.DecimalField(max_digits=10, decimal_places=3) inflow = models.DecimalField(max_digits=10, decimal_places=3) cleared = models.BooleanField() And this is the template: {% for transaction in transactions %} <ul> {% for field in transaction %} {% ifnotequal field.label 'Id' %} {% ifnotequal field.value None %} {% ifequal field.label 'Categories' %} // what do i do here? {% endifequal %} <li>{{ field.label}}: {{ field.value }}</li> {% endifnotequal %} {% endifnotequal %} {% endfor %} </ul> {% endfor %} The view: def transactions_on_account_view(request, account_id): if request.method == "GET": transactions = TransactionFormSet(queryset=Transaction.objects.for_account(account_id)) context = {"transactions":transactions} return render(request, "transactions/transactions_for_account.html", context) I want to list all the Transaction information on a page. How can I list the "account" property of Transaction and the "categories"? Currently the template shows only their id, I want to get a nice representation for the user (preferrably from their str() method). The only way I can see that would work is to iterate over the FormSet, get the Ids of the Account and Category objects, get the objects by their Id and store the … -
How to run a Django application with --noreload using AWS Elastic Beanstalk
Sometimes I noticed that a Django view is performed by two different processes. These situations cause problems: for example, during a file upload, the same file will stored two times. I think that this problem is due to the autoreload option. Is it correct? How can I fix this? -
Django accessing context data inside get_success_url
In my get_context_data method I create context variable only if certain conditions are met. I want my form to be able to redirect different urls regarding that context variable is created or not. How to access context['something'] in get_success_url method? Or is it possible? -
In this file, create a function check_credit() that takes two parameters user (job, size)
Create a new python file, billing.py In this file, create a function check_credit() that takes two parameters user (job, size) In this function, check that the user has sufficient data available. e.g sum(data) > size This is my models: class UserBillingHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=False, default="Free 100Mb on sign-up and Buy $40 and get 100Mb" ) cash_amount = models.DecimalField(max_digits=9, decimal_places=2) data = models.IntegerField(null=False, blank=False) date = models.DateTimeField(default=timezone.now, blank=False, null=False) is_confirmed = models.BooleanField(default=False) job = models.ForeignKey("Job", on_delete=models.SET_NULL, null=True) @property def user_can_view(self, user): return (self.user == user) def user_can_edit(self, user): return (self.user == user) def user_can_delete(self, user): return (self.user == user) def get_absolute_url(self): return "/userbillinghistorys/%s/" % self.id def cash_amount(self): return "$%s" % 0 def data(self): return 100 * 1024 * 1024 Can you please need to query for this.thanks. -
serving django apps through a master index.html
I have a webserver running with various different websites. My issue is when trying to navigate to the django project it comes up with the directory index of the folder. How do I link a django project using a generic html indedx file. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <title>Customer Portal</title> <head> <div class="page-header"> <h1>Customer Portal</h1> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"/> <link type="text/css" rel="stylesheet" href="indexstyle.css"> </div> </head> <body> <div class="content container" style="min-height: 95;"> <div class="Intro"> <h2> Welcome to the Customer Portal</h2> </div> <br/> <br/> <div class="row"> <div class="col-sm-6"> <div class="buttonHolder"> <form action="./support/"> <input type="submit" value="Ticket System"/> </form> </div> </div> <div class="col-sm-6"> <div class="buttonHolder"> <form action="./portal/"> <input type="submit" value="Database System"/> </form> </div> </div> </div> </div> </body> The second button should link to the django project portal, is there a certain file I reference to invoke a django app? -
Programmatic update the django record with file
I have Django REST and receive JSON payload. Everything works perfectly fine. Until user add more requirement it is photo. models.py class Invoice(AbstractModelController): """ number refers to InvoiceNumber pk quotation refers to QuotationNumber pk parent refers to invoice itself case scheduler generated case content_data = content of text document revision = revision number status = status of invoice """ number = models.ForeignKey(InvoiceNumber) quotation = models.ForeignKey(QuotationNumber, null=True, blank=True) payterm = models.OneToOneField(Payment, null=True, blank=True, on_delete=SET_NULL) parent = models.ForeignKey('self', null=True, blank=True, related_name='hidden_group', on_delete=SET_NULL) content_data = JSONField() temporal_data = JSONField(null=True) invoicing_date = models.DateTimeField(null=True, blank=True) due_date = models.DateTimeField(null=True, blank=True) revision = models.SmallIntegerField(verbose_name='Revision number of quotaion') status = models.SmallIntegerField(choices=Status.STATUS_CHOICES, default=Status.DRAFT) job_id = models.CharField(max_length=255, null=True, blank=True) photo = models.ImageField(upload_to='invoices/', null=True, blank=True) views.py: class InvoiceHTMLFormView(APIView): model = Invoice def post(self, request, pk, format=None): invoice = Invoice.objects.get(id=pk) import pdb; pdb.set_trace() image = request.data['FILES'] urls.py urlpatterns = [ url(r'form/(?P<pk>[0-9]+)', InvoiceHTMLFormView.as_view(), name="form"), ] I know how to use FORM and let the html form submit the photo. But I have to use JSON with POST since I have to follow scheduler logic and more business logic during the POST process. Therefore I have to POST json first and then PUT to upload a photo Question: How can I update the Django … -
how to access seperate data which is getting from requests in django?
I am calling api and getting response back but dont know how to access it according to each key. import requeste def test(request): if request.method == 'POST': data={ 'operator_id':request.POST.get('operator_id'),'mobile_number' :request.POST.get('mobile_number'),'amount':request.POST.get('amount') } r = requests.post(''https://www.somedomain.com/some/url/recharge'', data) print(r.text) if r.status_code == 200: return HttpResponse('it worked') else: return render(request, 'account/apitest.html') -
Django templatetags: objects inside filter
Let say, I want to create a simply templatetags for dynamic counter, and how can I inject an example the {{ request.user }} inside value of dict author : {{ blog.model.Post|counter:"{'author':'...?'}" }}? In my bad idea, {{ blog.model.Post|counter:"{'author':'request.user'}" }}, but of course it should return string of 'request.user' but not actual object. import ast from django import template from django.utils.module_loading import import_string register = template.Library() @register.filter def counter(model_name, filter=None): """ by all objects: {{ counter|yourapp.model.ClassName }} by filter objects: {{ yourapp.model.ClassName|counter:"{'field_name':'value'}" }} > example: {{ blog.model.Post|counter:"{'author':'...?'}" }} """ model = import_string(model_name) if filter is not None: filter_dict = ast.literal_eval(filter) return model.objects.filter(**filter_dict).count() return model.objects.count() -
django update form has no attribute save
I am trying to create a form which will allow users to update their name, I am using a forms.form instead of ModelForm because it gives you more control over the styling of the form because you can use widgets. when I go to save the form it says that updateNameForm has no attribute save view def UpdateName(request,user_id): if request.method == "POST": form = UpdateNameForm(request.POST,initial=initial) if form.is_valid(): name = form.cleaned_data['name'] form.save() else: form = UpdateNameForm(initial=initial) forms.py class UpdateNameForm(forms.Form): name = forms.CharField( required=True, label="*Status", widget=forms.widgets.Select(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}) ) -
Django get all base class objects that their derived class has a mixin
I have models that look something like this: class SomeModel(model.Model): pass class Base(models.Model): pass class Mixin1(models.Model): some_model = models.ForeignKey('SomeModel', on_delete=models.CASCADE) class Meta: abstract = True class Derive1(Base, Mixin1): pass class Derive2(Base, Mixin1): pass class Derive3(Base): pass Now I want to be able to get all objects that derive from Base and Mixin1, without explicitly listing all classes that use Mixin1. Something like: Base.objects.filter(some_model=X) Why this doesn't work I understand, but how to actually make it work I do not know. -
Django + CloudFront caching without HTTP_REFERER
We use django 1.8. on backend with default authorization that runs on elasticbeanstalk and AWS CloudFront to cache app pages on CDN level. The problem is that we want to whitelist as few http headers as possible to minimize keys amount and maximize hit rate. One of the headers that varies a lot and we would prefer to exclude is HTTP_REFERER. On business level we are fine with resolving referer through js by using document.referer and that sending it to server with ajax calls. The problem: csrf login, registration and other default django authentification apps require HTTP_REFERER when used on website on https protocol. One of the solutions I found is to move all auth pages to separate behaviours and proxy all headers there. Are there any other ways to make such set up work? -
Nginx how to get an SSL certificate for a Django app
I have a Digitalocean Droplet running Ubuntu 16.04. it's all configured and I can access my site. However I have been struggling to setup the SSL certificate (i am new to webserver administration). I have the CA signed certificate.crt and private.key in a folder called /var/certs/. Djang app settings.py has the following enabled: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True This is my /etc/nginx/sites-available/example: server { listen 80; server_name example.co.uk www.example.co.uk; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/project_folder; } location / { include proxy_params; proxy_pass http://unix:/home/user/project_folder/project.sock; } } I have done a lot of research on the Digitalocean site, here and google for how to configure Nginx to use a SSL certificate with a Django but its proving to be quite complicated. If anyone could point me in the right direction that would be awesome. -
How to inherit django models just for overriding functions?
I am working on a project where I need to define some models which have some functions with business logic in them, for example how to process the data when fetching from db. I want to inherit multiple models from the same parent model in where in each model I override some particular functions. I don't want that a new table is made for each new model, since I am only overriding functionality and not adding any fields. How to achieve this? Proxy models don't help since I can't retrieve the appropriate class from the database object. Example:- class ParentModel(models.Model): f1=fields.IntegerField() def processing_func1(self): <default func1 functionality> def processing_func2(self): <default func2 functionality> class ChildModel1(models.Model): def processing_func1(self): <overridden func1 functionality> class ChildModel2(models.Model): def processing_func2(self): <overridden func2 functionality> -
Django: Error when creating objects using from
I'v been trying to use form to insert comment. When user type comment it gets article number, username, and comment body and redirect to the previous paHowever It keeps display error message, and I couldn't find exactly which part I missed. This is model.py class Comment(models.Model): article_no = models.IntegerField(default=1) comment_no = models.AutoField(primary_key=True) comment_writer = models.CharField(max_length=50) comment_body = models.CharField(max_length=300) comment_date = models.DateTimeField(editable=False, default=datetime.now()) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['article_no', 'comment_body', 'comment_writer'] view.py @login_required def comment(request, article_no): user = request.user request.session['username'] = user.username if 'username' is None: return render(request, 'blog/home.html') else: if request.POST.has_key('comment_body') == False: return HttpResponse('comment is none') else: if len(request.POST['comment_body']) == 0: return HttpResponse('comment is none') else: comment_body = request.POST['comment_body'] print(comment_body) if request.POST.has_key('comment_writer') == False: return HttpResponse('writer is none') else: if len(request.POST['comment_writer']) == 0: return HttpResponse('comment is none') else: comment_writer = request.POST['comment_writer'] print(comment_writer) try: instance = CommentForm(Comment_body=comment_body, Comment_writer=comment_writer, Article_no=article_no) instance.save() instance.Comment += 1 instance.save() #return HttpResponse('comment added') item = get_object_or_404(Article, pk=article_no) return render(request, 'blog/detail.html', {'item': item}) except: print("A") return HttpResponse('error') print("B") return HttpResponse('error') urls.py url(r'^comment/(?P<article_no>[0-9]+)/$', views.comment, name='comment'), -
Django blog with picture
I have this in my database paragraph1 paragraph2 paragraph2 I would like to place a picture in between paragraphs. I tried this <img src="where/photo/is"> in the database and I use the | safe filter, but that still prints the same as above. Do you have any idea how to perform that acction? -
Django object locking
I'm using Django 1.8 and I have a model class ModelA(models.Model): some_field = models.PositiveIntegerField() Now, in my view I want to add a new ModelA object, but only if there are fewer than x entries for that value already. def my_view(request): # Using the value of 4 here just as an example c = ModelA.objects.filter(some_field=4).count() # Check if fewer than (x=20) objects with this field already if c < 20: # Fewer, so create one new_model = ModelA(4) new_model.save() else: # Return a message saying "too many" From my understanding, there could be more than one thread running this method and so thread 1 may perform the count and there are fewer than 20 and then the other thread saves a new object, then thread 1 would save its object and there be 20 or more. Is there some way to have the view be def my_view(request): get_a_lock_on_model(ModelA) c = ModelA.objects.... # Rest of the code the same release_lock_on_model(ModelA) Or is there some other way I should be thinking about doing this? There are only ever inserts, never updates or deletes. Thanks! -
how to specify model permission to staff user (non-superuser) in django admin
I have to manage to type of admin one superadmin and another sub admin. superadmin can do everything and superuser will allow permission to sub-admin. For this i have created one virtual table for staff. but when user login as staff no model showing, how i can allow permission to specific model for staff user ? -
i am trying to get base64 string of an image
trying to get base64 string of an image, which is uploaded locally by the user. my html code is- < div class="col-md-4"> <label class="control-label"></label> <input type="file" name="galleryImage" class="filestyle" data-buttonText="Select a Image"> <input class="btn btn-sm btn-info btn-block" name="getImageUrl" type="submit" Style="width: 100px;"> </div> and in my views galleryImageURL = request.POST.get('galleryImage') print(galleryImageURL) galleryImage = requests.get(galleryImageURL).content print(galleryImage) base64EncodedImageString = imageBase64Encode(galleryImage) print(base64EncodedImageString) def imageBase64Encode(galleryImage): with open(galleryImage, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) return encoded_string i am getting error Invalid URL '763814bc03a9838a7bae23ad4867ec01.jpg': No schema supplied. Perhaps you meant http://763814bc03a9838a7bae23ad4867ec01.jpg? -
Django + Nginx + uwsgi error 504 timeout
I am trying to setup computing application on my CentOS server with Django 1.10, uwsgi and Nginx. However I have been facing error 504 timeout all the time due to long running process at the server backend. I have tried increasing uwsgi_read_timeout and uwsgi_send_timeout to more than 60 seconds but the request are always timeout and give me error at one minute mark. Here are my configuration: Nginx Configuration server { uwsgi_read_timeout 120s; uwsgi_send_timeout 120s; listen 8580; server_name 10.100.112.196; charset utf-8; client_max_body_size 0; # adjust according to your needs # Django media & static files location /media { alias /usr/share/nginx/html/django/crm-design-v2/media; } location /static { alias /usr/share/nginx/html/django/crm-design-v2/static_root; } # All the other stuff is handled directly by Django location / { uwsgi_pass 127.0.0.1:8001; include /usr/share/nginx/html/django/crm-design-v2/uwsgi_params; } } uwsgi ini [uwsgi] chdir=/usr/share/nginx/html/django/crm-design-v2 module=design_portal.wsgi:application master=True pidfile=/tmp/project-master.pid vacuum=True max-requests=5000 daemonize=/usr/share/nginx/html/django/design_portal.log My uwsgi server is started with the following command: uwsgi --socket :8001 --module design_portal.wsgi --ini uwsgi.ini I have tried various solution on the forum but I have no idea why the timeout stay same at 60 seconds mark. The uwsgi log file showed everything is running properly, so I believe this has something to do with Nginx. -
Firebase Authentication and Django/Djangae
I am evaluating if Firebase authentication to see if it works well with Django/Djangae. Here comes some context require email/password authentication, able to additional field like job title, and basic things like reset password email. use Djanage framework (Django that uses datastore as data storage), app engine. really good to make use built-in authentication tool provided by Django, like session, require-loggin, etc. Drop-in authentication seems to be a candidate. Does it work with Django authentication, like permission, group, etc. Thanks for advance. -
'Database is locked' error while using sqlite3 during atomic transactions
I had previously observed that sqlite db writes are significantly faster when I wrap around an atomic transaction (django) - 0.3 secs without and 0.004 secs with transaction. Hence, I applied transactions throughout my project. Strangely after doing that I started encountering 'database is locked' error which led me to debug it to find out that when an update is running over a transaction (lets call it update A) and when I try to concurrently run another update (B) over a transaction then it fails instantly without waiting for the timeout (5 secs default). But when I tried running update B without transaction, it waited for A to finish and then completed the update. Could anyone provide me with an possible explanation for this which doesn't include removing transactions. -
Page not found error. Is Request URL wrong?
I got an error,Page not found. In profile.html,I wrote <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>UPLOAD</title> </head> <body> <form action="registration/accounts/fashion_result.html"> <input type="submit" value="ResultShow"> </form> <div class="container"> <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="files[]" multiple> <input type="hidden" value="{{ p_id }}" name="p_id"> <input type="submit" value="Upload"> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </body> </html> In this part <form action="registration/accounts/fashion_result.html"> <input type="submit" value="ResultShow"> </form> I wanna do screen transition(If I put this button,I wanna see fashion_result.html in browser. But now,I got the error. How can I fix this? -
Deploying Django to PythonAnywhere and cannot use SECRET_KEY from environment vars despite it being set
Currently, my error logs are spitting out nothing but this error: 2017-02-15 05:28:55,861 :Error running WSGI application 2017-02-15 05:28:55,862 :KeyError: 'SECRET_KEY' 2017-02-15 05:28:55,862 : File "/var/www/www_optranslations_net_wsgi.py", line 24, in 2017-02-15 05:28:55,862 : application = get_wsgi_application() 2017-02-15 05:28:55,862 : 2017-02-15 05:28:55,862 : File "/home/optranslations/.virtualenvs/optl/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2017-02-15 05:28:55,862 : django.setup(set_prefix=False) 2017-02-15 05:28:55,862 : 2017-02-15 05:28:55,862 : File "/home/optranslations/.virtualenvs/optl/lib/python3.5/site-packages/django/init.py", line 22, in setup 2017-02-15 05:28:55,862 : configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2017-02-15 05:28:55,862 : 2017-02-15 05:28:55,862 : File "/home/optranslations/.virtualenvs/optl/lib/python3.5/site-packages/django/conf/init.py", line 53, in getattr 2017-02-15 05:28:55,862 : self._setup(name) 2017-02-15 05:28:55,862 : 2017-02-15 05:28:55,862 : File "/home/optranslations/.virtualenvs/optl/lib/python3.5/site-packages/django/conf/init.py", line 41, in _setup 2017-02-15 05:28:55,863 : self._wrapped = Settings(settings_module) 2017-02-15 05:28:55,863 : 2017-02-15 05:28:55,863 : File "/home/optranslations/.virtualenvs/optl/lib/python3.5/site-packages/django/conf/init.py", line 97, in init 2017-02-15 05:28:55,863 : mod = importlib.import_module(self.SETTINGS_MODULE) 2017-02-15 05:28:55,863 : 2017-02-15 05:28:55,863 : File "/home/optranslations/translation-site/optranslations/settings.py", line 24, in 2017-02-15 05:28:55,863 : SECRET_KEY = os.environ.get('SECRET_KEY') 2017-02-15 05:28:55,863 : 2017-02-15 05:28:55,863 : File "/home/optranslations/.virtualenvs/optl/lib/python3.5/os.py", line 725, in getitem 2017-02-15 05:28:55,863 : raise KeyError(key) from None So, from what I can gather, it can't find the SECRET_KEY environment variable. Checking from both the bash terminal and the os.environ command in the interactive python interpreter, the key is correctly set in there. Furthermore, I tried both: SECRET_KEY = os.environ.get('SECRET_KEY') And: SECRET_KEY … -
How to get whether data for taluka level ?
Is there any way to get data directly by api call for pune district at taluka level ? for example : I have using this link to collect data for pune district https://www.timeanddate.com/weather/india/pune/historic?month=1&year=2015 I want data like : High temp , low temp , Pressure, humidity , dew point data for year -2015 at taluka level for pune district. How to get past data for some district data at taluka level for whether data?