Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript/Django - Reloading selector when option changed in another selector?
I have very little experience using JavaScript, I am trying to implement (similar to the first method in this question: Django/jQuery Cascading Select Boxes?) a drop down menu with options populated from a database table, then when an option is selected in the first drop down, options in the second drop down are populated depending on what was first selected. At the moment, my first dropdown is fine, but when selecting one of the options, javaScript for reloading the second dropdown is not working. I have no idea if I have implemented it correctly, any help would be appreciated. html <select name="make" id="select_make"> <option value="" disabled selected>(Car Make)</option> {% for mk in makes %} <option value="{{ mk }}" {% ifequal mk make %} selected="selected" {% endifequal %}>{{ mk }}</option> {% endfor %} </select> <select name="model" id="select_model"> {% for md in models %} <option value="{{ md }}" {% ifequal md model %} selected="selected" {% endifequal %}>{{ md }}</option> {% endfor %} </select> <script type="text/javascript"> $('#select_make').change(function(event) { $("#select_model").load(window.location.href + " #select_model"); }); </script> views.py def get(self, request): context = {'model': None, 'makes': Vehicles.objects.values_list('makename', flat=True).distinct()} if 'make' in request.POST: context['make'] = request.POST['make'] context['models'] = Vehicles.objects.filter(makename=context['make']).values_list('model', flat=True).distinct() if 'model' in request.POST: context['model'] = request.POST['model'] … -
Can RESTful API's scale, and do all mobile apps use them
I wanted to build an app in react-native, and a RESTful API in Django-rest-framework. My plan was to write the front end in react-native and write one RESTful API on one server for both my website and my app. My question is: Can this kind of architecture scale? Is this practical or possible? How do other apps connect to their backend (i.e. How does Instagram connect to its mobile backend)? Should I use this for my website that I am making in plain HTML, CSS, and Javascript? Any answers are appreciated, Thanks -
Django return to trigger the error view in jquery function
I have the following view in django: def update_card(request): return HttpResponse(status=400, message="You cannot call this method"). And in jquery: $.ajax({ url: "{% url 'update_card' %}", type: 'POST', success: function(data){ console.log('OK!') }, error: function(err){ var response_message = err.responseText; alert(err.responseText) } }); But for whatever reason, this is triggering the success method unless I do something like raise Exception(200, "You cannot call this method"). Why? Am I not allowed to return a HttpResponse object to jquery? -
Django Rest Framework custom permission validation
I have a custom ViewSet that makes composited queries and updates to the database. I want to establish different levels of permissions, so I can authorize some users to send GET method on the view, and some other users to be allowed to request POST and PUT methods. In the documentation I have found, all permissions are considered global to the class view, so I don't know how to apply some permissions to the list method, and some different permissions to the create and update methods of the ViewSet. This is the main code of the ViewSet: class ReservationCompositionViewSet(viewsets.ViewSet): def list(self, request, pk): reservation = models.Reservation.objects.filter(booking=pk).order_by('timestamp').last() if reservation == None: raise CustomValidation(_('There is not such Reservation: {}'.format(pk)), 'booking', status.HTTP_400_BAD_REQUEST) result_set = serializers.ReservationSerializer(reservation).data result_set['pax'] = self.get_reservation_people(reservation) result_set['itinerary'] = self.get_reservation_composition(reservation) return Response(result_set) ... def create(self, request): reservation_data = request.data user = request.user reservation = models.Reservation() reservation.booking = reservation_data['booking'] reservation.agency = models.Agency.objects.get(id=reservation_data['agency']) reservation.comment = reservation_data.pop('comment', None) reservation.status = reservation_data.pop('status', 'UNCONFIRMED') if reservation.status == None: reservation.status = 'UNCONFIRMED' reservation.arrival_date = reservation_data['arrival_date'] reservation.departure_date = reservation_data['departure_date'] reservation.confirmation = reservation_data.pop('confirmation', None) reservation.is_invoiced = reservation_data['is_invoiced'] reservation.user = user reservation.save() reservation_to_return = serializers.ReservationSerializer(reservation).data reservation_to_return['pax'] = self.save_reservation_people(reservation, reservation_data.pop('pax')) reservation_to_return['itinerary'] = self.save_reservation_components(reservation, reservation_data.pop('itinerary')) return Response(reservation_to_return) def update(self, request, pk): reservation_data = … -
Automating App Engine Deployments with Cloud Build failed with error
Now I am setting up "Automating App Engine Deployments with Cloud Build" at GCP and stuck at final step of Quickstarts. There is error message when I checked "Build history" after git push origin master. And it is hard for me to understand what the message means. ERROR: (gcloud.app.deploy) There is a cloudbuild.yaml in the current directory, and the runtime field in /workspace/app.yaml is currently set to [runtime: python]. To use your cloudbuild.yaml to build a custom runtime, set the runtime field to [runtime: custom]. To continue using the [python] runtime, please remove the cloudbuild.yaml from this directory. Please refer to following codes in the source directory, app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT acct.wsgi runtime_config: python_version: 3 manual_scaling: instances: 1 resources: cpu: 1 memory_gb: 0.5 disk_size_gb: 10 cloudbuild.yaml steps: - name: "gcr.io/cloud-builders/gcloud" args: ["app", "deploy"] timeout: "1600s" -
Django Rest Framework GET Request HTTP Header
Whenever I send a GET request to localhost:5000/endpoint, it completes successfully; however, when I append a HTTP Header to the request POSTMAN states that "Could not get any response. There was an error connecting to localhost:5000/endpoint." What could be the cause of the error? -
which is better? Flask or Django?
I am new to Python family and I am planning to learn a python framework. Suggest me which framework is better to start with and why to choose that? -
Problems deploying Django in Heroku
I am trying to deploy my django app on heroku but when I do heroku open I get application error and my logs says: 2018-10-19T20:39:59.583888+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=murmuring-ocean-21982.herokuapp.com request_id=a9f0b234-852a-4106-bbe2-16527c06057f fwd="88.1.141.252" dyno= connect= service= status=503 bytes= protocol=https 2018-10-19T20:39:59.815075+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=murmuring-ocean-21982.herokuapp.com request_id=0fde005c-d359-42f8-9f8a-a9b27464e340 fwd="88.1.141.252" dyno= connect= service= status=503 bytes= protocol=https I'm quite desperate at the moment please help me solved the issue. My code: https://bitbucket.org/molivera8/stackoverflow/src/master/ -
Combining css, html, and js in templates/ folder
I usually see variations on this project structure in django, where the static files are managed by apache or nginx: app/ views.py static/ js/ base.js img/ css/ base.css templates/ home.html manage.py urls.py settings.py However, for a tiny app, is the following an acceptable approach? app/ views.py templates/ base.js base.css home.html manage.py urls.py settings.py If it's a terrible approach, could someone please explain why? For me, it seems like often a template html file contains inline css or javascript for a particular override or convenience, so the above approach doesn't seem that much different for a small application. -
Wagtail Forms: Validator that compares two email fields
I am creating a form using Wagtail Forms, and I would like to add a couple of email fields, and compare them to make sure the user is not submitting the same email address twice. How would I go about this? -
Can ' and " be used interchangeably in Python / Django
I have a statement in django view : form.add_error(None,"Check your e-mail for activating username") Can i use form.add_error(None,'Check your e-mail for activating username') instead -
Minimal Example for dynamic HTML pages with Django and AJAX
I refer to the following posts: Reload table data in Django without refreshing the page Django dynamic HTML table refresh with AJAX Despite the two post and nice answers, I am still struggling to construct a minimal working example for dynamic HTML pages resorting to Django and AJAX. I have to following code: models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^get_more_tables', views.get_more_tables, name='get_more_tables') ] views.py from django.shortcuts import render from .models import Question def index(request): a = Question.objects.order_by('-pub_date') context = {'questions': a} return render(request, 'polls/index.html', context) def get_more_tables(request): a = Question.objects.order_by('-pub_date') context = {'questions': a} return render(request, 'polls/get_more_tables.html', context) index.html <html> <body> <table id="_appendHere"> <tr><td> text </td></tr> {% for a in questions %} <tr><td> {{ a.question_text }} </td></tr> {% endfor %} </table> </body> </html> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: "{% url 'get_more_tables' %}", data: {'append_increment': append_increment} }) .done(function(response) { $('#_appendHere').append(response); append_increment += 10; }); }, 1000) get_more_tables.html {% for a in questions %} <tr><td> {{ a.question_text }} </td></tr> {% endfor %} I have the following issues: According to Console Error with … -
Using django-select2 for a dropdown list with pictures
I'm trying to take another approach for the problem I desribed below making use of django-select2 module. Django choicefield using pictures instead of text not displaying I have a django model which looks like: My model looks like: class MyPicture(models.Model): name = models.CharField(max_length=60, blank=False, unique=True) logo = models.ImageField(upload_to='logos') def __str__(self): return self.name I would like to create a drop down looking like source: http://select2.github.io/select2/ where essentially I have a big picture on the left (corresponding to what I called logo) and some text on the right (corresponding to name). My form looks like: from django_select2.forms import Select2MultipleWidget class MyPictureForm(forms.Form): pictures = forms.ModelChoiceField(widget=Select2MultipleWidget, queryset=MyPicture.objects.all()) My view looks like: def mypicture(request): form = MyPictureForm(request.POST or None) if form.is_valid(): #TODO return render(request, 'myproj/picture.html', {'form': form}) and finally, my hmtl (where something is wrong): {% load staticfiles %} <head> {{ form.media.css }} <title>In construction</title> </head> <form action="{% url 'mypicture' %}" method="post"> {% csrf_token %} <select id="#e4" name="picture"> {% for x in form.pictures.field.queryset %} <option value="{{ x.id }}"><img src="{{ MEDIA_URL }}{{ x.logo.url }}" height=150px/></option> {% endfor %} </select> <br> <br> <input type="submit" value="Valider" class="btn btn-primary"/> <script src="//code.jquery.com/jquery-2.1.4.min.js"></script> <script type="text/javascript"> function format(x) { if (!x.id) return x.name; // optgroup return "<img src=" + x.logo.url + "/>" … -
Database design and Django Model for Contact and Enquiry
I'm working on a small Django website for a photographer. There are a contact form and a booking. A percentage of these contact leads will be lost. If the customer books, the app should be able to follow up with the customer. I've been thinking about how to proceed and my idea is to create a contact table with the information that the customer provides from the contact form and a second table that would have a "One to One" relationship in case that the lead becomes a customer. In a later stage after the event has happened, there will be a private access folder where the user can download his pictures. And has to be a user in order to be able to log in and have authorization and authentication. How would you design the database and the models in Django? Any advice or considerations in order to tackle de problem in the best way possible? Thanks for your help! -
{{ context.date_published }} prints blank in HTML file
Here is the Model that I created: from django.db import models from datetime import datetime class Disasters(models.Model): author = models.CharField(max_length=15, blank=False) date_published = models.DateTimeField(default=datetime.now, blank=True) link = models.CharField(max_length=100, blank=True) I created an object as follows: d = Disasters(title='title', body='body', link='link', author='author') Now when I print this through jinja logic I get nothing (blank) in place of {{ disaster.date_pusblished }}: <p class="post-meta">Posted by <a href="#">{{ disaster.author }}</a> on {{ disaster.date_pusblished }}</p> </div> And when I run the command: d.date_published I get: datetime.datetime(2018, 10, 19, 16, 17, 23, 396316, tzinfo=<UTC>) So I know the date_published field is not empty. Then why does it not show in the HTML page?? -
Django: Protecting certain media from non-authed users
I'm trying to protect certain files from outside users. After reading a bunch of posts and questions here, I came up with a solution that doesn't require adjusting server settings, and seemed within my technical level of understanding. But after all that research, my solution seems a bit too easy. So, I wanted to come here and see if this makes sense, is somewhat secure, and what holes I'm missing. I'm uploading the files I'm concerned about to a folder called protected within the media directory in this example. Here is my urls.py file: import re from . import views from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.auth.decorators import login_required from django.shortcuts import HttpResponseRedirect from django.urls import path from django.views.static import serve from django.contrib.auth import views as auth_views @login_required def serve_protected_media(request, path, document_root=None, show_indexes=False): return serve(request, path, document_root, show_indexes) def protected_serve(request, path, document_root=None, show_indexes=False): if re.match(r'^protected', path): return serve_protected_media(request, path, document_root, show_indexes) else: return serve(request, path, document_root, show_indexes) urlpatterns = [ path('', views.index, name='site_index'), path('admin/', admin.site.urls), path('hr/', include('hr.urls')), path('accounts/login/', auth_views.login, name='login'), path('accounts/logout/', auth_views.logout, name='logout', kwargs={'next_page': '/'}), ] + static(settings.MEDIA_URL, protected_serve, document_root=settings.MEDIA_ROOT) It works for me with some testing, but … -
ReverseNotFound - Can't connect Detail View to List View
When I try to go to the asset_list view, it gets hung up on the get_absolute_url() and throws the error Reverse for 'asset_detail' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['en/marketing/$/<int:id>/'] I am using a bunch of instances of this assets application around the site and each will serve out a few different assets based on a tag attribute. The Apphooks work great and everything is attached in the cms. I had everything working until I started experimenting with the detail views. I think I have two issues, one with the get_absolute_url and one in the urls.py This is what I have urls.py from django.conf.urls import url, include from .views import AssetListView, AssetDetailView app_name = 'assets' urlpatterns = [ # List View url(r'^$', AssetListView, name="asset_list"), url(r'^$/<int:id>/', AssetDetailView, name='asset_detail') ] models.py class Asset(models.Model): name = models.CharField(max_length=50, blank=False) description = PlaceholderField('asset_description') asset_category = models.ManyToManyField(Asset_Category, blank=True) tag = models.ManyToManyField(Tag, blank=True) product_category = models.ManyToManyField(Category, blank=True) product_series = models.ManyToManyField(Series, blank=True) product_line = models.ManyToManyField(Line, blank=True) product = models.ManyToManyField(Product, blank=True) url = models.CharField(max_length=250, blank=True, verbose_name='Video URL') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("assets:asset_detail", kwargs={"id": self.id}) views.py def AssetListView(request, *args, **kwargs): path = os.path.basename(os.path.normpath(request.path)) print(path) page_obj = Title.objects.filter(slug=path).first() print … -
Django: integrating standalone user authentication LDAP/Keycloak?
First question on stack overflow. I'm developing an app in Django, until now the built in user management solution has worked out well. However, now, I'd like users of my web app to get a git account when they start a project in the browser. Thus, I need a standalone user authentication that upon registration on my website sets up an account automatically on the git server. I've looked into this and am considering setting up FreeIPA + Keycloak (and utilizing Keycloak for Google authentication etc..). Im wondering if this is a preferred solution or what other options you would suggest? My idea, Webserver: Django <--> KeyCloak <--> FreeIPA (LDAP) Git-server: Git <--> FreeIPA (LDAP) This feels like quite a clunky solution, albeit, a robust one. Id like comments, ideas or your preffered solution. Im quite a novice when it comes to webprogramming and I'd like to use standard/optimized solutions. -
Django html form data throws NoReverseMatch
I have a simple Django site and im trying to build a form which is hidden until i click Add daata. Once i Click Add data it show show me below input aread like First Name, Last Name and Country. Once Submited it should redirect me to new page which will list all the names present in DB. Below is my Html form code : <div id="sub_div2"> <a href="/myapp/mylink"> <h4> Add Data</h4> </a> <p> <button onclick="myFunction()">Add New Data</button> </p> <button onclick="myFunction()">Add New data</button> </p> <form id="myDIV" style="display" action="{% url 'data_app:forminput' %}" method="POST" enctype="multipart/form-data"> <div style="margin:0;padding:0"> <label for="fname">First Name</label> <input type="text" id="fname" name="firstname" placeholder="Your name.."> <br> <br> <label for="lname">Last Name</label> <input type="text" id="lname" name="lastname" placeholder="Your last name.."> <br> <br> <label for="country">Country</label> <select id="country" name="country"> <option value="australia">Australia</option> <option value="canada">Canada</option> <option value="usa">USA</option> </select> <br> <br> <input type="submit" value="Submit"> </form> <br> </div> <br> And my Project url.py is as below urls url(r'^', include('data_app.urls', namespace='data_app')), url(r'^index$', views.index, name='index'), url(r'^forminput$', views.data_update, name='data_update'), and my views.py as below function def data_update(request): if request.POST: messages.success(request, 'Form submission successful') return HttpResponseRedirect('/') When i try this i get below error : Reverse for 'forminput' not found. 'forminput' is not a valid view function or pattern name. I want to enter … -
I am attempting to deploy a django project on an Ubuntu server but I keep getting a "Connection timed out" error
I set the project up with a viturualhost and I have configured the apache server accordingly as far as I understand. I initially tested the server out with a basic django skeleton project which ran perfectly fine, both on the django server on port :8000 and also on the apache server with just the plain domain address. After uploading the project I configured and migrated the database and installed all requirements. I am able to use the "python manage.py runserver" command with no visible errors. Also the apache error log does not display any serious errors that could possibly be causing the problem. Is there something I'm missing? -
Template Syntax Error - Django dictionary assignment with static files keyword
In my Django project, what I am trying to achieve is that I pass a dictionary of the form dict ={0 = ["'eduaction/Apple.obj'","'education/Apple.mtl'"]}. I just want to assign these values to the .obj and .mtl attributes. But I keep getting the error of the type : Could not parse the remainder: '[0]' from 'value[0]'. I am new at Django, is this the correct way of assigning values from the dictionary to the template? Please help. My views.py : from django.http import HttpResponse from django.template import loader def viser(request): template = loader.get_template('education/viser.html') context = {} context[0] = [] context[0].append("'education/Apple.obj'") context[0].append("'education/Apple.mtl'") query = request.POST.get('inputquery', False) if query: for classlabel, value in context.items(): print(value[0]) template2 = loader.get_template('education/DOG.html') return HttpResponse(template2.render(context, request)) return HttpResponse(template.render(context, request)) DOG.html: <html> <head> <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script> </head> <body> <a-scene> <a-sky color="#6EBAA7"></a-sky> {% load static %} {% for class, value in context.items %} <a-entity obj-model="obj: {% static value[0] %}; mtl: {% static value[1] %};" scale="0.1 0.1 0.1" rotation="0 0 0" position="0 1 -10"></a-entity> {% endfor %} <a-camera position="0 0 100" look-controls wasd-controls="acceleration:1000"> <a-cursor color="yellow"></a-cursor> </a-camera> </a-scene> </body> </html> -
templates won't work after adding migrations
I added the data via migration and now after running migrate and makemigrations i tried to runserver and there are NoReverseMatch Errors everywhere. Take a look at this error: NoReverseMatch at /blog/ Reverse for 'blog_post_detail' with keyword arguments '{'year': 2008, 'month': 9, 'slug': 'django-10-released'}' not found. 1 pattern(s) tried: ['(?P\d{4}/)^(?P\d{1,2}/)^(?P\w+)/$'] This is the actual urlpattern: re_path (r'^(?P<year>\d{4}/)' r'^(?P<month>\d{1,2}/)' r'^(?P<slug>\w+)/$',post_detail,name='blog_post_detail'), Similarly every template has the same problem.... -
Django radio buttons - I'm going crazy
I can really use some help. I tried to be as detailed and thorough as I could be. Overall, I have two questions: Q1 - Should I even be using crispy or Django forms for this? Or is it too complex and needs to be written straight up in the template with HTML and CSS? Q2 - if you think it can be done with crispy, can you please help me along in figuring this out? I have strings of data stored in the backend database (PostGres) that look like this: 'LAC@ARI 18 October 2018 08:00 PM ET' I can easily get each object and display it in a crispy form by doing this: class GameFadeForm(forms.Form): def __init__(self, *args, **kwargs): super(GameFadeForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False initial = kwargs.pop('initial', None) if initial: NFL = initial['NFL'] games = [(g.id, str(g.game_info)) for g in NFL.games] self.fields['game_fade'].choices = games game_fade = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'style': 'height: 15em;'}), required=False) This successfully renders the form and I can select the strings...however, this isn't what I really wanted to do, it was just a first step really. There is a link to a PNG of what I'm trying to get to - I have had several … -
How to pass a variable from one view to another in Django
I would like to pass a variable from one view to another in Django, and am not sure of the best method. The "defaultCreateView" below is a form that makes a new database entry, and has a required field that I want filled automatically (device_id). So my thought is I could pass it through in the URL. This form is accessed using the button shown in my template below. So the idea is that the first view passes the variable to the template where the button is, then this button adds the device_id to the url via the href. I think I am close but I am getting a 'NoReverseMatch "default_new"' error. I think this is due to the template variable not being passed into the url properly, or my url syntax is incorrect... Is there a much easier/better way to accomplish this? Thanks in advance for any help. urls.py urlpatterns = [ path('<int:pk>/edit/', defaultUpdateView.as_view(), name='default_edit'), path('<int:pk>/', defaultDetailView.as_view(), name='default_detail'), path('<int:pk>/delete/', defaultDeleteView.as_view(), name='default_delete'), path('<int:device>', DefaultsListView.as_view(), name='Default_Listview'), path('<int:device>/new/', defaultCreateView.as_view(), name='default_new'), path('Defaultsapidata/', apiDefaultsListView.as_view(), name='Defaults_apidata_list'), path('<int:pk>/changedefaults/', changeDefaultsViewSingle.as_view()), ] Views.py class DefaultsListView(LoginRequiredMixin,ListView): model = models.DefaultDMLSProcessParams template_name = 'defaults_list.html' login_url = 'login' def get_queryset(self): return super(DefaultsListView, self).get_queryset().filter(device_id=self.kwargs['device']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) deviceID = self.kwargs['device'] … -
Django model decoupling
I'm working with Django 2.1 on a fairly simple application and I'm struggling to find a pattern I'm convinced with when dealing with app decoupling. Right now I have a simple sales app and a taxes app. The taxes app references the Customer model in the sales app in a model I called Contributor which contains the tax information for a specific customer. Here is a simplified version. #sales/models.py class Customer(models.Model): name = models.CharField() address = models.CharField() email = models.CharField() #taxes/models.py class Contributor(models.Model): customer = models.ForeignKey(sales.models.Customer) tax_id = models.CharField() sales_tax_type = models.CharField() What I would like to do is to be able to keep these apps loosely coupled so if I needed to replace the taxes app entirely the sales app wouldn't even care. The problem arises when I need to perform lookups based on fields on both tables, for instance I need to retrieve customers containing a string in their names and having a certaing sales_tax_type. Right now I'm querying in the taxes app by referencing the customer attributes. This aproach I don't really like because it requires me to query based on the customer model specifically and later on I may require contributor data for other models (like …