Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have Google Places Autocomplete work with AMP?
I'm trying to convert this homepage to AMP: excurj.com. Is there a way to keep the Autocomplete feature on the hero search field ? I saw this question. However, I need these two scripts to make autocomplete work: <script src="{% static 'js/autocomplete.js' %}"></script> <script src="https://maps.googleapis.com/maps/api/js?key=*****&callback=initMap&libraries=places"></script> This is what's inside autocomplete.js: // script to auto complete location function initMap() { var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(-90, 91), new google.maps.LatLng(-180, 80)); var options = { types: ['(cities)'], bounds: defaultBounds }; var input = document.getElementById('google_city_search'); var autocomplete = new google.maps.places.Autocomplete(input, options); } -
Django Form validation without a form.py
Is it possible to do form validation on a field that is created by html only? In example: <select class="form-control my_boolean" id="required_courseid" name = "required_course" > <option value = ""> Is this a required course? </option> <option value = "0"> No </option> <option value = "1"> Yes </option> </select> Before hitting the submit button I want to display an error if the user hasn't selected this option. Similiar to the .clean function i've read about. I do have a form created in the html as <form action = "{% url 'result' %}" form method = "POST"> I'm not using a class for the form in form.py since it's all done in the html. Did I go about this the wrong way, please offer suggestions. -
Share models between multiple apps and multiple database without code duplication (django)
I'm currently developing a web app in Django. My app is dealing with vegetables and gardens. A garden can have its own vegetables, but I would like it to be able to import vegetables from a common library/encyclopedia. Diagram of the models in the main app and in the library A first idea was to have a garden_id for all vegetables and set it to 0 or None for vegetables of the library but then the library isn't really reusable and is tightly coupled to the main app. A second idea was that vegetables linked to garden inherit from vegetables from library, but inheritance tends to be tricky with Django. A last idea that I use for the moment, is to create a second django app for the vegetable library and duplicate the vegetable model (in the main and the library app). I plan to implement an "import" module, that would convert vegetables from the library to vegetables linked to a garden. I also have two databases, one for the main app and one containing the common vegetables ( Can i use different databases for different apps in django ) Duplication is never a good idea, but I can't find … -
django url with or condition
I have an app in django - 1.11. When changing the language in the template, the address appears: localhost:8000/en/events/None/None/None Below solution is OK. My question is it possible to join these 4 regexes with one regex? For example, add something like or into regex? My dirty solution with few url regex: url(r'^$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P<filter1>[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P<filter1>[a-zA-Z0-9-]+))?(?:/(?P<filter2>[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P<filter1>[a-zA-Z0-9-]+))?(?:/(?P<filter2>[a-zA-Z0-9-]+))?(?:/(?P<filter3>[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), -
django file not found error: when javacript file inside static directory trying to access another file in the static directory?
I am doing one django project. And I am able to access the "custom.js" file from static folder path.This is a line inside my "index.html" file. <script type="text/javascript" src="{% static 'crypto_app/js/custom.js' %}" ></script> But inside "custom.js" file it is using this : $(window).ready(function() { 'use strict'; $.vegas('slideshow', { backgrounds:[ { src: 'images/bg-slider/bg-1.jpg', fade:1000 }, { src:'images/bg-slider/bg-2.jpg', fade:1000 }, { src:'images/bg-slider/bg-3.jpg', fade:1000 } })(); And hence, due to wrong file address, I am not able to access the images. And it is showing file not found. Is there some django way to declare path of images as variable and accessing it from the "custom.js" file? Given below is my directory structure : | admin.py | apps.py | models.py | tests.py | tree.txt | urls.py | views.py | +---migrations | | __init__.py| +---static | \---crypto_app | +---css | | | +---fonts | +---images | | \---bg-slider | | bg-1.jpg | | bg-2.jpg | | bg-3.jpg | | | \---js | custom.js +---templates | \---crypto_app | index.html -
Insert new section into Django Admin UserChangeForm
I am adding a section to the end of UserChangeForm using this code. from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from apps.auth_app.models import UserProfile class ProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'Profile' class ProfileAdmin(UserAdmin): inlines = [ ProfileInline, ] admin.site.unregister(User) admin.site.register(User, ProfileAdmin) I would rather insert that section of code after "Personal info", but have been unable to find a way to do this with just the fieldset. I have found examples like this, but is there a way to do this without having to subclass all of the Django Admin User Form? class UserAdmin(auth_admin.UserAdmin): fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ('<<Custom Fields>>', {'fields': (<<Field Names>>)}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) ... form = UserChangeForm -
jquery hidden div remove field required
How to remove required in hidden fields. It must remain required in visible field.When one of the options is selected, the required field needs to be removed. This form created django framework. For example, when "tuzel" is selected, the required field needs to be removed from the adi field. Jquery Code <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ var optionValue = $(this).attr("value"); if(optionValue){ $(".col").not("." + optionValue).hide(); $("." + optionValue).show(); } else{ $(".col").hide(); } }); }).change(); }); </script> <select name="secenek" class="form-control select2" required id="id_secenek"> <option value="" selected>---------</option> <option value="tuzel">Tüzel</option> <option value="gercek">Gerçek</option> </select> <div class="tuzel col col-lg-6"> <div id="fnWrapper" class=" parsley-input"> <label class="form-control-label">Firma Ünvanı: <span class="tx-danger">*</span></label> <input type="text" name="firma_adi" class="form-control" id="id_firma_adi" maxlength="256" required/> </div> </div><!-- col-4 --> <div class="gercek col col-lg-6"> <div id="fnWrapper" class=" parsley-input"> <label class="form-control-label">Adı: <span class="tx-danger">*</span></label> <input type="text" name="adi" data-parsley-class-handler="#fnWrappe" class="form-control" required="True" id="id_adi" maxlength="128" required/> </div> </div><!-- col-4 --> -
Django and Celery (Threads issue)
I have a problem with an idea that I have in mind but to achieve it I need a lot of machine resources. The idea is the following: Create a web system, with django, in which there are several users (suppose there are many); each user can create one or several processes (around 200 processes) that execute code indefinitely on the server (it can take up to days to give a result), for the process creation management I'm using celery (which I do not know if it's the Better option). I know that this is very expensive for the server, so my question is: Is it possible to achieve this task without spending so many machine resources? As I understand celery works with threads, which are supposed to be lighter than creating new processes, but in the same way it is too expensive for the given problem. -
Django include partial fields just once
I got a partials html with some form fields set. Actually, in my template i use the include tag for this partial with every field as i show in this code: <div class="row"> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.gender type="select2" addon="fa-intersex" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="inline" field=form.blood_type type="select2" addon="fa-tint" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="inline" field=form.rh_factor label_set="Factor" type="select2" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.civil_status type="select2" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.native_language type="select2" addon="fa-language" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.race type="select2" %}</div> </div> <div class="row"> <fieldset> <legend >Contacto</legend > <div class="col-md-4 col-lg-3">{% include "partials/field.html" with form_type="vertical" field=form.email type="email" addon="fa-envelope" %}</div> <div class="col-md-4 col-lg-3">{% include "partials/field.html" with form_type="vertical" field=form.email_additional type="email" addon="fa-envelope" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.cell_phone addon="fa-mobile" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form_residence.telephone addon="fa-phone" %}</div> </fiedset> </div> Like that many times, so, template takes quite long to render....is there a way to make only one include and then call the fields without that tag and improve time and efficiency in template render ?? Thanks in advance -
can't get image to load
I probably did something stupid but when i upload a image with /admin I can't get it to load. I made a for loop to get all post's and everything shows except for the image model: `class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() image = models.ImageField(upload_to='blog/media/photos') date = models.DateTimeField()` template page: ` {% for post in object_list %} <h5><a href="/blog/{{post.id}}">{{post.title}}</a></h5> <img src="{{ post.image.url }}"> <h1>{{ post.image.url }}</h1> {% endfor %}` -
How granular should Django apps be?
Per the answer to a similar question, should a new app be made for every model unless they are closely related (i.e. logically one unit)? What are the benefits of doing so? Say you have the following models class Address(models.Model): street = models.CharField(max_length=100) city = models.CharField(max_length=100) state = models.CharField(max_length=100) class Employee(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.PROTECT) company = models.ForeignKey(Address, on_delete=models.CASCADE) class Company(models.Model): name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.PROTECT) Should each model be put into its own app? Should Address be in one app with Company and Employee in another? Are they all closely related enough to belong to the same app? What is the recommended granularity for apps in a good Django project? -
Django postgress - dynamic SearchQuery object creation
I have a app that lets the user search a database of +/- 100,000 documents for keywords / sentences. I am using Django 1.11 and the Postgres FullTextSearch features described in the documentation However, I am running into the following problem and I was wondering if someone knows a solution: I want to create a SearchQuery object for each word in the supplied queryset like so: query typed in by the user in the input field: ['term1' , 'term2', 'term3'] query = SearchQuery('term1') | SearchQuery('term2') | SearchQuery('term3') vector = SearchVector('text') Document.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank').annotate(similarity=TrigramSimilarity(vector, query).filter(simularity__gt=0.3).order_by('-simularity') The problem is that I used 3 terms for my query in the example, but I want that number to be dynamic. A user could also supply 1, or 10 terms, but I do not know how to add the relevant code to the query assignment. I briefly thought about having the program write something like this to an empty document: for query in terms: file.write(' | (SearchQuery( %s )' % query )) But having a python program writing python code seems like a very convoluted solution. Does anyone know a better way to achieve this? -
Override clean_<fieldname>() in django so that it does not return an error when an existing entry is entered
I have a django form which takes a charfield: panel_name = forms.CharField(required=True, label='Panel Name') I want this form to be able to take existing panel_names as well as add new ones. However when I add a panel that is already in my Panel table, calling: if form.is_valid(): raises an error which renders to this next to the HTML input field: <span id="error_1_id_panel_name" class="help-inline"><strong>Panel with this Panel name already exists.</strong> How can I override this using "cleaned_panel_name"? I have tried it doing the following, but it still happens: def clean_panel_name(self): panel_name = self.cleaned_data['panel_name'] try: Panel.objects.get(panel_name=panel_name) print("INFO: Panel exists.") return panel_name except ObjectDoesNotExist: pass return panel_name thanks -
update model instance which has m2m fields also
I want to update my model instance using .update(**kwargs) for non-realted fields and .clear() followed by .add() for related fields. My problem is that only one of them is getting executed at a time. When I do the following its working and updating the m2m fields: def preview(request): worksheet_object = WorkSheet.objects.get(pk=int(wsheet_id)) worksheet_object.question.clear() worksheet_object.question.add(*question_pk_list) #other m2m fields But I want to update the non-related fields also and its not working when I do the following: def preview(request): worksheet_object = WorkSheet.objects.get(pk=int(wsheet_id)).update( classroom=worksheet_data['classroom'], category=worksheet_data['category'], #other fields) worksheet_object.question.clear() worksheet_object.question.add(*question_pk_list) #other m2m fields I am using this answer and this answer to do the same in my view. Can anyone help figure out what I am doing wrong? and how it can be corrected? -
How to set oninput event on a field in DjangoAdmin?
Because Django html is generated in the back, I don't have much control over how each field is generated. Because of this, I'm trying to set the element's oninput in a <script> tag but it's not working. Does anyone know how to get the following to work? <input type="number" name="area_hct" value="0.70" step="0.01" required id="id_area_hct" /> <input type="text" id="country" value="Norway" readonly><br> <script> function octest() { var hct = document.getElementById("id_area_hct") var country = document.getElementById("country") country.value = hct.value } var hct = document.getElementById("id_area_hct") hct.oninput = octest() </script> -
Select ROI on a Webpage using Django and OpenCV
Recently, I am trying to create a webapp using Django where my workflow is something like this: User opens up a page [localhost:8000/some_name] My Django app which is running on Raspberry Pi clicks the image. The image which is snapped is shown on the page The user should be able to select the ROI field of the image Once selected I should get the following x1, y1, x2, y2 . I am able to do it using OpenCV as a standalone script but unable to add the same to my page in Django app. Hope I am clear with the statement. Here's my views.py code which I have tried : from django.shortcuts import render import cv2 import numpy as np from picamera import PiCamera from time import sleep def get_roi_option(request): camera = PiCamera() camera.start_preview() sleep(5) camera.capture('picture_initial.jpg') camera.stop_preview() # Read image im = cv2.imread("<path_to_pic>") # Select ROI r = cv2.selectROI(im) # Crop image imCrop = im[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])] print(int(r[1])) print(int(r[1] + r[3])) print(int(r[0])) print(int(r[0] + r[2])) dict_of_values = {'r1': int(r[1]), 'r2': int(r[1] + r[3]), 'r3': int(r[0]), 'r4': int(r[0] + r[2])} context = {'ctx': dict_of_values} # Display cropped image cv2.imshow("Image", imCrop) cv2.waitKey(0) return render(request, context, 'base.html') -
Django Error While Creating Pages
I encountered this issue while creating a page in tango_with_django_project. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/rango/category//add_page/ Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order: admin/ ^rango/ ^$ [name='index'] ^rango/ about/$ [name='about'] ^rango/ ^add_category/$ [name='add_category'] ^rango/ ^category/(?P<category_name_url>\w+)/$ [name='category'] ^rango/ ^category/(?P<category_name_url>\w+)$/add_page/$ [name='add_page'] ^media\/(?P<path>.*)$ The current path, rango/category//add_page/, didn't match any of these. Please have a look at my files. The following is my views.py. def add_page(request, category_name_url): context = RequestContext(request) category_name = decode_url(category_name_url) if request.method == 'POST': form = PageForm(request.POST) if form.is_valid(): page = form.save(commit=False) try: cat = Category.objects.get(name=category_name) page.category = cat except Category.DoesNotExist: return render_to_response('rango/add_category.html', {}, context) page.views = 0 page.save() return category(request, category_name_url) else: print (form.errors) else: form = PageForm() return render_to_response( 'rango/add_page.html', {'category_name_url': category_name_url, 'category_name': category_name, 'form': form}, context) This is my urls.py from django.conf.urls import url from rango import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'about/$', views.about, name='about'), url(r'^add_category/$', views.add_category, name='add_category'), url(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'), url(r'^category/(?P<category_name_url>\w+)$/add_page/$', views.add_page, name='add_page'), ] This is my add_page.html <!DOCTYPE html> <html> <head> <title>Rango</title> </head> <body> <h1>Add a Page to {{category.name}}</h1><br/> <form id="pageI encountered this issue while creating a page in tango_with_django_project. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/rango/category//add_page/ Using the … -
Like/Unlike Button with jQuery in a Django App
I'm trying to create a Like/Unlike button with jQuery! Here's what I did, Here's the HTML, <span class="like-button">{% if request.user in content.likes.all %}Unlike{% else %}Like{% endif %}</span> Here's the jQuery, $('.like-button').click(function(){ var x = $(this); x.toggleClass('like-but'); if(x.hasClass('like-but')){ x.text('Like'); } else { x.text('Unlike'); } }); This code seems working fine but the problem is when i like some content (it shows Unlike, fine) & then refresh the page (still shows Unlike, fine), But when I press Unlike after refreshing page it doesn't work. It takes 2 clicks not 1 to change from Unlike to Like. -
how to use model's serializer fields content?
I have a serializer like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') and a function like this: def check (self , request): if unique('username' , 'email'): return True return False how could I pass 'username' and 'email' content through the function? -
Difference between child model types in Django
I am building a control panel that will have multiple sub-applications in Django. One of my models is an application, which will have important settings like name, description, install_path and id (so that I can associate specific settings and configuration values to this application. Right now I'm struggling in trying to figure out how to declare this particular model. Each application will do something completely different than each other application. One might manage specific CMS settings and another may handle password resets for our development environment. The goal is to get the commonly used things in one place. My question is, what is the difference between declaring my applications using abstract base class models vs. proxy models. The main information for each application will be the same. Each will have a name, description, etc. The difference will be what they do and what settings they use. The settings are in their own model though, with a link back to the application via foreign key. -
import error rest_framework_httpsignature.authentication django rest frame work?
i am importing from rest_framework_httpsignature.authentication import SignatureAuthentication in django 1.8v and python 2.7.6 ,it causeing importing error only to this class SignatureAuthentication in vs studio , please help but i can able to import this class rest_framework.authentication -
Lightweight alternative to geodjango for MVP (minimal viable product)
For a django-based webapp MVP I need a global city/country database. It has two requirements. It should be as simple as possible to get up and running. Ideally without much installation, but maybe as initial data in fixtures, which can be pushed to collaborators. The user generated location information (eg their home city), should later on be transferable to a more involved geodatabase like geodjango. Do you know a good option? Thank you! -
Creating answer related questions
this is my third post about the tool I am writing and until now you have helped me so much. I am writing a QuizTool which has to handle Polls, Multiple Choice Questions and Branched Questions. So far I am able to list my surveys, loop through questions and post the related answers to save them in my model. Also i am able to create multiselect fields for the Multiple Choice Questions. But its realy hard to figure out how the Branched Questions work for me. Let me explain how I approach to this problem. Here is the relevant part of my model: class Answer(models.Model): answer_id = models.AutoField(blank=False, null=False, primary_key=True) answer_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Antwort')) # Internal fields date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am')) date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am')) def __str__(self): return self.answer_text class Meta: # db_table = 'data' verbose_name = _(u'Antwort') verbose_name_plural = _(u'Antworten') ordering = ['answer_id'] class Question(models.Model): question_id = models.AutoField(blank=False, null=False, primary_key=True) # Fields answer = models.ManyToManyField('Answer', through='Question_Answer', related_name='+') question_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Frage')) # Internal fields date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am')) date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am')) #Typunterscheidung der Fragen QUESTION_TYPES = ( ('0', … -
Centralized Authentication in Django 2.0
I need some help with building something (That I call) Centralized Authentication Server in Django 2.0, which will support the following: Say There are 2 services: Service A - which is the frontend application. It's a simple Django project the has only one view that serves a VueJS application. Service B - which is the API. Service A is sending AJAX requests to Service B. The 2 services are totally separate, and ideally I would like to not handle any User model in none of the services. What I would like is to use Service C, which is a service that handles all the Authentication and the User model. When a user goes to Service A and he is not logged in, he will be redirected to Service C and login to the system using his credentials (User/Password) and then will be redirected back to Service A, alongside with a token that will enable him to speak with service B. Then service B will get this token, and authenticate it against service C. (In each request, or only in the first request / dedicated 'login' request). I read a lot about django-mama-cas + django-cas-ng, and tried to implement it. But … -
Anonymise email data with django allauth
I am migrating an old database to django allauth using the email address as the username. However, the database has a load of old users that have used the same email address to register for separate accounts, so the migration is failing. I'd quite like to anonymise the duplicate accounts (and it's something I think is worth being able to do anyway, with GDPR in mind) but I'm not sure how to go about it. The only thing I can think of is to set their email address to something (unique) that my system can then check for and not send emails to. But that feels really hacky to me. Is there a better way?