Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        In Django Bootstrap 4, how to avoid rendering an alert with form errors?I'm using django-bootstrap4 (https://django-bootstrap4.readthedocs.io/en/latest/) in a project and find that when there are errors in a form, an alert box shows up with a list of the errors. In my case, this is problematic because the errors are repeated: I've had a look at the FormRenderer source code, and I don't see a way I can opt out of displaying this 'alert of errors': class FormRenderer(BaseRenderer): """ Default form renderer """ def __init__(self, form, *args, **kwargs): if not isinstance(form, BaseForm): raise BootstrapError( 'Parameter "form" should contain a valid Django Form.') self.form = form super(FormRenderer, self).__init__(*args, **kwargs) self.error_css_class = kwargs.get('error_css_class', None) self.required_css_class = kwargs.get('required_css_class', None) self.bound_css_class = kwargs.get('bound_css_class', None) def render_fields(self): rendered_fields = [] for field in self.form: rendered_fields.append(render_field( field, layout=self.layout, form_group_class=self.form_group_class, field_class=self.field_class, label_class=self.label_class, show_label=self.show_label, show_help=self.show_help, exclude=self.exclude, set_placeholder=self.set_placeholder, size=self.size, horizontal_label_class=self.horizontal_label_class, horizontal_field_class=self.horizontal_field_class, error_css_class=self.error_css_class, required_css_class=self.required_css_class, bound_css_class=self.bound_css_class, )) return '\n'.join(rendered_fields) def get_fields_errors(self): form_errors = [] for field in self.form: if not field.is_hidden and field.errors: form_errors += field.errors return form_errors def render_errors(self, type='all'): form_errors = None if type == 'all': form_errors = self.get_fields_errors() + self.form.non_field_errors() elif type == 'fields': form_errors = self.get_fields_errors() elif type == 'non_fields': form_errors = self.form.non_field_errors() if form_errors: return render_template_file( 'bootstrap4/form_errors.html', context={ 'errors': form_errors, 'form': self.form, 'layout': self.layout, 'type': type, } ) …
- 
        Django, JSON serialize queryset and list of models has different behaviorI have a Django model with a function (on the Python class) that modifies some of its fields. I can do this, and it works from django.core.serializers.json import DjangoJSONEncoder json.dumps(list(MyModel.objects.filter(...).values()), cls=DjangoJSONEncoder) Now I'd like to call the function MyModel.MyFunction on all the models before JSON encoding them. I've tried this, but obviously it returns the fields as they are in the database, not modified by MyFunction: from django.core.serializers.json import DjangoJSONEncoder mymodels = MyModel.objects.filter(...) for mymodel in mymodels: mymodel.MyFunction() # or mymodel.myfield = somethingelse json.dumps(list(mymodels.values()), cls=DjangoJSONEncoder) So I've tried this from django.core.serializers.json import DjangoJSONEncoder mymodels = MyModel.objects.filter(...) _mymodels = [] for mymodel in mymodels: mymodel.MyFunction() # or mymodel.myfield = somethingelse _mymodels.append(mymodel) json.dumps(_mymodels, cls=DjangoJSONEncoder) but TypeError: Object of type MyModel is not JSON serializable. I've read on other answers that you'd have to either install django rest framework or implement a to_json function on MyModel. However, I'd like not to clutter my application to achieve a behavior that is already available. How can I tell django to behave the same way on an array of models that it behaves on a queryset of the same model?
- 
        Should I build my tuition website in Phoenix/ElixirFor background, I want to build a tuition site which can help tutors: Be found by students/parents and arrange lessons with said clients Organise their timetables with these students Teach online create my own plugins for the site (e.g. like a homework generator or something like that) Why Phoenix? From my research, even though it's new, it's very good at concurrency and hence should be very scalable if I manage to get a lot of tutors. It's also particularly fast which really sold me too. However, I've just come out of university with a BSci in Comp sci so it's my first proper deployable project. It's a really really enjoyable project (Functional languages are amazing) but I don't want my zeal to give me tunnel vision. I should also say, this is my own personal project that I want to build really to help students that I tutor. It is very fun learning phoenix, but I notice it's quite difficult to troubleshoot as it's not exactly the most popular framework. Stuff like ruby has a lot more tutorials and things like that. Nonetheless, from my surface-level research, phoenix feels perfect with its speed benchmarks. I'm a pretty capable programmer too. …
