Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changes made to code not getting reflected on a django app with nginx and gunicorn
I have already tried the systemctl restart gunicorn/nginx and have already deleted the cached files ending with .pyc. Anyone got any solutions other than this? The site is running on an ubuntu ec2 instance of aws -
The best framework for the Web (With server-side python) [on hold]
I will explain the need: I am starting a project in my graduation project and I would like to create a platform (Python with other language for interfaces), and here is the approach: I thought about Wordpress and I already posted a subject in this way, but I can not do related Wordpress and Python (I do not find a plugin for that) There is Django and Flask (I'm looking for something that can give me a very good interface, I have to work a lot on the designated side) I am open to your proposals stp. Thank you very much. Regards, -
Django rest disable templates for only return data
Environment: Python 3.6 Django 2.0 Django REST 3 I am connecting a django project with an android application and everything has worked correctly but I have a problem that anyone who accesses the url of the requests in android can see that data. I want to block that render or template and only return the json data that I need for my android application. myapp/View.py class restContact(APIView): def get(self, request): allcontact = Contact.objects.all() serializer = ContactSerializer(allcontact, many=True) return Response({"state":"1","control":serializer.data},status=status.HTTP_400_BAD_REQUEST) myapp/Url.py from django.contrib import admin from django.conf.urls import url,include from apps.my-app.views import restContact urlpatterns = [ url(r'^contacts/$', restContact.as_view()), ] proyect/url.py from django.conf.urls import url from django.urls import include from django.contrib import admin urlpatterns = [ url(r'',include('apps.index.urls')), url(r'^admin/', admin.site.urls), url(r'^index/',include('apps.index.urls')), url(r'^movil/', include('apps.myapp.urls')), ] I just need to return jsonObject and in the browser to write the url www.mypage.com/movil/contacts can not see all the data in the get. -
Django: Filter a Queryset made of unions not working
I defined 3 models related with M2M relationsships class Suite(models.Model): name = models.CharField(max_length=250) title = models.CharField(max_length=250) icon = models.CharField(max_length=250) def __str__(self): return self.title class Role(models.Model): name = models.CharField(max_length=250) title = models.CharField(max_length=250) suites = models.ManyToManyField(Suite) services = models.ManyToManyField(Service) Actions = models.ManyToManyField(Action) users = models.ManyToManyField(User) def __str__(self): return self.title In one of my views I tried to collect all the Suites related to an specific User. The user may be related to several Roles that can contain many suites. And then filter Suits by name. But the filter seem to have no effects queryset = Suite.objects.union(*(role.suites.all() for role in self.get_user().role_set.all())) repr(self.queryset) '<QuerySet [<Suite: energia>, <Suite: waste 4 thing>]>' self.queryset = self.queryset.filter(name="energia") repr(self.queryset) '<QuerySet [<Suite: energia>, <Suite: waste 4 thing>]>' The query atribute inside the queryset not alter its content before executin the filter: (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite") UNION (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite" INNER JOIN "navbar_role_suites" ON ("navbar_suite"."id" = "navbar_role_suites"."suite_id") WHERE "navbar_role_suites"."role_id" = 1) (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite") UNION (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite" INNER JOIN "navbar_role_suites" ON ("navbar_suite"."id" = "navbar_role_suites"."suite_id") WHERE "navbar_role_suites"."role_id" = 1) -
Apps deployed on Heroku do not reflect on a part of programme although they can work on local server
This application was developed through Djangogirls tutorial (https://tutorial.djangogirls.org/en/django_forms/). I would like to know how to find out the reason and fix them. I dont get why those kinds of problems happens as the blow pictures show. The local server: Everything does work correctly and I just would like to make this work on heroku enter image description here Apps deployed on Heroku: Any post does not show up although I think that I push correctly files on heroku enter image description here What I already did was here: 1) restart heroku and relaunch apps 2) clear cache of chrome and reload apps 3) check git log 4) commit and push again (git push heroku master) What should I do next ? See how data migration is working but I do not know how to check ... -
How to customize database connection settings' timezone in django?
I am looking into django db backends. I have found that datetime values' timezone are changed to and forth by django, while saving dates into db as well as retrieving them. During this conversion process, django uses database connection's timezone settings. I have seen that by default for sqlite db, 'UTC' is the timezone. I want to change the database connections options, during the start of django application. How can I do that ? Thanks in advance. -
I'm overlooking something: TypeError: create() got unexpected keyword argument 'system'
It's probably a noob mistake, but I cant find the error. Below is the project.models class ProjectManager(models.Manager): """""" def create(self, owner, project_name): project = super().create(owner=owner, project_name=project_name) project.save() System.objects.create(project=project, system_name="System initial name") return project class Project(models.Model): objects = ProjectManager() owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE) project_name = models.CharField(max_length=200) In the system.models I now define the System and Circuit model, i.e. each project has at least one System and each System has at least one circuit. class SystemManager(models.Manager): """""" def create(self, project, system_name): system = super().create(project=project, system_name=system_name) system.save() Circuit.objects.create(system=system, circuit_name="Primary circuit") return system class System(models.Model): objects = SystemManager() project = models.ForeignKey('solgeo.Project', related_name='systems', on_delete=models.CASCADE) system_name = models.CharField(max_length=200) @classmethod def create(cls, project): system = cls(project=project) def __str__(self): return "system name: " + str(self.system_name) class CircuitManager(models.Manager): """""" def create(self, project, system_name): circuit = super().create(system=system, circuit_name=circuit_name) circuit.save() return circuit class Circuit(models.Model): """Models a hydraulic circuit""" objects = CircuitManager() system = models.ForeignKey(System, related_name='circuits', on_delete=models.CASCADE) circuit_name = models.CharField(max_length=200) Now I get the error: create() got an unexpected keyword argument 'system'. When I comment out: Circuit.objects.create(system=system, circuit_name="Primary circuit") then the error disappears. -
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.