Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add a hyperlink inside your textarea
I want to add a hyperlink in between my texts. I don't want to hardcode it all in my template What is the best approach for it? For e.g. Where is Angy? -
Django models description in default permissions
Is there some possibility to add description to default permission in django model? My own permission look like this: permissions = ( ("add_deposit", "Can create a deposit") ) And default permissions looks like this: default_permissions = ('add', 'delete', ) But there is no description to them. Is there some possibility to add some there? -
Django: raise ValidationError doesn't work
Anyone who can explain me, why my ValidationError in my form doesn't work? I can see "Test" in my terminal, but the ValidationError doesn't show. I am happy to share the full code, but maybe the mistake already lies in the snippet below? def clean_ticket(self): ticket = self.cleaned_data['ticket'] if not self.event == ticket.event: print("Test") raise forms.ValidationError( _("The ticket you chose doesn't belong to your event."), code='ticket_belongs_to_event_validation', ) return ticket -
Django: Auto suggest using Elasticsearch DSL
I am using elasticsearch-dsl to index data in elasticsearch index. I am am using following class to create elasticsearch document: class BooksDoc(Document): title = Text( analyzer=my_analyzer ) author = Text( analyzer=my_analyzer ) publisher = Text( analyzer=my_analyzer ) image_url = Text(analyzer=my_analyzer) price = Text(analyzer=my_analyzer) category =Text(analyzer=my_analyzer) published = Boolean() upload_date = Text() class Index: name = 'books' Here is my analyzer: my_analyzer = analyzer('my_analyzer', tokenizer=tokenizer('trigram', 'edge_ngram', min_gram=1, max_gram=20), filter=['lowercase'] ) I am using following function to index document: def indexing(self): doc = BooksDoc( meta={'id': self.id}, title=self.book_title, author=self.book_author, publisher=self.book_publisher, image_url=self.front_image, price=self.book_price, catagory=__catagory, published=self.isPublished, upload_date=self.dateadded ) try: doc.save() return doc.to_dict(include_meta=True) except: print(traceback.format_exc()) return None I want to implement search such that when user enters a search string i can query elasticsearch and fetch all the records where i find a match. For example, if user enters "Boo" then all the records containing string "Boo" should be returned.Right now search works fine when string matches exactly in elasticsearch but i also want to fetch record if there is a partial match. How can i do this? -
django: unable to login using django Remote authentication
I'm developing a new django project ,in the i have created a simple login page, which i want to just login and go to the home page. when i try to login i'm getting and login is not happening successfully. Project name: mysite appname : dsmdata Below are the codings project(mysite) Settings.py file below """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.environ['REMOTE_USER'] = "dsmuser1" #LOGIN_URL = '/dsm/login' # Redirect to home URL after login (Default redirects to /accounts/profile/) #LOGIN_REDIRECT_URL = '/dsm/logged_in' LOGIN_REDIRECT_URL = '/' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'y%cwxi-m5s-0zct+k%$u1$z!#o#u52zu_!z*#8(8saqdx+6t$l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': … -
get_error_or_404 returning a tuple with no attributes
Learning django and recently can't get this error to be fixed. Error says 'tuple' object has no attribute 'title'. My views.py file looks like this: def post_detail(request): instance = get_object_or_404(Post, id=3), context = {"instance": instance, "title": instance.title # Line of error } return render(request, "post_detail.html", context) template file post_detail.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Post Details</title> </head> <body> <h1> {{ title }} logged in.<br><br></h1> {{instance.title}}<br> {{instance.content}}<br> {{instance.updated}}<br> {{instance.timestamp}}<br> {{instance.id}}<br><br> </body> </html> models.py class Post(models.Model): title = models.CharField(max_length=120) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False,auto_now_add=True) def __str__(self): return self.title Can someone point me where I'm going wrong? -
CSS in Django 2.0
Here is a HTML code that my teammate wrote that uses CSS/Bootstrap How do I render it in Django. It works when I open the file as HTML but I am not able to render it in Django <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <link href="vendor/simple-line-icons/css/simple-line-icons.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/stylish-portfolio.min.css" rel="stylesheet"> -
Unable to find Manage.py in Anaconda after Djnago installation
I am just starting with Django. I am trying to run this code found over internet "c:/python35/python manage.py startapp webapp". Since i have installed anaconda i need to change the path mentioned above, but i am not able to find manage.py in anaconda3 folder. Guys let me know your thoughts on this -
Django - Querying Database to created by other application
I have an sqlite database located at /home/pi/Desktop/Databsaes/data.db and wish to access it from my models.py script. To view table contents in a normal command prompt I would execute: sqlite3 sqlite> .open data.db sqlite> SELECT * from table1 How can I perform something of the sort directly in my models.py script? Models.py is still untouched: from __future__ import unicode_literals from django.db import models # Create your models here I have been reading through this official tutorial, but I do not understand how to access my local db and perform the above. From what I am gathering, field lookups may be used, which specify arguments for QuerySet methods (such as get()). -
Django: add choices to a ForeignKey field
I'm trying to add a choices option to a ForeignKey field. But that prevents the input form from getting validated. I'm not sure if you can use choices in ForeignKey field, but how else would you provide human readable output for the choices? I don't want the user to be able to choose from all groups and don't want to display the actual group name as it's contains additional info for the admins, that shouldn't be visible to the user, for cosmetic reasons. Any idea how to achieve that would be greatly appreciated. Here is my code: The model: from django.contrib.auth.models import Group as DjangoGroup class Category(models.Model): created_by = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='category_author') last_edited_by = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='category_editor') name = models.CharField(max_length = 100) privileges = models.ForeignKey('auth.Group', on_delete=models.PROTECT, blank=True, null=True, choices=((DjangoGroup.objects.get(pk=5), 'Test group'),)) The Form: from django import forms from .models import * class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = ('created_by', 'last_edited_by',) With this code the form gives the desired option 'Test group', but when I try to submit it I get the following error: Select a valid choice. TestGroup(just for testing purposes) is not one of the available choices. with 'TestGroup(just for testing purposes)' being the actual group name … -
Pythonic way to intersect with unknown number of parameters
I have to make a QuerySet.intersection() between an unknown number of parameters. Is there a better way to write the following code ? profileQuerySetList = None for tag_id in current_tags: if profileQuerySetList: profileQuerySetList = profileQuerySetList & Profile.objects.filter(tags__id=tag_id) else: profileQuerySetList = Profile.objects.filter(tags__id=tag_id) profiles = Profile.objects.intersection(profileQuerySetList) -
Add links to forms using custom tags
So I have a simple model with a CharField called context. The user submits the form and the context field is displayed in a <“pre”>element. However, even if the user inputs HTML tags such as <“b”> and <“a”>in the form, it doesn’t get displayed as a bold or an anchor but instead the tag itself gets displayed. I want the user to be able to use these tags to style texts and add links, or even better, be able to use custom tags such as [b] and [a www.blahblah.com]. -
Filter list of dictionaries with higher key value remove duplicate dictionaries
I have list of dictionaries like: sel_list = [{'a': 8}, {'a': 4}, {'a': 4}, {'b': 8}, {'b': 9}] I want to remove duplicate dictionaries and if more than one dictionaries have same key but different values then choose that dictionary with higher value. Like : sel_list = [{'a': 8}, {'b': 9}] I have tried: [i for n, i in enumerate(sel_list) if i not in sel_list[n + 1:]] its results in: [{'a': 8}, {'a': 4}, {'b': 8}, {'b': 9}] What I can do to achieve my results? -
TypeError at /blogs/article-list-view/ 'str' object is not a mapping in django python framework
TypeError at /blogs/article-list-view/ 'str' object is not a mapping Request Method: GET Request URL: http://127.0.0.1:8000/blogs/article-list-view/ Django Version: 2.1 Exception Type: TypeError Exception Value: 'str' object is not a mapping Exception Location: /home/neilravi/.local/share/virtualenvs/practice-a8_j53lF/lib/python3.6/site-packages/django/urls/resolvers.py in _populate, line 443 Python Executable: /home/neilravi/.local/share/virtualenvs/practice-a8_j53lF/bin/python Python Version: 3.6.4 Python Path: ['/home/neilravi/practice/src', '/home/neilravi/.local/share/virtualenvs/practice-a8_j53lF/lib/python36.zip', '/home/neilravi/.local/share/virtualenvs/practice-a8_j53lF/lib/python3.6', '/home/neilravi/.local/share/virtualenvs/practice-a8_j53lF/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/neilravi/.local/share/virtualenvs/practice-a8_j53lF/lib/python3.6/site-packages'] Server time: Wed, 8 Aug 2018 06:19:18 +0000 -
Django: Image is stored twice
In my web application I have a model called Photo that contains a field image and thumbnail. When a user uploads an image, I'm resizing and compressing it using pillow. Unfortunately, I just noticed that both the normal image (image field) and the thumbnail (thumbnail field) are stored twice in the file system. Here you can see the code in my models.py for the Photo: class Foto(models.Model): image = models.ImageField(upload_to=RandomFileName(directory="photos"), validators=[ FileExtensionValidator(allowed_extensions=['png', 'gif', 'jpg', 'jpeg']), FileSizeValidator(mb=10), ]) thumbnail = models.ImageField(editable=False, upload_to=RandomFileName(directory="photos/thumb")) def save(self, *args, **kwargs): # Compress the uploaded image compressed_image_binary, file_extension = compress_image(max_width=1500, max_height=1300, quality=83, original_image=self.image) # Because of the 'upload_to' parameter, the filename here does not matter. Only extension needed! self.image.save("_." + file_extension, ContentFile(compressed_image_binary), save=False) del compressed_image_binary # Just let's make sure memory can be freed # Now create a thumbnail thumbnail_binary, file_extension = compress_image(max_width=320, max_height=300, quality=60, original_image=self.image) # Because of the 'upload_to' parameter, the filename here does not matter. Only extension needed! self.thumbnail.save("_." + file_extension, ContentFile(thumbnail_binary), save=False) super().save(*args, **kwargs) def compress_image(max_width, max_height, quality, original_image): MAX_WIDTH = max_width MAX_HEIGHT = max_height image = Image.open(original_image) image.thumbnail((MAX_WIDTH, MAX_HEIGHT), Image.ANTIALIAS) image_type = image.format if image_type not in ('JPEG', 'GIF', 'PNG'): raise Exception("Image has wrong file type: " + image_type) # Save … -
Add Facebook login and data Collection from pages in django(Social Auth)
I have used django-social-auth in my django application . Since Facebook has updated their policy about request url that it must be from https my django application has giving me this error : Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https:/ I have already installed ssl in my site and it worked fine with Twitter and google.In twitter i have given this callback URL : http://example.com/oauth/complete/twitter/ same goes with google, Facebook does not allow you to even add callback URL with http in it. Now I can not get pass through this. Is their any way to get go pass through it. Help needed . -
Django cms: {% url %} tag is not loading under static_placeholders [ django-cms version : 3.5.2 ]
Use-case: The requirement is to push my site's footer to static-placeholders. Example: <footer id="DarkFooter"> <p>disclaimer txt<p> <!-- some links of the site in list --!> <ul> <li class="footer-item" id="ContactFooter"><a href="{% url 'app1:contact' %}">Contact</a></li> <ul> </footer> Now I want the contents to be in static placeholder. Changed the above footer as - {% load cms_tags %} <footer id="DarkFooter"> {% static_placeholder 'footerv1' %} </footer> Issue: After changing to static_placeholders the url tags are not loaded.The contact us link is loading with https://localhost/page1/%7B%%20url%20'app1:contact'%20%%7D ( here app1:contact was my argument to url tag) -
Querying MYSQL with Django framework in HTML
I am building a site using Django framework with google api + MYSql. Currently I display all data entries' latitude and longitude from my dB onto a heatmap layer. I need to be able to filter my data to refine what I am displaying. e.g - I would like to filter HazardInside.title by types such as "Slip" and "trip". This filter will need to be able to filter by many other requirements simultaneously such as date and weather conditions. e.g title="Slip" + weather="Wet" + between dates of (dd/mm/yy - dd/mm/yy) My current problem is successfully creating a view that requests new data from my dB and parses it to my HTML page. models.py class HazardInside(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=250) incident_date = models.DateField(auto_now=False) lat = models.FloatField(max_length=25, default=0.00000) lng = models.FloatField(max_length=25, default=0.00000) room_number = models.CharField(max_length=25) floor = models.CharField(max_length=10) def __unicode__(self): return self.title class InjuryInside(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=250) incident_date = models.DateField(auto_now=False) lat = models.FloatField(max_length=25, default=0.00000) lng = models.FloatField(max_length=25, default=0.00000) room_number = models.CharField(max_length=25) floor = models.CharField(max_length=10) def __unicode__(self): return self.title views.py from django.shortcuts import render, HttpResponse from qutheatmap.models import Markers, HazardInside, InjuryInside def home(request): marker = Markers.objects.all() hazardinsides = HazardInside.objects.all() injuryinsides = InjuryInside.objects.all() mapdata = { 'markers': marker, 'hazardinsides': … -
Single form contain Multiple Model field, so how to use this form in UpdateView with multiple model in django
I have three Models name User, Tenant and TenantUser. I want to output like this Setting.html But i cannot write view to show this "models.py " class Tenant(models.Model): name = models.CharField(max_length=100) memo = models.TextField(blank=True) users = models.ManyToManyField(settings.AUTH_USER_MODEL, through='db.TenantUser', blank=True) agent_timezone = models.CharField( max_length=30, choices=const.AGENT_TIMEZONES) class TenantUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) tenant = models.ForeignKey('Tenant', on_delete=models.CASCADE) ui_language_code = models.CharField( max_length=5, choices=const.UI_LANGUAGE_CODES, default=const.UI_LANGUAGE_CODES.japanese) "forms.py" from db import const class EditMemo(forms.Form): agent_timezone = forms.ChoiceField(choices=const.AGENT_TIMEZONES) memo = forms.CharField(widget=forms.Textarea) ui_language_code = forms.ChoiceField(choices=const.UI_LANGUAGE_CODES) "Views.py" class AccountSettingsView(LoginRequiredMixin,UpdateView): # views Code here that can update two models tanant and tanantUser -
django javascript variable manipulate in for
I was reading: Built in template tags and filters so went using django-mathfilters, works great but how do I do complex calculations using them? What I want is X/((100+Y)/100)-Z I was Doing: {{ X|div:100|add:Y|div:100 }} using mathfilters which gives me wrong result. I think JavaScript would be better: currently I have HTML as: {% for item in items %} <tr> <td>{{a}}</td> --see javascript <td>{{b}}<td> --see javascript </tr> {% endfor %} And came across: <script type="text/javascript"> var a = "{{ item.X }}"; item.X = item.X/((item.Y+100)/100); var b = item.Z - a; </script> But how do I display variable there? <html> <head> <script> function myFunction() { var number = "123"; document.getElementById("myText").innerHTML = number; } </script> </head> <body onload="myFunction()"> <h1>"the value for number is: " <span id="myText"></span></h1> </body> </html> The div would work, but the variable has to be changing for each row! -
Django application redirecting all urls
I made a very simple django application, and just added a form (and related views, entries in urls.py etc), however I noticed no matter what URL I put in the address bar it always just redirects to the homepage. This is my urls.py: from django.conf.urls import url from . import views urlpatterns = [ url('', views.index, name='index'), url('booking/new/', views.booking_new, name='booking_new'), ] and my views.py: from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.template import loader from .forms import BookingForm def index(request): template = loader.get_template('/home/dave/dave/dave_site/home/templates/home/index.html') return HttpResponse(template.render({}, request)) def booking_new(request): form = BookingForm() return render(request, 'home/booking_edit.html', {'form': form}) I noticed when attempting to access /home/booking/new or /booking/new that it just loads the default homepage I setup. When putting in any url, even a nonsense one, it still shows this website, and the log to the console from running runserver shows ever request as HTTP 200 successful. I don't seem to have setup a 'catchall' url, so not sure why this is happening. What is the problem and how can I fix it? -
How do I convert a file to mp3 before saving django?
I found some information on extending and changing the save() function on the model, but a few other people mentioned that it was bad practice to do that, and one should instead modify the admin form. Any help would be great, I have been searching around and trying to solve this for a few hours now. Thank you. -
How to block user from opening pages if user is not logged in
I have login and work page. I want user to login first and then redirect to work page. This scenario is working fine for me. However when I try hitting the work page it is giving me error, I am checking it through session variable which I know I am doing it wrong as I am not sure which user is trying to access the page if user tries to hit the work page directly as there will be many users in database. How can I restrict user to hit the work page directly and if user does it should redirect to login page views.py file method is as follows:- def chatbox_index(request): context={} template_name = "bot/chatbot.html" **<I have to check here if user session is active or not?>** return render(request, template_name,context=context) else: return render(request,'' ,context=context) after user login I am creating session and storing in below 2 variables:- request.session['employee_name'] = employee.usrFirstName request.session['employee_id'] = employee.id -
Using Elasticsearch as Database with Django
I am trying to make website where I could display information from Elasticsearch index. What I do not understand how can I connect django to existing Elasticsearch index ? What I found is how to create new index with elasticsearch_dsl library, so I could create new one and populate it with all the data from old index. But it will take some time to transfer all the data. The main question is how can I retrieve information from old elasticsearch index? -
Django Channels - send data to socket at Shell command level
I want to send data to the Front-End socket outside of my class ChatConsumer. Here is my consumer.py. class ChatConsumer(AsyncConsumer): async def ws_connect(self, event): self.send = get_db_object() .... await self.send({ "type": "websocket.accept" }) # I need to CONSTANTLY receive & send data async def ws_receive(self, event): obj = ...# query DB and get the newest object json_obj = { 'field_1': obj.field_1, 'field_2': obj.field_2, } await self.send({ "type": "websocket.send", "text": json.dumps(json_obj) }) And my routing.py. from chat.consumers import ChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ # the documentation used url(), so just stick to this instead of re_path url(r"^messages/(?P<username>[\w.@+-]+)/$", ChatConsumer), ] ) ) ) }) As you can see, my ChatConsumer is called in my routing.py, and inside my ChatConsumer, I can send data to Front-End by using await self.send({...}). But what if I want to send data to my currently open Front-End using Shell Command? Assume that the port is already open by running manage.py runserver. And I want to feed data to the Front-End using Shell commands. How can I do this? How can I get the same connection that my ChatConsumer has at Shell level?