Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django abstract alphabet validator
I'm writing a field that takes an alphabet as an argument and generates a crypto-secure random string from that alphabet. The validator also takes a length argument. Here's the template for that: from django.core.validators import RegexValidator class AlphabetValidator(RegexValidator): def __init__(self, alphabet, max_length): pass As you can see, the idea is to use RegexValidator as a base class. The problem lies within the flexibility that is given to the alphabet, as it can incorporate everything. I'm only using it for validating either letters and digits or only hexadecimal representations, but I'd like to make it safe for other uses as well in advance. Also notice that any characters from the given alphabet should be taken literally, including $, ., and so on. What I have in mind is to wrap the alphabet in a class: "[" + alphabet "]". This, of course, implies that I need to escape - and ]. I'm not sure about [. My question is whether escaping these three characters would be enough? Are there others I should consider? Or whether the community has a better way to suggest to accomplish the same. -
How to give star rating for movie like IMDB in django application?
I am developing a web application for my college project in Django. I have 10 movie name display on my web page. I have finished the work of authentication. Now I want the user to rate the movie and give star out of 10 as the user does in IMDB. Please help me or give me hint how can I enable this feature in my application. -
Django and Angular on AWS Elastic Beanstalk
How would I use docker containers to have a Django backend and an Angular/React/Vue frontend on AWS elastic beanstalk? -
Odd ImportError During Testing in Bitbucket Pipelines
I'm running docker-compose in a pipelines step to run selenium tests. Everything is working fine but I get this error: Failure: ImportError (No module named 'app') ... ERROR dj01 | dj01 | ====================================================================== dj01 | ERROR: Failure: ImportError (No module named 'app') dj01 | ---------------------------------------------------------------------- dj01 | Traceback (most recent call last): dj01 | File "/usr/local/lib/python3.6/site-packages/nose/failure.py", line 39, in runTest dj01 | raise self.exc_val.with_traceback(self.tb) dj01 | File "/usr/local/lib/python3.6/site-packages/nose/loader.py", line 418, in loadTestsFromName dj01 | addr.filename, addr.module) dj01 | File "/usr/local/lib/python3.6/site-packages/nose/importer.py", line 47, in importFromPath dj01 | return self.importFromDir(dir_path, fqname) dj01 | File "/usr/local/lib/python3.6/site-packages/nose/importer.py", line 79, in importFromDir dj01 | fh, filename, desc = find_module(part, path) dj01 | File "/usr/local/lib/python3.6/imp.py", line 297, in find_module dj01 | raise ImportError(_ERR_MSG.format(name), name=name) dj01 | ImportError: No module named 'app' dj01 | dj01 | ---------------------------------------------------------------------- dj01 | XML: /app/test-results/nose/noseresults.xml dj01 | Name Stmts Miss Cover dj01 | ---------------------------------------------------------------------- dj01 | sasite/__init__.py 0 0 100% dj01 | sasite/admin.py 16 16 0% dj01 | sasite/migrations/0001_initial.py 6 0 100% dj01 | sasite/migrations/0002_casestudy_download_url.py 5 0 100% dj01 | sasite/migrations/__init__.py 0 0 100% dj01 | sasite/models.py 100 100 0% dj01 | sasite/settings/__init__.py 0 0 100% dj01 | sasite/settings/base.py 54 54 0% dj01 | ---------------------------------------------------------------------- dj01 | TOTAL 181 170 6% … -
Extend number of characters used by Django SessionStore from 32 to 64
Django==1.11.17, Python==3.6.7 I would like to extend the number of characters used for the session key. Looking in django.contrib.sessions.backends.base.py: class SessionBase(object): ... def _get_new_session_key(self): "Returns session key that isn't being used." while True: session_key = get_random_string(32, VALID_KEY_CHARS) if not self.exists(session_key): break return session_key ... I would like to modify 32 -> 64. I tried monkey-patching, in one of my files: import django.contrib.sessions.backends.base as sessions_base import django.contrib.sessions.backends.file as sessions_file from django.utils.crypto import get_random_string def _get_new_session_key(self): while True: session_key = get_random_string(64, sessions_base.VALID_KEY_CHARS) print("SESSION KEY: {}".format(session_key)) if not sessions_file.SessionStore.exists(self, session_key): break return session_key sessions_file.SessionStore._get_new_session_key = _get_new_session_key django.contrib.sessions.backends.file.py implements SessionStore, and exists(). This solution is just ignored by Django, and I get no print statement showing. Just fyi, this does print the session id (with 64 chars) but errors out: sessions_file.SessionStore._get_new_session_key = _get_new_session_key(sessions_file.SessionStore) File "/Users/.../lib/python3.6/site-packages/django/contrib/sessions/backends/file.py", line 51, in _key_to_file session_key = self._get_or_create_session_key() AttributeError: 'str' object has no attribute '_get_or_create_session_key' Questions: This does not work. Is it due to the fact that the SessionStore object is instantiated due to a middleware, before this file is accessed? Should my solution be a middleware? (I'd rather monkey-patch) NOTE: Also tried: 1. sessions_file.SessionStore.__dict__["_get_new_session_key"] = _get_new_session_key <-- error is raised 2. setattr(sessions_file.SessionStore, '_get_new_session_key', _get_new_session_key)` <-- same issue, ignored -
Pre-fill Django form field with individual elements of a list
I want to pre-fill a form field with all the individual elements of a list that I pass it: def edit_song(request, song_id): """Edit a song.""" song = Song.objects.get(id=song_id) if request.method != 'POST': # Initial request; pre-fill form with current song info. producers = [] for producer in song.producer.all(): producers.append(producer.name) data = {'artist':song.artist.name, 'producer':producers, 'label':song.label.name} form = AddSongForm(instance=song, initial=data) Right now it's filling the 'producer' field with the producers list, but I would like it to instead fill it with each individual string from that list. Can I do this in views.py? -
How can I delete the photo after proccesing it?
I have two fields in my django model: class Staff(models.Model): photo = models.FileField(blank=True, null = True) encodings = JSONField() I get the photo from form and after that using this photo get encodings. How can I delete the photo after proccesing it? I tried self.photo = None or self.photo = '' but in this case I get "The 'photo' attribute has no file associated with it" -
Selenium stopped working with Firefox, works with Safari
I've been using Selenium with Python 3 for a while. Yesterday it stopped working. I've tried uninstalling and reinstalling everything, but it hasn't worked. I enabled the driver for Safari, and that works, but I don't know what changed. I tried going to a different project that I haven't used in a while but functioned, thinking my code threw it off, but it doesn't work either. I know there are other posts out there similar to this, but they haven't been helpful and I wasn't sure if I should contact Mozilla/Selenium about this issue. Here are my details: Python 3.7.1 Django 2.1 Firefox 64 Selenium 3.141.0 Geckodriver 0.23.0 I am running these in a virtual environment. Any more questions, let me know. Really confused as to what broke. -
Django render elasticsearch results
im currently trying to display my search results of elastic-search onto my template but somehow i get the following error: Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P\d+)/$'] Request Method: GET {% block content %} <h1 class="center">Search results</h1> {% if object_list.count == 0 %} <div class="search_not_found"> <img src={% static "/gfx/sys/not_found.png" %}> <h2>Nothing found here ...</h2> </div> {% else %} {% for post in object_list %} <div class="post"> <h3><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h3> <p>{{ post.content|safe|slice:":800"|linebreaksbr}} {% if post.content|length > 300 %} <a href="{% url 'post_detail' pk=post.pk %}">... more</a> {% endif %}</p> <div class="date"> <a>Published by: <a style="font-weight: bold;" href="{% url 'profile' pk=user.pk %}" >{{ post.author }}</a></a><br> <a>Published at: {{ post.published_date }}</a><br> <a>Category: {{ post.category }}</a><br> <a>Tag(s): {{ post.tag }}</a> </div> </div> {% endfor %} {% endif %} {% endblock %} if i remove the following content from the template href="{% url 'post_detail' pk=post.pk %}" i get my results display or at least the titel, content and tag. other informations are missing and im also not able to access the actual post object. Seems that no id gets passed to the template this is how my elasticsearch view looks like: def globalsearch_elastic(request): keywords … -
How to check if a value is in a list in Django/Jinja
I'm iterating through a list of all users and trying to check if the current user is following them. The "in following" doesn't work. Where am I going wrong here? following = [<User: testaccount1>, <User: testaccount2>] all_users_list = <QuerySet [{'id': 1, 'username': ‘testaccount1’},{‘id': 2, 'username': ‘testaccount2’},{‘id': 3, 'username': ‘testaccount2’}] {% for follow_user in all_users_list %} {% if follow_user.username in following %} FOLLOWING {% else %} Not Following {% endfor %} -
Translating humanize text in Django
I have some issues while trying to translate in django (on the front end) So I have a Contact model that has a bunch of messages. Each message has a "contact_date" field which I convert using humanize on the front end. {{ message.contact_date | neutraltime }} I have these in my settings.py LANGUAGE_CODE = 'en-US' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I kind of managed to make it work, but it involved changing my project's language code to the other language and removing the LocaleMiddleware. Then what happened is that my admin area changed into that language and I want it in English. My goal is to leave everything in English and just convert the contact_date to the other language. Any help would be appreciated, thanks! -
How to a serialize model field that holds raw JSON?
Supposing I have a field in my model that stores raw JSON (so containing double quotes, null, false etc.): class Activity(models.Model): textjson = models.TextField(default="Unassigned") how do I serialize this model so that the API response will not contain backslashes, the sign of double serialization? -
Printing a list in a django template without a trailing comma
My django template was printing a list with the elements separated by comma, but the last item always had a comma as well. I was able to solve the problem in the template doing the following: <li>Producer: {% for producer in producer %} {% if not forloop.last %} {{ producer }}, {% else %} {{ producer }} {% endif %} {% endfor %} </li> But after reading some posts on here, I think it would be better to do it in the views.py file. I don't know how to do that and couldn't really understand the other posts on here. Here is the corresponding views file: def song(request, song_id): """Show a single song.""" song = Song.objects.get(id=song_id) date_added = song.date_added artist = song.artist url = song.url year = song.year genres = song.genre.all() country = song.country producer = song.producer.all() label = song.label source = song.source source_url = song.source_url comments = song.comments context = {'song': song, 'date_added': date_added, 'artist': artist, 'url': url, 'year': year, 'genres': genres, 'country': country, 'producer': producer, 'label': label, 'source': source, 'source_url': source_url, 'comments': comments} return render(request, 'great_songs_app/song.html', context) Is there a way to turn 'producer' into a dictionary and pass it to the template in a way that all … -
Is the Gzip Middleware vulnerable to BREACH?
From the Django official documentation I found this. Please explain me how to use GZIP compression safely in my application. GZIP Middleware Warning -
Django: how to capture values in request from form without POST method
I've succesfully created a token using a javascript library called Culqipy. They also have a python library for doing this, called Culqipy. And I would like to use it for creating the payment record. Problem: Their JS code renders a form without "POST" method. So I don't know how to capture it's values in request, and after that calling it's values like: token = request.POST['token'] If it had a POST method I could do something like: if request.method == 'POST': print ("StripToken:") print(request.POST) try: token = request.POST['stripeToken'] email = request.POST['stripeEmail'] print("This is the token: " + token) print("This is the user's email: " + email) customer = stripe.Customer.create( email = email, source = token ) charge = stripe.Charge.create( amount = stripe_total, currency = "pen", description = description, customer = customer.id, ) except stripe.error.CardError as e: return False, e JS that on click renders the form: <script> $('#buyButton').on('click', function (e) { // Abre el formulario con la configuración en Culqi.settings Culqi.open(); e.preventDefault(); }); </script> Form's HTML: <form class="form"> <div class="form-row"> <div class="col col-12"><div class="form-group"> <div class="input"> <input name="cardNumber" autocomplete="cc-number" type="tel" maxlength="19" class="input-card" data-mask="#### #### #### ####" data-previous-value=""> </div> <label for="cardNumber" class="">Número de Tarjeta</label> <div class="brand"></div></div></div></div> <div class="form-row"><div class="col col-6"> <div class="form-group"><div … -
The 'photo' attribute has no file associated with it?
I have three fields in my model: photo, name and encodings. I get photo and name from form and after proccesing this photo I get encodings. But when I try to edit name using Django admin page I get "The 'photo' attribute has no file associated with it" My model: class Staff(models.Model): photo = models.FileField(blank=True) encodings = JSONField() name = models.CharField() ... def save(self, *args, **kwargs): if self.photo is None: super(Staff, self).save(*args, **kwargs) else: self.encodings = self.get_encodings() self.photo = None super(Staff, self).save(*args, **kwargs) -
django-admin --version syntax error in windows command prompt
I have installed Django latest version i.e 2.1 on my pc and also updated my currently installed python version from 3.5.rc1 to 3.7.1. But still command 'Django-admin --version' giving error- Traceback (most recent call last): File "C:\Python34\lib\runpy.py", line 170, in _run_module_as_main "main", mod_spec) File "C:\Python34\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Python34\Scripts\django-admin.exe__main__.py", line 5, in File "C:\Python34\lib\site-packages\django\core\management__init__.py", from django.conf import settings File "C:\Python34\lib\site-packages\django\conf__init__.py", line 18, in from django.utils.functional import LazyObject, empty File "C:\Python34\lib\site-packages\django\utils\functional.py", line 12 return _curried_func(*args, *moreargs, **{**kwargs, **morekwargs}) -
how to open template with button click
I want to open another template like "booking" in following example by clicking. projectforms bookingform urls templates index.html projectforms urls bookingform.urls urlpatterns = [ path('' , views.purchasing_view, name="purchasing"), path('',views.add_model, name="booking"), path('' , views.payment_view, name="payment"), path('' , views.payment_view, name="payroll"), ] projectforms.urls from bookingform.views import add_model, purchasing_view,payment_view,payroll_view,index_view urlpatterns = [ path('admin/', admin.site.urls), path('', index_view), path('booking/',add_model), path('purchasing/', purchasing_view), path('payments/', payment_view), path('payroll/', payroll_view), ] How to call "booking" url with following button. <a class="btn">Booking</a> -
running javascript in a nested component-like django partial template
I would like to make a "component" (several actually, but let us start with one). That is I would like to have a template file, which itself may include javascript. Then I would like to be able to include that "component" in whatever (other) Django template file. Importantly: in the base.html I include utility javascript (like jquery or bootstrap or whatever) and I want those things to be in scope in the component's javascript. Here is a visual of one Django template: and when an item is clicked, it will update the other part of the page, allowing that template and its included JS to run with access to the rest of the page's javascript. Here is some coe to go along with it (i mistyped base to baste, so I went with the theme): models.py class CommonTask(models.Model): ## nothing special name = models.CharField(max_length=30, default='yummy') urls.py app_name = 'food' urlpatterns = [ ## the list view on the left url(r'^edible/?', views.EdibleList.as_view(), name='edible'), ## the partial on the right url(r'^billable/edit/(?P<jid>[a-zA-Z0-9-\w:]+)/?', views.EdibleEdit.as_view(), name='edibleEdit'), views.py class EdibleList(ListView): template_name = 'food/edible-list.html' def get_queryset(self): return Dish.objects.filter('edible'=True) class EdibleEdit(UpdateView): form_class = EdibleForm template_name = 'food/edible-edit.html' def get_initial(self): … # for the form/formset info def get_object(self): return … -
Python - Django - Heavy lifting in C++
Currently i have to deal with a architectural problem. My task is to solve some big image processing issues and somehow expose the evaluated data, e.g. as json. So what i thought of: Create a application which does the heavy lifting(image processing, c++) and return its evaluated data in json format Create a webapp(e.g. Django) which calls this c++ app and exposes the returned data in json as well. This webapp would kind of act as a gateway to the world(www). In the next step anybody could access the webapp and display the data according to rest api defined in the webapp. What do you think of it in general? Do you know better ways to solve this kind of problems? What are your preferred architectures? Thanks and Greetings! -
Django: passing a foreign key to an admin add form
I have a model that I want to maintain in my admin site only as a child of another model and not directly via its own changelist. It has too many fields to maintain sensibly in an inline, so I'm trying to add new instances via a link to the add form from the parent model's admin. So I have: ### models.py class A(models.Model): # class A's stuff class B(models.Model): fk_a = models.ForeignKey(A) # etc. ### admin.py class BInline(admin.TabularInline): model = AreaMeetingOfficeHeld show_change_link = True extra = 0 max_num = 0 # to suppress inline "add another" fields = (<SUBSET_OF_FIELDS>) # ... etc @admin.register(A) class AAdmin(admin.ModelAdmin): inlines = (BInline,) # ... etc ### templates/admin/myapp/a/change_form.html {% extends "admin/change_form.html" %} {% block object-tools %} {% if has_change_permission %} <a href="{% url 'admin:myapp_b_add'%}?fk_a_id={{original.pk}}"> </i>Add B </a> {% endif %} {% endblock %} ... so far so good. The link is correct, the add form for B is instantiated. As far as I can see from delving through stack traces and debug-by-print-statement it sees fk_a.id in its initial data. But then does nothing with it: the correct instance of A is neither displayed nor saved. What am I missing here? I assume I need … -
Twiiter, Webhooks, and Django CRC Check --> 'str' object has no attribute 'xframe_options_exempt'
I am using Django for my webapp and have adapted the tutorial @ https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/securing-webhooks to run in Python 3 however I am running into this problem in my views from django.shortcuts import render from django.http import HttpResponse, HttpRequest import base64, hashlib, hmac, json from django.views.decorators.csrf import csrf_exempt from django.views.decorators.clickjacking import xframe_options_exempt from django.views.decorators.http import require_GET @csrf_exempt @xframe_options_exempt def twitter_webhook(request): msg = request.GET.get('crc_token') msg_bytes = msg.encode() sha256_hash_digest = hmac.new(b'bEfpTIneaRBaVqHiev4S271m1F7mYX9Th9QhzjkCpLeF2Ga6HH', msg_bytes, digestmod=hashlib.sha256).digest() resp = 'sha256=' + str(sha256_hash_digest) twitter_response = { 'response_token': resp } return json.dumps(twitter_response) 'str' object has no attribute 'xframe_options_exempt' Using pycharm I have debugged step by step through my code and it all works fine returning the appropriate hash up until the point it gets caught by clickjacking middleware. Request Method: GET Request URL: http://127.0.0.1:8000/twitter?crc_token=1230983450923485 Django Version: 2.1.4 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'xframe_options_exempt' Exception Location: C:\Users\micha\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\decorators\clickjacking.py in wrapped_view, line 51 Python Executable: C:\Users\micha\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.1 Python Path: ['C:\\Users\\micha\\Documents\\Projects\\sinclaire_webhooks', 'C:\\Program Files\\JetBrains\\PyCharm 2018.3.1\\helpers\\pydev', 'C:\\Users\\micha\\Documents\\Projects\\sinclaire_webhooks', 'C:\\Program Files\\JetBrains\\PyCharm ' '2018.3.1\\helpers\\third_party\\thriftpy', 'C:\\Program Files\\JetBrains\\PyCharm 2018.3.1\\helpers\\pydev', 'C:\\Users\\micha\\.PyCharm2018.3\\system\\cythonExtensions', 'C:\\Users\\micha\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\micha\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\micha\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\micha\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\micha\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site- packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2018.3.1\\helpers\\pycharm_matplotlib_backend'] Server time: Sun, 16 Dec 2018 17:58:20 +0000 I have searched and can not find anything definitive to lead me towards a … -
Django created_at__gt=self.request.user.last_login workinly only on users already signed in.
Intro: I have a 3 models user, post, group. User is able to make posts however each post has to belong to a group. Users have to choose from the existing groups for their posts. Users cannot add, delete, update group's. Furthermore: Users can become a member of groups and when they click on a certain group. They see all the posts in that group. What I want When Users come on the home page they see posts that were added since the last time they logged in My Models class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() created_at = models.DateTimeField(auto_now=True) My Views class Homepage(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(Homepage, self).get_context_data(**kwargs) if self.request.user.is_authenticated(): context['object_list'] = Group.objects.filter(members=self.request.user) #What am I doing wrong in the below code new_posts = Post.objects.filter(created_at__gt=self.request.user.last_login).count() context['new_posts'] = new_posts else: context['object_list'] = Group.objects.all() return context In my templates I have <div class="list-group"> {% for group in object_list %} {% if not new_posts %} {{group.post.count}} {% else %} {{new_posts}} {% endif %} {% endfor %} </div> The Issue: Only the users who are already signed in and refresh their page see the new posts example:4 new, … -
Django model configuration for dynamic attributes
I have been trying to figure out the best way (or correct) way to set up models for our PIM/PriceModel app in Django. Example models (stripped): class ProductItem(models.Model): """ An actual item/product, what it all revolves around. """ part_number = models.CharField(unique=True, max_length=50, help_text='') internal_part_number = models.CharField(primary_key=True, max_length=50, help_text='') # prefilled by partnumber type = models.ForeignKey('Type', null=True, on_delete=models.SET_NULL) attributes = HStoreField(db_index=True) # and more .... class Type(models.Model): """ Product type i.e. camera-dome, camera-bullet, pir, etc. """ pass class Segment(models.Model): """ A segment of the company like Industry, Retail, Guarding etc. """ pass class ProductCategory(models.Model): """ Supposedly a child category of TopCategory. """ pass class InstallPrice(models.Model): """ Product item installation prices based on Type, Product Category and Segment. """ install_price = models.DecimalField(max_digits=8, decimal_places=2, help_text='') type = models.ForeignKey('Type', null=True, on_delete=models.SET_NULL) product_category = models.ForeignKey('ProductCategory', null=True, on_delete=models.SET_NULL) segment = models.ForeignKey('Segment', null=True, on_delete=models.SET_NULL) Take a look at "attributes = HStoreField(db_index=True)" in the ProductItem model. The main thing i need to store in a product item is attributes like how many inputs/outputs/connection-options does it have. I need to store this for testing products against each other further down the line in the price-model app. This to make sure you have the right amount of products with matching … -
How to send signal from Oracle to Python-django
How can I send signal or execute python script if new record inserted in Oracle DB?Is it possible without triggers? How about Django signals function?