Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to match CharField with String in Django framework?
Initially, when I am saving this 'status' field in database it is (=models.CharField(max_length=200)) So, Now I am trying to get this data in HTML template and trying to match with "string" likes the following code. But it does not working.It always shows the {% else %} output. <td> {% if "{{order.status}}" == "inprogress" %} <span class="label label-warning">inprogress</span> {% elif "{{order.status}}" == "issued" %} <span class="label label-warning">issued</span> {% elif "{{order.status}}" == "completed" %} <span class="label label-warning">completed</span> {% else %} <span class="label label-warning">overdue</span> {% endif %} </td> -
Download an image from image url
I have simple django project and i want to download image from website to my media. Url looks like this: https://i.ytimg.com/vi/Ks-_Mh1QhMc/hqdefault.jpg How can i do this? -
Reading excel file using xlrd in python and displaying on a webpage using Django
I'm trying to use django for the fisrt time. I have a python project where I'm reading an excel file and displaying its columns on the console as follows: def read_data(xls): book = xlrd.open_workbook(xls) sheet = book.sheet_by_index(0) b=[] d={} v=[] for row_index in xrange(1, sheet.nrows): # skip heading row #timestamp, text1, header, transporter, device_type = sheet.row_values(row_index, end_colx=5) col1, col2, col3, col4, col5 = sheet.row_values(row_index, end_colx=5) b.append(col2) v.append(col3) col2 = unicode(col2).encode('UTF8') col3 = unicode(col3).encode('UTF8') d.setdefault(col2, []) d[col2].append(col3) del d[''] #print(d) return d The output of d is as follows: {'1':['Name1', 'Name2'], '2': ['Name3', 'Name4'],...} I want to display it on a webpage as follows: Id | Name 1 | Name1 1 | Name2 2 | Name3 2 | Name4 I followed the tutorial here: https://realpython.com/learn/start-django/#create-an-app to setup a django_project and its structure looks as follows: How do I display that on the webpage? Any guidance about Django? Still trying to understand django. -
Django Haystack & SOLR Alphanumeric Searches
I am trying to search on a SKU field. The SKU contains letters and numbers... I only get the expected results if I search on all numbers, all letters, OR if the query has two consecutive letters. I am using Apache SOLR 4.10, Django 1.9, Django_haystack 2.6.1 products/models.py class Product(models.model): ... SKU = models.CharField(max_length=25, null=True, blank=True) .. #products/search_indexes.py class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) SKU = indexes.NgramField(model_attr='SKU', null=True) ... #portal/templates/search/indexes/products/product_text.txt {{ object.title }} {{ object.SKU }} ... #schema.xml <schema> ... <types> <fieldType> </types> <fields> ... <field name="SKU" type="ngram" indexed="true" stored="true" multiValued="false" /> ... </fields> Example1 - Requiring two consecutive non numeric characters I have an indexed product with SKU = 1594CF; Search : 1549 #Return 1594CF in results Search : 1594C #No Results Search : 1549CF # Returns 1549CF Example2 - SKU that does not have two consecutive non-numeric characters I have an indexed product with SKU = 21703F Search : 21703 #Returns 210703F Search : 21703F #No Results When I used the SOLR admin query, I get the expected results if i use /q SKU:"1594C" -
Django Queryset to return objects in Many to Many fields
I have a database table like this : ID epic_key issue_key status 1 JIR-1 JIR-12 TODO 2 JIR-2 JIR-13 OPEN 3 JIR-2 JIR-18 CLOSE 4 JIR-2 JIR-88 TODO 5 JIR-3 JIR-89 TODO 6 JIR-3 JIR-99 CLOSE In a Django template (index.html), I want to display all issue_key related with unique epic_key values. ALl the information should be displayed in the table in one go. For eg. For JIR-2 epic_key, display all issue_keys It should be like Select issue_key where epic_key is "epic_key" JIR-2 JIR-13 JIR-18 JIR-88 JIR-3 JIR-89 JIR-99 A collapsible block, a table, accordion anything can help. -
Would old version of mysql(5.1) caused performance issue in Django(1.11)
I'm rewritting a web application using Django 1.11. When i hooked up to my test mysql database (version 5.7), the performance is amazing. The page renders within 1 second. However, when I connect to the existing production mysql (version 5.1), the page takes more than 10 seconds. I installed the debug toolbar, and I found out the the query time is actually not the issue. Most of the time are in the CPU. I've eliminated the possibility of mysql performance issue by directly running the query on the database. It's not network issue either since my ping is just fine. I am wondering whether the Django is having issues with older mysql version when Django receives the data and try to map it to objects via ORM. -
error while using "django.contrib.auth.views.login"
i am getting error "view must be a callable or a list/tuple in the case of include()." while trying to use django's built-in Login system (login,logout,logout_then_login). can anyone please sort this out. bookmarks/accounts/urls.py- from django.conf.urls import url from . import views urlpatterns = [ url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'), url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'), ] bookmarks/urls.py- from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^account/',include("account.urls")) ] templates/registration/login.html- <body> <h1>Log-in</h1> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% else %} <p>Please, use the following form to log-in. {% endif %} <div class="login-form"> <form action="{% url "login" %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Log-in"></p> </form> </body> templates/registration/logged_out.html- <h1>Logged out</h1> <p>You have been successfully logged out. You can <a href="{% url "login" %}">log-in again</a>.</p> </body> -
Implementing RAML documentation in django project
I already set up RAML for django . Its reading my urls and showing the documentation page in my localhost. Now i need to write the RAML Code for documentation where i define all the requests and responses . I dont know where to write the RAML code in my django project . urls.py from django.conf.urls import url, include from django.contrib import admin from users import views from rest_framework.schemas import get_schema_view from rest_framework_raml.renderers import RAMLRenderer, RAMLDocsRenderer schema_view = get_schema_view( title='Example API', renderer_classes=[RAMLRenderer, RAMLDocsRenderer]) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/v1/users/emailsignup/', views.SignUp.as_view()), url(r'^api/v1/users/userget/', views.UserDetail.as_view()), url(r'^api/v1/users/emailsignin/', views.SignIn.as_view()), url(r'^api/v1/users/emailsignout/', views.SignOut.as_view()), url(r'^raml/$', schema_view), ] I need to know where to write the raml code in the project and how to give its url -
Running two celery workers in a server for two django application
I have a server in which two django application is running appone, apptwo for them, two celery workers are started with commands: celery worker -A appone -B --loglevel=INFO celery worker -A apptwo -B --loglevel=INFO Both points to same BROKER_URL = 'redis://localhost:6379' I can see the task configured in these two apps in both app's log, which is leading to warnings and errors. Can we configure in django settings such that the celery works exclusively without interfering with each other's taks? -
Django ListView Page Redirect into custom URL
I'm trying to redirect a page after submitting a post with the object id placed into the urlpattern. Currently it is returning the following error: Reverse for 'create_quotation_add_product' with keyword arguments '{'kwargs': {'pk': 43}}' not found. 1 pattern(s) tried: ['create_quotation/quotation-id-(?P\d+)/$'] The first view is for the user to input details and submit it into the database. The second view needs to take the data into the url to bring up the submitted object's primary key for use as a foreign key in a separate table. Views.py class CreateQuotation(ListView, ModelFormMixin): model = Quote form_class = QuoteForm template_name='quotations/create_quotation.html' def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) return ListView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) if self.form.is_valid(): self.object = self.form.save(commit=False) self.object.created_by = request.user self.object.created_date = timezone.now() self.object.save() return redirect('create_quotation_add_product', kwargs={'pk': self.object.pk}) return self.get(request, *args, **kwargs) class QuotationAddProduct(ListView, ModelFormMixin): model = Quote_Products form_class = QuoteProductForm template_name='quotations/quotation_add_products.html' def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) return ListView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) if self.form.is_valid(): self.object = self.form.save(commit=False) self.object.quote_id = Quote.objects.get(pk=self.kwargs['pk']) self.object.save() self.form = self.get_form(self.form_class) return self.get(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): … -
Celery Exception Refusing to deserialize untrusted content of type json (application/json)
I am getting below exceptions in my django app: raise self._for_untrusted_content(content_type, 'untrusted') kombu.exceptions.ContentDisallowed: Refusing to deserialize untrusted content of type json (application/json) (, ContentDisallowed('Refusing to deserialize untrusted content of type json (application/json)',), ) My Django Celery settings looks like: CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['json','application/text'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' I tried application/json too but it doesnt help. What am I missing? -
Which type of chart is this in Chart.js?
I am using chart.js and Django in my project to show data in a chart. I need different types of chart. But In chart.js documentation, I am unable to find the type of chart which I have attached. var chart = new Chart(ctx, { type: 'bar', # here shows ber type data: data, }); Which type will I write to show the chart? -
Django Pytest Test URL Based on Settings
I have an endpoint /docs in django that I only want to be visible when DEBUG = True in settings - otherwise, it should throw a 404. My setup looks like this urls.py urlpatterns = ... if settings.DEBUG: urlpatterns += [ url(r'^docs/$', SwaggerSchemaView.as_view(), name='api_docs'), ] When doing testing, though, django doesn't automatically reload urls.py, which means simply overriding DEBUG to True or False doesn't work. My tests look something like this @override_settings(DEBUG=True) @override_settings(ROOT_URLCONF='config.urls') class APIDocsTestWithDebug(APITestCase): # check for 200s ... @override_settings(DEBUG=False) @override_settings(ROOT_URLCONF='config.urls') class APIDocsTestWithoutDebug(APITestCase): # check for 404s ... Now here's the weird part: When I run the tests individually using pytest path/to/test.py::APIDocsTestWithDebug and pytest path/to/test.py::APIDocsTestWithoutDebug, both tests pass. However, if I run the test file as a whole (pytest path/to/test.py), APIDocsTestWithDebug always fails. I was wondering if anybody had come across a similar issue and either has an entirely different solution or can give me some tips as to what I'm doing wrong. Thanks! -
ProgrammingError at /home/post/4/bid/ column home_bid.amount does not exist ^
ProgrammingError at /home/post/4/bid/ column home_bid.amount does not exist LINE 1: SELECT "home_bid"."id", "home_bid"."amount", "home_bid"."bid... I keep getting this error. I am using django1.10.6 and postgresql database. Whenver I try to bid by clicking the bid button this error pops up. Bid form is also not displayed. My models.py file is from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.db import models from django.contrib.contenttypes.models import ContentType class Post(models.Model): title = models.TextField(null=True) post = models.CharField(max_length=500) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) class Bid(models.Model): amount = models.PositiveIntegerField(null=False, default=0) bid = models.ForeignKey(Post) description = models.TextField(null=True) my forms.py file is from django import forms from home.models import Post, Bid class HomeForm(forms.ModelForm): post = forms.CharField(widget=forms.TextInput( attrs = { 'class':'form-control', 'placeholder':'Write post', } )) title = forms.CharField() class Meta: model = Post fields = ('title' ,'post',) class BidForm(forms.ModelForm): class Meta: model = Bid fields = ('amount', 'description',) my urls.py file is from django.conf.urls import url from home.views import HomeView from home import views urlpatterns =[ url(r'^$', … -
Django migrate to MySql
In my Django app, I have this in the settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<myname>', 'USER': '<myuser>', 'PASSWORD': '<mypassowrd>', 'HOST': 'db677888126.db.1and1.com', 'PORT': '3306' } } I get this with 'python manage.py inspectdb' command in the shell: django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db677888126.db.1and1.com' (0)") However the connection works in PHP with the same variables... Why? -
django app won't deploy because of app/static/ FileNotFoundError
Trying to deploy this application but the deploy keeps failing because of the following: (env) Davids-MBP:fim_db davidmaness$ git push herokufim master Enter passphrase for key '/Users/davidmaness/.ssh/heroku_crib': Counting objects: 35, done. Delta compression using up to 8 threads. Compressing objects: 100% (23/23), done. Writing objects: 100% (35/35), 4.29 KiB | 0 bytes/s, done. Total 35 (delta 24), reused 18 (delta 12) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 112, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 397, in listdir remote: … -
Request Approvals by E-mail and process it Python + Django
Maybe I am not asking the right question in the search area, but I can't find an answer for this. I am pretty sure that many people have this use case, but as a beginner in Django + Python, I need to ask it. I have user that fills up a form and the data is stored in the database. Basically this form asks for an access to a Database and after the form is submitted I want my program to send an email to the user's manager and to the DBA to APPROVE or DENY it. Very simple, right? My idea is that in this e-mail I send two URL's, one for approving and one for denying the request. When the URL the is clicked I send a response to the server with an update in the manager_approval field. Has anyone implemented this solution, or could point me to something that could help me? I am doing everything using Django + Python. Regards, Marcos Freccia -
Velidating upload file type in Django
I have a Post model with a filefield which is used to upload files. How can I validate the file type (pdf for now, or any other types if I change to later). Preferably i'd like to validate the content, but if not I guess suffix would do too. I tried to look up online but most of the solutions I found are from way back and as the Django document get updated they don't work any more. Please if anyone can help. Thanks. class Post(models.Model): author = models.ForeignKey('auth.User',default='') title = models.CharField(max_length=200) text = models.TextField() PDF = models.FileField(null=True, blank=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Django-organizations OrganizationUserAddForm is not working
I'm using Django-organizations and I'm trying to use the OrganizationUserAddForm in a custom view. I'm using Django 1.10.7 The form is not valid although I have some date in my request.POST. However, when I printout form.bound it gives 'False' This is my code: views.py def Mainadmin(request, slug): study = PhaStudy.objects.filter(hierarchy__company__slug = slug) users = OrganizationUser.objects.filter(organization__slug =slug) organization = Organization.objects.get(slug=slug) #check if we have post lets create the new user if request.method == "POST": userAddForm=OrganizationUserAddForm(request.POST, organization=organization) print(userAddForm.fields) print(request.POST) print(userAddForm.is_bound) print(userAddForm.data) if userAddForm.is_valid(): userAddForm.save() else: userAddForm = OrganizationUserAddForm(None, organization) context = {'studies':study, 'users': users, 'form': userAddForm} return render(request, "phaadmin/users.html", context) The printout from my console is the following OrderedDict([('is_admin', <django.forms.fields.BooleanField object at 0x7ff049aab9d0>), ('email', <django.forms.fields.EmailField object at 0x7ff049ad8ad0>)]) <QueryDict: {u'csrfmiddlewaretoken': [u'TtM1aTQK5Ppzh0fQKz18V9pK02wB1HI4IVORk1U1HcsRe9N9POIzKPstDIgIWUPg'], u'email': [u'something@exemple.com'], u'submit_button': [u'Submit']}> False {} Thanks a lot for the help. -
XMLHttpRequest cannot load http://xx-xx.s3.amazonaws.com/. Response to preflight request doesn't pass access control check
I am trying to implemet react fineuploader direct upload to s3 bucket.I get this error when i try to upload files. XMLHttpRequest cannot load http://xx-xx.s3.amazonaws.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://x.x.com' is therefore not allowed access. The response had HTTP status code 403. In my local i can write to s3 using cors-anywhere if i append it before xx-xx.s3.amazonaws.com I am using react+node+express and Django as backend. -
How do I make my website respect the spaces?(in a admin post)
I have a website called www.confiam.com.br, which is a django project. I have been doing some adjustment, and in the last adjustment I broke something from the posting paragraph, now this doesn't respect the blanks, or even when I skip some lines. In the html I have: <div class=item> <p><h1>{{ post.nome_evento }}</h1></p> <center><picture>{% cloudinary post.foto_evento %}</picture></center> <p><h2>{{ post.apresentacao_evento }}</h2></p> <br> </div> and in the css I have: p{ text-align:justify; } .item h1{ font-family: 'Kurale'; margin: 0 auto; position: relative; padding:20px; word-wrap: break-word; text-align: center } .item h2{ font-family: 'Kurale', serif; position: relative; margin: 0 auto; padding:20px; word-wrap: break-word; text-align: center } I am going to be so much happy if somebody can help me, I have no idea what mistake I had. Very thanks everyone. -
Error linking app with database in Dokku in LightSail server
I am develop web server with Django, I have my code in a repo, my boss contract an Amazon service called LightSail so I understand this server is like ours, since it is not an instance of the Amazon community, it turns out that I try to use Dokku to implement my web server and when I make the link between my base Data created with Dokku and my app created with dokku I get this error. ubuntu@ip-172-26-13-39:~/trackerServer$ dokku postgres:link trackerdb trackerServer no config vars for trackerServer -----> Setting config vars DATABASE_URL: postgres://postgres:02foobarfoobarc24d53011@dokku-postgres-trackerdb:5432/trackerdb -----> Restarting app trackerServer App trackerServer has not been deployed I don't understand why, I trying the tutorial of Dokku, The steps I've taken are few, I'll post them. $ git clone https://github.com/fabulias/trackerServer.git $ cd trackerServer/ ~/trackerServer$ dokku apps:create trackerServer ~/trackerServer$ sudo dokku plugin:install https://github.com/dokku/dokku-postgres.git ~/trackerServer$ dokku postgres:create trackerdb ~/trackerServer$ dokku postgres:link trackerdb trackerServer In a moment I had returned some error, but I do not understand why that final message appears that the web server could not be deployed. -
How to send a body in Swagger Django documentation?
I try to use Swagger documentation in my Django project however I am not able to send body. Furthemore, List Operations doesn't work. Anyone have an idea how to fix it? I have only default settings: urls.py: from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^swagger', schema_view), ] I can only list all my URLs and log in as admin. Logout doesn't work. At this moment when I choose Expand Operations I see something like this: -
Django how to use connection_created signal
I am looking to find out when a connection is made to my Django database, or when my Django server is restarted. I found the connection_created Django signal. The description is: Signals sent by the database wrapper when a database connection is initiated. So I think using this signal will be a good solution for my case. I want to run a function once the connection is made. I can't find any documentations on the use cases of this signal. connection_created.connect is probably the function to use. This function takes in a bunch of arguments, but the ones that are relevant are self, receiver, sender and weak. Does anyone know how I can use these arguments and this function to run my function at a new connection instance? Also if anyone has any alternative solutions other than this signal, I'd love to hear them. -
Finding common elements based on a condition in django
I have three models connected through an m2m relationship. Stop represents a bus stop, Route represents a bus route, and RouteStation is an intermediary model connecting Stop and Route to one another, with information about where that stop is on the route (RouteStation.order). class Stop(models.Model): lat = models.FloatField() lon = models.FloatField() name = models.CharField(max_length=250, blank=True, default="None") stop_id = models.IntegerField(unique=True) class Route(models.Model): route_id = models.CharField(max_length=20) journey_pattern = models.CharField(max_length=20) stops = models.ManyToManyField(Stop, through="RouteStation") class RouteStation(models.Model): stop = models.ForeignKey(Stop, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) order = models.IntegerField() Given two stops, I need to return a queryset containing all routes common to both stops, where the value of RouteStation.order is higher for the second stop than the first. This condition ensures that the second stop is accessible via the first stop on that route. I can find the common stops using the following: stop1 = Stop.objects.get(stop_id=origin) stop2 = Stop.objects.get(stop_id=destination) routes1 = stop1.route_set.all() routes2 = stop2.route_set.all() common = routes1 & routes2 However I'm having trouble filtering this based on RouteStation.order values. Does anyone know the best way of going about this?