- 
        Pagination in Django with two Querysets formatted in different waysI want to get pagination to work with two separate query sets that are formatted in different ways. The first query set is smaller and will never be longer than the first page. The second query set is very long and will go on for 5 or 6 pages. The result content of both query sets are the same, but I format them in different ways in the html template. The models are exactly the same, Book and PremiumBook, except PremiumBook has lots more books (and contains all the elements in Book). I'll include the views.py and then the template: def servicesListView(request, category): model = Books table = Books.objects.filter(category=category) values_books = table.filter().values_list("serviceid") # remove these observations from next table. My next table is premium and not available to non-authenticated users new_table = PremiumBooks.objects.filter(category=category).exclude(bookid__in=values_books) new_table = new_table.filter().annotate(price_count=Count('premiumcost__price')).order_by('-price_count')[:60] page = request.GET.get('page', 1) paginator = Paginator(new_table, 5) try: new_table = paginator.page(new_table) except PageNotAnInteger: new_table = paginator.page(1) except EmptyPage: new_table = paginator.page(paginator.num_pages) return render(request, 'services/index.html', {'table': table, 'new_table': new_table}) Then, this is the template for the them: <main class="ui-book-list"> <div class="results-list grid-view"> <div class="container"> <h2>Book list </h2> <div class="grid-results-list book-list"> {% for book in table %} <div class="record"> <div class="content"> <h6> {{ book.easy_desc }} …
- 
        Views in Django: Sending array with dictionariesI am looking for a smart solution on how to provide data to my template in django. Given is a array, filled with dictionaries. in the file "views" i have: from .pymodules import url_scraper as spider from .pymodules import url_list def result(request): top10 = spider(url_list) #array filled with dicts return render(request, "result.html", {"top10" : top10} ## example for top10 --> [{"key1" : "value_A"},{"key1" : "value_B"},{"key1" : "value_C"}] Now i have the problem, that everything I try does not give me the "key" : "value" output i want. Trying for something like this: {% x in top10 %} {x[key]} ## key is given {% endfor %}
- 
        Retrieve Data to Populate Table in DjangoI have one view which renders a dropdown where a user will select an order number and direct them to another view where there should be a table which populates with all data related to that order #. Each order # has multiple records associated to it - I'm not sure how to properly get this data and display it. This is what I'm trying - but I just keep getting errors, and I have a feeling I'm not approaching this right in the first place. views.py #rendering the dropdown def manifest_reference_view(request): query_results = Orders.objects.all() reference_list = BlahBlah() context = { 'query_results': query_results, 'reference_list': reference_list, } return render(request, 'manifest_reference_view.html', context) #this view should show table with all data relating to user selection def manifest(request): if request.method == 'POST': reference = request.POST.get('Reference_Nos') referenceid = reference form = CreateManifestForm(request.POST, instance=referenceid) manifest = Manifests.objects.all().filter(reference__reference=referenceid) #order = Orders.objects.get(reference=reference) if form.is_valid(): form.save() return redirect('display_orders') else: form = CreateManifestForm(instance=referenceid) return render(request, 'edit_manifest_frombrowse.html', {'form': form}) forms.py class BlahBlah(forms.Form): Reference_Nos = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(), empty_label=None) class CreateManifestForm(forms.ModelForm): class Meta: cases = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter Cases'})) model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') edit_manifest_frombrowse.html {% extends 'base.html' %} {% block body %} <div class="container"> <form id="create_mani_form" method="POST"> …
