Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get non-hashed urls when using Django's ManifestStaticFilesStorage
When using ManifestStaticFilesStorage the static template function always returns the 'hashed' file name (when DEBUG=False). Is there any way to get the non-hashed regular file name in the template? It seems odd that there's no obvious way since collectstatic always includes both hashed and non-hashed files, but the non-hashed ones would never be used. I'm guessing what I need to do is create my own templatetag, but was wondering if I missed something. -
Django Default image for ImageField using Google Drive Storage
I'm using an ImageField to store the images of my models and implementing Google Drive Storage as a backend to store the data. However, in some cases it is necessary to load a predetermined image. So try to assign a static image from the model but it did not work from django.db import models from gdstorage.storage import GoogleDriveStorage # Define Google Drive Storage gd_storage = GoogleDriveStorage () class Album (models.Model): name = models.CharField (max_length = 250) cover = models.ImageField (upload_to='images/', default='static/no_cover.jpg', storage=gd_storage) Then I solve it from the template in the following way but I do not think it is the most ideal. {% if album.cover.url == None%} <img class="card-img-top" src="{% static 'no_cover.jpg'%}"> {% else%} <img class="card-img-top" src="{{album.cover.url}}"> {% endif%} Any idea how to load the static image? -
Variables not displaying on Django template
I have added variables to my Django views and I am trying to call them on my template. I have researched several related questions and I understand that I needed to add a context, which I believe I have done. I am slightly confused by the use of render(), is this required when using generic views? Here is an example of my view: class SubgenView(generic.TemplateView): template_name = 'projects/subgen.html' context_object_name = 'subject_line_gen' all = { "first": ['Save up','New in','Huge savings',], "cat": ['trainers','suits','onesies'], "brand": ['one', 'two', 'three'], "third": ['at crazy prices', 'in colours galore'], "end": ['click now!', 'come and get it!'] } first = random.choice(all['first']) def create_subject_parts(self): first = random.choice(all['first']) test = 'hi' return first Adding {{ first }} or {{ test }} to my template yields nothing, what am I missing? -
Static files not loading (Django 1.11)
I am trying to set up a development version of a Django Rest (1.11) application on a mac. I have run the python manage.py collectstatic command and this resulted in the files being copied into a 'static' folder. However when I run the application (python manage.py runserver) none of the static files load in the browser (no css). The Network tab shows the status of the static files as 404. My settings.py file has the following: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR + '/abba_rest/static/' Appreciate any advice on how to debug this issue. -
page not found when useing slug url in django 2
I have a problem with slug URL .. when I use it and run the server it gives me that the page it's found urlpatterns = [ path('admin/', admin.site.urls), path('', RestaurantListView.as_view()), path(r'restaurant/^(?P<slg>[\w-]+)/$', SearchRestaurantListView.as_view()), path('about', TemplateView.as_view(template_name='about.html')), path('contact', TemplateView.as_view(template_name='contact.html')), ] here's the urls file and this is the server -
Is there a way i could use open cv in django but inside the browser
Blockquote i'm trying to write a django app to detect faces via opencv but the problem is the opencv image comes from the terminal/command interpreter but not actually from the browser it self i was hoping is there any way i could use opencv cam via browser itself -
Django admin camera upload - Android Chrome
I'm uploading images in Django Admin. When using a cell phone I want the user to be able to use their camera. This works in Firefox but not on Android Chrome where I get the following traceback: Traceback: File "/var/www/scheduler/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/var/www/scheduler/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 117. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/var/www/scheduler/env/lib/python3.6/site-packages/django/middleware/csrf.py" in process_view 294. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/var/www/scheduler/env/lib/python3.6/site-packages/django/core/handlers/wsgi.py" in _get_post 111. self._load_post_and_files() File "/var/www/scheduler/env/lib/python3.6/site-packages/django/http/request.py" in _load_post_and_files 310. self._post, self._files = self.parse_file_upload(self.META, data) File "/var/www/scheduler/env/lib/python3.6/site-packages/django/http/request.py" in parse_file_upload 269. return parser.parse() File "/var/www/scheduler/env/lib/python3.6/site-packages/django/http/multipartparser.py" in parse 175. 'The number of GET/POST parameters exceeded ' Exception Type: TooManyFieldsSent at /admin/houses/house/4/change/ Exception Value: The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. I'm using the following form: class HouseDocumentInlineForm(forms.ModelForm): class Meta: model = HouseDocument fields = '__all__' widgets = { 'doc' : forms.FileInput(attrs={ 'accept': 'image/*;capture=camera', }) } And this is the TabularInline class HouseDocumentInline(admin.TabularInline): readonly_fields = ['get_current_file'] fields = ['name','doc','get_current_file'] model = HouseDocument extra = 1 can_delete = True form = HouseDocumentInlineForm def get_current_file(self, obj): return mark_safe('<a target="_blank" href="%s">%s</a>' % (obj.doc.url, obj.doc.url)) get_current_file.short_description = "Current File" I originally tried with the standard Django admin form but was getting the same error so tried this to see if … -
Integrating python-social-auth users with existing app users
I have a Django app that already has existing users and now I'm trying to implement social authentication using auth0. When signing in with social authentication, I see that a new record is created in both social_auth_usersocialauth and the auth_user tables in the db. These new records are created regardless of whether a user with the same username is already present in auth_user. My understanding is that python-social-auth FIRST checks in social_auth_usersocialauth table if there's a user with the same username and THEN creates a user in auth_user accordingly. How can I make it first check in the auth_user table if there's already an entry with the same username and if so create a new user ONLY in the social_auth_usersocialauth table and associate it to the one in auth_user. https://python-social-auth-docs.readthedocs.io/en/latest/pipeline.html -
Django Rest Framework Module Not Found Error
I made sure that every step was followed correctly but this happened and I don't know how to solve this. **ERROR:** Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000017F5090E620> Traceback (most recent call last): File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Chrisannesuuuu\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Chrisannesuuuu\etona\etona\etona\urls.py", line 3, in <module> import etona.quickstart.views ModuleNotFoundError: No module named … -
Django : 'NoneType' object is not callable
I am trying to grab the data from website and store in Django model field. Just for testing purpose, I am using only tags here which is to be stored in a model field called tags. But it's giving error. from django.shortcuts import render import requests from bs4 import BeautifulSoup from scrapy.models import scrape def scrapy(request): url = 'https://www.dataquest.io/blog/tag/python' site = requests.get(url) soup = BeautifulSoup(site.text, 'lxml') post_feed = soup.find('div', class_='post-feed') posts = post_feed.find_all('article', "post-card") for post in posts: tags = post.find('span', class_='post-card-tags') # Creating Object store = scrape() store.tags = tags args = {'tags': 'tags'} store.save() return render(request, 'template/scrapy.html') models.py from django.db import models class scrape(models.Model): tags = models.CharField(max_length=199) def __str__(self): return self.tags -
Get database column if 2 other things match in DB row
I am trying to create a view for when users want to download their file. I have a HTML button that says download, and when that is clicked I want to redirect it to my view to do some stuff. Now each download button has a unique path to the file which I also have saved in my database. So in my views I need to check if a row has some columns that matches the logged in user (request.user), and a TaskID which is in my HTML table where the download button also is located -> And if those matches then grab the column containing the OutputPath. How would I construct such a query? <div class="tasks-finished"> <h1>Finished tasks</h1> </div> <div class="tasks-list"> <table> <tr> <th>Name</th> <th>Task ID</th> <th>Status</th> </tr> {% for item in query_finished %} <tr> <td>{{ item.TaskNavn }}</td> <td>{{ item.TaskID }}</td> <td><a href="{{ myDownloadView }}">Download</a> </tr> {% endfor %} </table> -
Performing full text search on more than one field from model (Django 2.1)
I want to perform full text search on 2 fields from my model. Here is my current code: if 'keyword' in request.GET: search_term = request.GET['keyword'] vector = SearchVector('Title', weight='A') + SearchVector('Content', weight='B') articles = articles.annotate(similarity=TrigramSimilarity(vector, search_term),).filter(similarity__gt=0.01).order_by('-similarity') This code returns the error message "function similarity(tsvector, unknown) does not exist". I assume this is because my code isn't how you would perform search on more than 1 field. What's the proper way of searching in more than one field? -
A Chatbot that sends the queries to the Staff and updates DataBase
I want to create a chatbot using Machine Learning and I don't know where to start, Whether to use Tensorflow and what web framework to use Django etc and how to integrate these things into my web page, also what and how will I be able to get the data sets required for doing so. -
Wrong gmail after send message from contact form. Django 2.1.5
I send message from pythonanywhere, but to my gmail coming message with my email, as sender email (see screen). forms.py class ContactForm(forms.Form): subject = forms.CharField() contact_email = forms.EmailField() content = forms.CharField(widget=CKEditorUploadingWidget() views.py def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['contact_email'] content = form.cleaned_data['content'] try: send_mail(subject, content, from_email, ['dinamo.mutu111@gmail.com'], ) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, 'contact.html', {'form': form}) settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'dinamo.mutu111@gmail.com' EMAIL_HOST_PASSWORD = '****' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER All settings for gmail.com enabled -
Show document in template from BinaryField
I have a model with a BinaryField storing a document (pdf, doc, etc.). It seems to be working to upload it there through a FileField, but is it even possible to show it in the template so users can download it? -
Retrieve object by specific field using DRF ViewSet
Is it possible to retrieve an object by model field other than pk in ViewSet? Below is much simplified example of my case. I have two models: MainModel and RelatedToMainModel. RelatedToMainModel relates to MainModel via OneToOne field called main. I have url pattern with attached ModelViewSet that looks something like .../main_model/{id}/related_to_main_object My ViewSet should be albe to retrieve, create and update RelatedToMainModel object by id of MainModel in main field. -
how can i display django field on the base.html?( for classified template ) did i need ajax or there is another way?
I am new in Django and I wonder how can I display Django field on the base.html? Same thing in the classified header. I want to add category, state and city in the header. Did i need Ajax or there is another way? I have tried to search in google but the information about Django 2.1.5 is so poor. Thank you -
Iterating over pandas dataframe when you don't know the indexes or number of columns
I'm sending a pandas dataframe to a Django template using to_html(). I'm adding classes as well as working with the css to make my resulting table look the way I want it. df.to_html(classes="table table-bordered table-sm g-font-secondary") But now I need to add a class "g-bg-white" to tags based on the content of the data cell: <td class="g-bg-white">item needs white background</td> In addition I need to add a couple header rows at the top of the table: <tr> <td colspan="2" class="no-line"></td> <th colspan="x" class="g-bg-primary text-center no-line">LABEL</th> </tr> <tr> <td colspan="2" class="no-line"></td> <th scope="col">1</th><th scope="col">2</th><th scope="col">3</th><th scope="col">4</th><th scope="col">5</th><th scope="col">6</th> </tr> As well as a tag into the first row of data: <th scope="row" rowspan="y" class="g-bg-primary text-center">LABEL</th> My sense is that this level of manipulation requires that I iterate through the dataframe on the template. The issue there is that the Django template does not know the indexes or the number of columns in each table. So I don't know that this would work for me: for index, row in df.iterrows(): print(row['c1'], row['c2']) -
how do I search null or none in mongoengine in my django work?
there is a field in my mongodb, i want to search the field, no matter this field is None or not, how do i search? for example:Robot.objects(data_set_id=None) i use this to search ,but get the error: bson.errors.InvalidId: 'None' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string -
html page twisted in phone UI
I have the django program with base.html as followed. But when it shows in the phone page, the html is not as original as the html page. The nav function cannot show in one line as the picture below. {% load bootstrap3 %} {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=100%, initial-scale=1"> <title>xxx</title> <link rel="shortcut icon" href="{% static 'images/aaaa.png' %}"/> {% bootstrap_css %} {% bootstrap_javascript %} <style> nav {width: auto;} </style> </head> </html> </head> <body> <!-- Static navbar --> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> </button> <a class="navbar-brand" href="{% url 'xxx:index' %}">Introduction</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'learning_logs:aaa' %}">A</a></li> <li><a href="{% url 'learning_logs:topics' %}">B</a></li> <li><a href="{% url 'learning_logs:results' %}">C</a></li> <li><a href="{% url 'learning_logs:results2' %}">D</a></li> </ul> <ul class="nav navbar-nav navbar-right" style="position:relative;top:15px;right:0px;color:#5B5B5B"> {% if user.is_authenticated %} Hello, {{ user.username }}&nbsp;&nbsp; <a href="{% url 'users:logout' %}">log out</a> {% else %} <a href="{% url 'users:register' %}">register</a> <a href="{% url 'users:login' %}">log in</a> {% endif %} </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> <div class="page-header"> {% block header %}{% endblock %} </div> <div> {% block content %}{% endblock %} </div> … -
Deploy one django project with multiple app on multiple subdomains on AWS EC2
I have one django project which contains 2apps namely, admin and api. The admin app is dependent on api app to access the models. I have 2 subdomains like: admin.xxxx.com and api.xxxx.com. This project is currently deployed in AWS EC2 using gunicorn + nginx. Is there any way I can point my admin app to admin.xxxx.com and api to api.xxxx.com? -
LinkColum with urlencode()
I have a LinkColum like this: artist = tables.LinkColumn('artist_detail', args=[A('artist')], Unfortunately, there are artists which have special characters like a slash in it and are breaking the Django-URL-system. I tried to encapsulate A('artist') with django.utils.http.urlencode() but that's not working unfortunately. Is there a way to solve this issue? -
Is Saleor good for selling for a lottery?
I plan on developing an ecommerce site, hopefully using saleor. The site is supposed to be selling e tickets for a lottery. My question is, do you think saleor is suitable and customizable enough for this? Any advice would be much appreciated! -
django python execute mssql query and print to web page
Is there any way to execute MsSql query by django-python and print result to web page? I want to write a script to watch ACS logs on web browser. Im already have a SQL query that returns some last logs and I want to watch logs on web page with dynamic update information -
How to implement django-mongo-auth
i am not able to implement the django-mongo-auth library google authentication to my project. i have seen the docs.. but i am not able to understand how can i implement it. this is the docs: https://github.com/mitar/django-mongo-auth/tree/master/mongo_auth i have been struggling to understand. i want to implement django-mongo-auth for google authentication. please help me someone with his/her knowledge. thank you