- 
        How to set CELERY_TASK_QUEUES so that django-celery-beat uses "default" queue?In my django admin interface, it shows this under the Periodic Tasks table from django-celery-beat I need my beat tasks to use the queue: 'default', which is doesn't by default. I can't find any reference to CELERY_TASK_QUEUES in any documentation. How do I set the default queue to 'default' for django-celery-beat periodic tasks?
- 
        how to pass parameters from views django to the templatewhat is the error in my code because i have been trying to pass the variable for several hours without any success. Yet i know that i can send it as dictionary. so i am using a form that will allow user to enter the folder number and then it will be send it to the views using ajax call to get the request and store it in the database then it render the dropDown.html and display the folder number using Django Tags and it print the value correctly in the cmd. all the process is done but concerning the display in the template , it display nothing. create_folder.html <form> <!-- problem in formInput vs radioBtn --> <div id='left-column-Input'> <!-- <div class="formInput" id="fileIDfield"> <input type="text" id="fileID" value = "{{dbfolder.id}}" name="fileID" autocomplete="off" required /> </div> --> <div class="formInput" id="fileNum"> <input type="number" id="fileNumField" name="fileNum" autocomplete="off" required /> <label for="fileNum" class="label-name"> <span class="content-name" name="fileNum">folder number</span> </label> </div> <div class="home-Button" id="linkFormDiv"> <button id="linkForm" name="formSave" type="submit">Link</button> </div> </form> <script type="text/javascript"> $(document).ready(function(){ $("#save").on('click',function(event){ event.preventDefault() // MalafID = $('#fileIDfield').val() MalafNum = $('#fileNumField').val() $.ajax({ url: '/folder/', method: 'POST', data:{ FolderNum: MalafNum, } headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(){ // alert('done redirecting to Person Module') alert('Folder saved') // this line will …
- 
        DRF - Add get_FIELD_display fields (AssertionError)I want to modify a serializer such that it contains FIELD_display field for every field which has any choices, the value is get_FIELD_display. I'm trying to dynamically add those fields inside __init__ method but it returns error: The field 'subcategory_display' was declared on serializer ApiRealestateSerializer, but has not been included in the 'fields' option. serializer class ApiRealestateSerializer(serializers.ModelSerializer): subcategory_display = serializers.CharField(source='get_subcategory_display') class Meta: model = RealEstate fields = [x.name for x in RealEstate._meta.fields] def __init__(self, instance=None, data=None, **kwargs): super().__init__(instance, data, **kwargs) self.set_display_fields() def set_display_fields(self): """adds FIELD_display field for every CharField (eg. name = "peter", name_display = "Peter" )""" for field in RealEstate._meta.fields: if field.choices: fieldname = f"{field.name}_display" self.fields[fieldname] = serializers.CharField(source=f'get_{field.name}_display') self.Meta.fields.append(fieldname) Do you know how to make it work?
- 
        Cross validation in Django Admin between Parent and Child inline modelsI have a Post model, which can contain either images or links to videos, or both. The requirement is that every Post must have at least one image or one link to video. My current problem is I don't know where to place the correct validation to make. I tried to override the functions add_view and change_view in PostAdmin but could not make it work. I also tried to make some validations in ImagenPostAdminFormSet and VideoLinkPostAdminFormSet, but were useless as either of them can be empty, but not both. Following is my code for the models: class Post(models.Model): .... nombre_post = models.CharField('Nombre del Posteo', max_length=255) descripcion = models.CharField('Descripción', max_length=255) .... class ImagenPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="imagen_post") imagen_post = ContentTypeRestrictedFileField('Imagen del Posteo', upload_to=media_posteos, help_text='Formatos válidos: jpg, jpeg, gif, png') ... class VideoLinkPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="video_link_post") video_link = EmbedVideoField('Link de Video', max_length=150, help_text='Ingresar Link de Video') ... Following the code for Admin: class ImagenPostAdminInline(admin.StackedInline): model = ImagenPost form = ImagenPostAdminForm formset = ImagenPostAdminFormSet extra = 1 class VideoLinkPostAdminInline(admin.StackedInline): model = VideoLinkPost form = VideoLinkPostAdminForm formset = VideoLinkPostAdminFormSet extra = 1 class PostAdmin(admin.ModelAdmin): form = PostAdminForm inlines = [ImagenPostAdminInline, VideoLinkPostAdminInline] As I said, the validation to make is that one …
- 
        How to interpret an SQL Query to Django QuerysetWhat is the best way to read and interpret a raw SQL query and convert it to Django QuerySet, Im having trouble to understand with the alias and the join For example: select sum(balance_amount) balance_amount from account_balance a join public.account_catalog b on a.account_id=b.id where b.account_type in accounts and a.balance_date in date and bank_id in bank
- 
        Issues with HyperlinkedModelSerializer with recursive modelOverview I'm setting up a new Django application with Django REST Framework (DRF), and this is my first time using the HyperlinkedModelSerializer for the API endpoint. I've overridden the get_queryset() method on the ModelViewSet, so I've also the basename argument to the application router and explicitly defined the url attribute in the serializer as suggested here. This fixed issues that I was having with the model's own url attribute. However, I'm getting the following error message when trying to serialize a ForeignKey field of the same class as the parent model. It fails with the following message: Could not resolve URL for hyperlinked relationship using view name "employee-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Is there something special in the serializer I need to do to support using recursive model relationships like this? Example code # app/models.py from django.db import models class AbstractBase(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Employee(AbstractBase): name = models.CharField(max_length=254) manager = models.ForeignKey('self', related_name='direct_reports', on_delete=models.SET_NULL, blank=True, null=True) ... def __str__(self): return str(self.name) # app/views.py from rest_framework import viewsets from rest_framework.pagination import PageNumberPagination from app import models …
- 
        Why doesn't Django have a simpler way to style form fields?I've looked at a lot of different methods on how to style form fields and all of them seem to be pretty unideal. Especially when you're trying to use bootstrap. I've done it a few different ways and I'm just surprised there isn't a better method than any of these. Ex: Within the form file alias = forms.CharField(max_length=15, widget=forms.TextInput(attrs={'placeholder': 'Username'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['alias'].widget.attrs.update({'class': 'special'}) Ex: Doing it manually in the template as Django mentions (which I would rather not have to resort to doing) Ex: with the django-widget-tweaks package (got errors saying incorrect inputs when they definitely were correct) Is there another method or any instructions someone can point me to for what has worked well for them? Thanks.
- 
        Python 2.7 and 3.7.2 compatible django-redis serializerI'm trying to write a py2.7 - py3.7 compatible django-redis serializer. I'm using django-redis==4.8.0 with django==1.11.22 and the PickleSerializer. I saw this issue https://github.com/niwinz/django-redis/pull/279 on django-redis and wrote a serializer similar to what's said in the thread. However my object seems a little bit more complex? Not sure. My goal is to have 2 applications running at the same time, one with py2.7 and the other with py3.7. They have to be 100% compatible, and I'm not being able to get past this. Here is the code for the serializer: # -*- coding: utf-8 -*- import six from django.utils.encoding import force_bytes from django_redis.serializers.pickle import PickleSerializer try: import cPickle as pickle except ImportError: import pickle class CompatPickleSerializer(PickleSerializer): def loads(self, value): if six.PY3: return self._loads_py3(value) return super(CompatPickleSerializer, self).loads(force_bytes(value)) def _loads_py3(self, value): return pickle.loads( force_bytes(value), fix_imports=True, encoding='bytes' ) Example of object I'm trying to serialize: { 'created_at': datetime.datetime(2019, 7, 30, 20, 0, 29, 244916, tzinfo = < UTC > ), 'items': [{ 'unit_price': Decimal('3.00'), 'name': 'my item', 'id': '12312312', }] 'id': 'b5c6210d-561f-4e4e-a025-e55b39d95418', 'name': 'cart', 'customer': None, } The object is a lot bigger then that, but I assume that if I can do the flow with this object, I can do with a …
- 
        Keep user session logged in when page refreshed in vue jsI'm create user login page in vue js and consuming data from django with axios. I have utilized jwt to create token session in client-side The problem is the session is not saved when the page is refreshed. I have frustated because it. This is my source code : In '../src/store/modules/auth.js' import Vue from 'vue' import Axios from 'axios' import 'es6-promise/auto' // In order that Axios work nice with Django CSRF Axios.defaults.xsrfCookieName = 'csrftoken' Axios.defaults.xsrfHeaderName = 'X-CSRFToken' const state = { authUser: {}, users: [], isAuthenticated: false, jwt: localStorage.getItem('token'), endpoints: { obtainJWT: 'http://127.0.0.1:8000/api/auth/obtain_token/', refreshJWT: 'http://127.0.0.1:8000/api/auth/refresh_token/', baseUrl: 'http://127.0.0.1:8000/api/auth/', register: 'http://127.0.0.1:8000/signup/' } } const mutations = { setAuthUser: (state, { authUser, isAuthenticated }) => { Vue.set(state, 'authUser', authUser) Vue.set(state, 'isAuthenticated', isAuthenticated) }, updateToken: (state, newToken) => { localStorage.setItem('token', newToken); state.jwt = newToken; }, removeToken: (state) => { localStorage.removeItem('token'); state.jwt = null; }, } const actions = { refreshToken(){ const payload = { token: this.state.jwt } Axios.post(state.endpoints.refreshJWT, payload) .then((response)=>{ this.commit('updateToken', response.data.token) }) .catch((error)=>{ console.log(error) }) } } export default { state, mutations, actions, } In '../src/store/index.js' import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' import auth from './modules/auth' Vue.use(Vuex) // Make Axios play nice with Django CSRF axios.defaults.xsrfCookieName = …
- 
        Apache with Gunicorn proxy not serving /static Django filesAs the title says, I'm having difficulty getting Apache setup correctly to serve Django static files in production with a Gunicorn proxy for the backend. I'm finding that when I switch DEBUG = False that the app quits working with: < unexpected token. Reading about it, it has to do with the use of STATIC_ROOT being incorrect. I have my STATIC_ROOT = os.path.join(BASE_DIR, 'static'), and I'm running python manage.py collectstatic which is collecting all the assets to /static in the project root. Then I run gunicorn wsgi -D in the same directory as wsgi.py. Anyway, this is how the Apache configs are setup: HTTP: ServerName www.website.com ServerAlias website.com ### Redirect http to https RewriteEngine On # This will enable the Rewrite capabilities RewriteCond %{HTTPS} !=on # This checks to make sure the connection is not already HTTPS RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] # This rule will redirect users from their original location, to the same location but using HTTPS. # i.e. http://www.example.com/foo/ to https://www.example.com/foo/ # The leading slash is made optional so that this will work either in httpd.conf # or .htaccess context HTTPS: ServerName www.website.com ServerAlias website.com Alias /static /home/website/src/static ProxyPreserveHost On ProxyPass /static http://localhost:8000/static/ ProxyPass / http://localhost:8000/ retry=5 ProxyPassReverse …
- 
        Django model not saving for some reason (after second run of function)I am making a game. For users to be able to move, they need to solve math problems. Up/down/left/right each have problems. At the beginning of the game, 4 math problems are generated. Here is the code for it: def generate_first_4_problems(level, operation, game_object, player_type): creator_problems = ['p1up', 'p1right', 'p1down', 'p1left'] opponent_problems = ['p2up', 'p2right', 'p2down', 'p2left'] problems = [] answers = [] while len(problems) < 4: problem = generate_problem(level, operation) answer = x(problem).expr() if answer not in answers: problems.append(problem) answers.append(answer) print('problems') print(problems) if player_type == 'creator': for i, d in enumerate(creator_problems): setattr(game_object, d, problems[i]) print('creator_problem %s' % d) print(getattr(game_object, d)) game_object.save() elif player_type == 'opponent': for i, d in enumerate(opponent_problems): setattr(game_object, d, problems[i]) print('opponent_problem %s' % d) print(getattr(game_object, d)) game_object.save() game_object.save() print('after save') print(game_object.p1up) return problems This code is run twice for each player (creator and opponent) also, here is what is printed: problems ['7 + 3', '1 + 4', '10 + 9', '8 - 10'] creator_problem p1up 7 + 3 creator_problem p1right 1 + 4 creator_problem p1down 10 + 9 creator_problem p1left 8 - 10 after save 7 + 3 {'problem_list': ['7 + 3', '1 + 4', '10 + 9', '8 - 10']} problems ['2 + 6', '2 + …
- 
        Django Rest Framework: Nested Serializer lookup based on ForeignKey object?I have a single CustomUser model which is shared by different type of profiles. One particular profile model allows users to have multiple Photos. class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) ... other fields class Photo(models.Model): uuid = ShortUUIDField(unique=True, editable=False) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) image = models.ImageField(blank=False, null=False) My API endpoint retrieves the profile model via the CustomUser id, this is easy to do. models.Profile.objects.filter(user=user) What confuses me is how to reference the CustomUser model for the nested Photo serializer to retrieve all the user photos. All the examples I've managed to lookup use a field from the parent model as lookup but I need to use a child model field as lookup here. Here's what I've tried so far: class PhotoSerializer(serializers.ModelSerializer): class Meta: model = models.Photo fields = "__all__" class ProfileSerializer(serializers.ModelSerializer): photos = PhotoSerializer(many=True,read_only=True) class Meta: model = models.Profile fields = "__all__" Thanks!
- 
        How to convert an uploaded file (InMemoryUploadedFile) from pdf to jpeg in Django using wand?I'm trying to convert a pdf file uploaded in Django to a jpg file. I would like to use the file directly in the InMemoryUploadedFile state. I tried to use wand but without any success. Here is the code I wrote: from django.shortcuts import render from wand.image import Image as wi # Create your views here. def readPDF(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] if uploaded_file.content_type == 'application/pdf': pdf = wi(filename=uploaded_file.name, resolution=300) pdfImage = pdf.convert("jpeg") return render(request, 'readPDF.html', {"pdf": pdfImage}) I tried different things like using uploaded_file.file or uploaded_file.name as the first argument for the wand image but without any success.` I thank you in advance for your help!
- 
        favicon.ico not loading with DjangoI'm trying to make a simple web server with Django in Python3. I'm having trouble getting favicon.ico to load properly. When I attempt view the root web page I see the following on my terminal... [30/Jul/2019 19:49:22] "GET /catalog/ HTTP/1.1" 200 583 [30/Jul/2019 19:49:22] "GET /static/jquery-3.4.1.min.js HTTP/1.1" 304 0 [30/Jul/2019 19:49:22] "GET /static/my_typeahead.js HTTP/1.1" 304 0 [30/Jul/2019 19:49:22] "GET /static/bootstrap.min.css HTTP/1.1" 200 106006 [30/Jul/2019 19:49:22] "GET /static/bootstrap.min.js HTTP/1.1" 304 0 Not Found: /favicon.ico [30/Jul/2019 19:49:22] "GET /favicon.ico HTTP/1.1" 404 2313 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 55932) Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- Here is my project file structure... . ├── catalog │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ …
- 
        How to Select Audio Element by ID when ID is dynamically generated by DjangoI have a django app which is generating multiple audio elements (for loop) on a page based on a model. The id of each audio element is generated by the pk of the corresponding object. {{ beat.pk }} I am using jquery to style an audio player, and when I click play on one, all of the audio players play. I've tried to select in jquery by ID using $('#{{ beat.pk }}') but that doesn't work. Here is the code that generates the audio players: {% for beat in beats %} <div class="col-md-4"> <div class="card mb-2 h-100"> <img class="card-img-top" src="{% static beat.coverArt %}" alt="cover art for exclusive trap beats for sale"> <div class="card-body"> <h5 class="card-title">{{ beat.title }}</h5> <p class="card-text">{{ beat.description }}</p> <!-- AUDIO SOURCE HERE--> <audio id="{{ beat.pk }}"> <source src="{% static beat.mp3preview %}" type="audio/wav"> </audio> <!-- START CUSTOM AUDIO PLAYER DIV--> <div class="player"> <div class="btns"> <div class="iconfont play-pause icon-play"></div> </div><!-- END BUTTONS DIV --> <div class="progress"> </div> </div> <!--END CUSTOM AUDIO PLAYER DIV --> <a href="{% url 'beat_detail' beat.pk %}" class="btn btn-primary"> Purchase Exclusive Rights </a> </div> </div> </div> {% endfor %} </div> Here is the javascript: $( function(){ var aud = $('audio')[0]; $('.play-pause').on('click', function(){ if (aud.paused) { aud.play(); …
- 
        intl-tel-input how can i set a relative path to the images ? django-intl-tel-input not working?when I tried using Django-intl-tel-input it didn't work so how can I set a relative path to the images as in the documentation in this question I showed my template and my terminal log 3.Override the path to flags.png in your CSS .iti__flag {background-image: url("path/to/flags.png");} @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { .iti__flag {background-image: url("path/to/flags@2x.png");} } can I use Django's/python's template tags like {static 'images/flags@2x.png' } or should I just use the images inside the CSS file directory? so how can I set this with Django so I don't need to change the path when I deploy the project on a server?
- 
        Users are not automatically logged in to social-auth-app-djangoI configured user authorization via GoogleOauth2.0 (social-auth-app-django). Entries in the social_django / usersocialauth / application are created. Also created user profiles in accounts / user /. But for some reason there is no automatic login. What could be the reason? As I understand it, this is due to the fact that the user has is_active = False (I redefined BaseUser). Is it possible to somehow intercept user authorithation through social_django to set their status as is_active = True. Only signals come to mind. settings.py MIDDLEWARE_CLASSES = ( 'django.contrib.auth.middleware.AuthenticationMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ) TEMPLATES = [ { 'OPTIONS': { 'context_processors': [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) INSTALLED_APPS = ( #... 'social_django', ) AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '***********' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '****' LOGIN_REDIRECT_URL = '/kredity/' urls url(r'^accounts/', include('django.contrib.auth.urls')), url('', include('social_django.urls', namespace='social')), html <a href="{% url 'social:begin' 'google-oauth2' %}">Google+</a>
- 
        Single quote inside double quote is messing up javascript codeI'm building a Django web app and I'm trying to send a JSON object to my javascript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "test4 - don't delete"] return json.dumps(autocomplete_list) <!-- html page --> <script> // Things i've tried autocomplete = {{ autocomplete_list|safe }}; autocomplete = '{{ autocomplete_list|safe }}'; autocomplete = JSON.parse('{{ autocomplete_list|safe }}'); </script> If I wrap {{ autocomplete_list|safe } in single quotes like '{{ autocomplete_list|safe }}', then the single quote in test4 - don't delete messes up the variable and Uncaught SyntaxError: Unexpected identifier. However, if I leave it as {{ autocomplete_list|safe }}, then the HTML text highlights it as an error with red underlines. What am I doing wrong here?
- 
        How to deserialize MySql timestamp field in DjangoI have MySQL database with a column called 'created' and its type is TIMESTAMP. In my Djano serializers.py if I do the following: created = serializers.DateTimeField() an exception is thrown: 'datetime.date' object has no attribute 'utcoffset' How can I resolve it?