Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Uploaded image with FileField does not appear in templates
I am pretty new in Django and this problem is really bothering me finishing my first simple project. All I want to do is upload an image from admin page and display it in my template, but it does not appear. After I inspect my page, I found this one in my img tag:` <img src=(unknown)> This is my models.py: class Topic(models.Model): title = models.CharField(max_length=100) picture = models.FileField() def __str__(self): return self.title urls.py: from django.conf.urls import url from django.contrib import admin from firts_app import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name="index") ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL) settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' index.html as my template: {% block content %} <ul> {% for title in title_list %} <li> {{ title }} </li> {% empty %} <p>No input</p> {% endfor %} </ul> <img src="{{ topic.picture.url }}" /> {% endblock content %} -
Implementing similar type of content across most pages
Pretty basic question (I think) from a Wagtail & Django beginner. I have a website which, on every page except for the homepage, has a header image and a caption. Initially I was going to just create fields on every Page but I figured this goes against DRY principle. So then I thought a Snippet would be a good idea - however you would have to go on two different pages in the Admin to work with one page, which I didn't really like. Is there a simple and efficient way to create a template/model which every Page can instantiate? -
Django: object disappearing from model
I have a simple django model with an integer field status: from django.db import models class MyObject(models.Model): dateDownloaded = models.DateField(null=True) dateShared = models.DateTimeField(null=False) sharedBy = models.CharField(max_length=100, null=False) sharedTo = models.CharField(max_length=100, null=False) token = models.CharField(max_length=200, null=False) status = models.IntegerField(null=False, default=0) def save(self, *args, **kwargs): if not self.pk: # First time saved self.status = 0 self.token = get_random_string(length=32) super(MyObject, self).save(*args, **kwargs) I can add objects to my model and I have a simple helper that counts the number of created objects. Now I also have a call that does the following: def resetStatus(request): myObjects = MyObject.objects.all() for myObject in myObjects: myObject.status = 0 myObject.save() return HttpResponse("reset done") Issue is, after calling this, from time to time all the objects from my database have disappeared. Maybe I have done something wrong with my objects in between but I have no idea what it could be. How can I go about debugging this ? -
instanse dont work correctly for form field
I have FORM for editing data. When I open form I want to see current data values. Problem is with function field. instance works well with program field but dont work with function field. In other words in program field I see current data values but in function field it dont show me current data. I think problem is bacause I used in forms ModelChoiceField for ManytoManyField (function field). But function field must be ManyToManyField and I want to make able to add only one object(For thats why I use ModelChoiceField). models.py: class Requirement(models.Model): group_requirement = models.ForeignKey(GroupRequirement, on_delete=models.CASCADE) function = models.ManyToManyField("Function") program = models.ManyToManyField('Program') forms.py: class RequirementForm(forms.ModelForm): function = forms.ModelChoiceField(widget=Select2Widget(), queryset=Function.objects.none()) program = forms.ModelMultipleChoiceField(widget=Select2MultipleWidget(), queryset=Program.objects.none()) class Meta: model = Requirement fields = ('function', 'program') def __init__(self, all_functions, all_programs, *args, **kwargs): super(RequirementForm, self).__init__(*args, **kwargs) self.fields['function'].queryset = all_functions self.fields['program'].queryset = all_programs views.py: def requirement_edit(request, project_id, group_requirement_id): group_requirement = get_object_or_404(GroupRequirement, pk=group_requirement_id) all_functions = Function.objects.filter(project=project_id) all_programs = Program.objects.filter(project=project_id) if request.method == 'POST': requirement_form = RequirementForm(data=request.POST, instance=requirement, all_functions=all_functions, all_programs=all_programs) if requirement_form.is_valid(): requirement_form.save() -
Controller not registered according to console
For some reason my controller doesn't seem to be registered and I'm honestly not sure why... I've been following along an AngularJS and Django development course on PluralSight. The only difference between the instructor's stack and mine is that I'm using Angular 1.6.4 and he is using 1.5.0. I've previously hit some errors (like routing syntax), but it's overall been fine. EDIT: I should mention that I'm simply following the instructor's instructions and writing the same code as him. Right now, however, I'm simply stuck. I've got this routing in scrumboard.config.js: (function () { "use strict"; angular.module('scrumboard.demo', ["ngRoute"]) .config(["$routeProvider", config]) .run(["$http", run]); function config($routeProvider) { $routeProvider .when('/', { templateUrl: "/static/html/scrumboard.html", controller: "ScrumboardController", }) .when('/login', { templateUrl: "/static/html/login.html", controller: "LoginController", }) .otherwise('/'); } function run($http) { $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http.defaults.xsrfCookieName = 'csrftoken'; } })(); And this controller for login.html: (function() { "use strict"; angular.module("scrumboard.demo", []) .controller("LoginController", ["$scope", "$http", "$location", LoginController]); function LoginController($scope, $http, $location) { $scope.login = function () { $http.post('/auth_api/login/', $scope.user) .then(function (response){ $location.url("/"); }, function(error) { //failure $scope.login_error = "Invalid username or password"; }); }; }; })(); When navigating to localhost:8000/#!/login I can see my form: <form ng-submit="login()"> <div style="...">{{ login_error }}</div> <div> <label>Username</label> <input type="text" ng-model="user.username"/> </div> <div> … -
column "date" cannot be cast automatically to type timestamp with time zone django/postgres
There were a date charfield , when I saved date as string before. But now I changed the field from charfield to datetimefield and dropped all previous data. date = models.DateTimeField(default=timezone.now) Localy it works fine, but in production it raises following error when trying to migrate . I dropped the column , the model, commented and uncommented, deleted and created the field again, returned to previous migrations and migrated again, but all that didn't help. django.db.utils.ProgrammingError: column "date" cannot be cast automatically to type timestamp with time zone HINT: You might need to specify "USING date::timestamp with time zone". How to solve the problem correctly? Using django 1.8, python 2.7 and postgres -
Python Django website development
my code website/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] music/urls.py from django.conf.urls import url from . import index urlpatterns = [ url('^$', views.index, name='index'), ] views.py from django.http import HttpResponse def index(request): return HttpResponse ("This is Music Homepage ") INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'music', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' Problem Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^admin/ The current path, music, didn't match any of these. -
Django Error - AttributeError: 'CourseOverview' object has no attribute 'start_datetime_text'
I have been trying to get this theme working for Open edX (based on Django) and I am getting this error in supervisor logs - AttributeError: 'CourseOverview' object has no attribute 'start_datetime_text' The whole error is this - May 14 11:43:36 ip-172-26-15-154 [service_variant=lms][django.request][env:sandbox] ERROR [ip-172-26-15-154 20450] [base.py:256] - Internal Server Error: / Traceback (most recent call last): File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner return func(*args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view response = view_func(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/common/djangoapps/util/cache.py", line 78, in wrapper response = view_func(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/lms/djangoapps/branding/views.py", line 94, in index return student.views.index(request, user=request.user) File "/edx/app/edxapp/edx-platform/common/djangoapps/student/views.py", line 221, in index return render_to_response('index.html', context) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 198, in render_to_response return HttpResponse(render_to_string(template_name, dictionary, context_instance, namespace, request), **kwargs) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 188, in render_to_string return template.render_unicode(**context_dictionary) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/template.py", line 454, in render_unicode as_unicode=True) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 829, in _render **_kwargs_for_callable(callable_, data)) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 864, in _render_context _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 890, in _exec_template callable_(context, *args, **kwargs) File "/tmp/mako_lms/c11f9c5f254718c770fcf021e95ac093/main.html.py", line 286, in render_body __M_writer(filters.decode.utf8(self.body())) File "/tmp/mako_lms/c11f9c5f254718c770fcf021e95ac093/marvel-theme-eucalyptus/lms/templates/index.html.py", line 54, in render_body runtime._include_file(context, (courses_list), _template_uri) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/mako/runtime.py", line 752, in _include_file callable_(ctx, **_kwargs_for_include(callable_, context._data, **kwargs)) File "/tmp/mako_lms/c11f9c5f254718c770fcf021e95ac093/marvel-theme-eucalyptus/lms/templates/courses_list.html.py", … -
Django rest framework get or create for
I start to create REST API for my web-application with Django and Django rest framework and I need one logic problem. There are entities Instruction and Tag. The user visit my service and create self Instruction and add exists Tag OR new Tag for it. I created my model seriallizer class with using PrimaryKeyRelatedField for relation Instruction<->Tag. But if I do POST for a new Instruction with new Tag I got error: "Invalid pk \"tagname\" - object does not exist.". I solved this problem with the overriding of the to_internal_value method in my field class. What is the best practice for solving this problem? It seems to me this problem is typical for web and REST API. My models: class Tag(Model): name = CharField(max_length=32, verbose_name=_("Name"), unique=True, validators=[alphanumeric], primary_key=True) def __str__(self): return self.name class Instruction(Model): user = ForeignKey(settings.AUTH_USER_MODEL, related_name='instructions', on_delete=CASCADE, blank=False, null=False, verbose_name=_("User")) title = CharField(max_length=256, verbose_name=_("Title"), blank=False, null=False) created_datetime = DateTimeField(verbose_name=_("Creation time"), editable=False) modified_datetime = DateTimeField( verbose_name=_("Last modification time"), blank=False, null=False) tags = ManyToManyField(Tag, related_name="instructions", verbose_name=_("Tags")) class Meta: ordering = ['-created_datetime'] # singular_name = _("") def save(self, force_insert=False, force_update=False, using=None, update_fields=None): n = now() if self.id is None: self.created_datetime = n self.modified_datetime = n super(Instruction, self).save(force_insert, force_update, using, update_fields) def … -
Django User Notification
I have two questions related to Django: 1) Is there a way to let the server execute some code (for example delete/create a model instance) based on a user related event (a user changed is account details, or a user placed a new "offer" resulting in a model instance creation)? 2) Is there a way to target a specific user with this code in question 1? Like a user accepted somebodies "offer" which results in a notification sent to the counterparty, appearing immediately on his screen? I would be pleased being guided into the right direction. -
Django in Docker using PyCharm
I'm trying to develop a database manager in Django and want to develop and deploy it in Docker. As my IDE, I'd like to continue using PyCharm, but I'm having trouble understanding how it interacts with Docker. I am new to Docker and its integration in PyCharm. I already tried using PyCharm's remote interpreter, but I have to activate the port forwarding manually (using Kitematic), since PyCharm does somehow not forward the exposed port automatically. I also tried using a "Docker Deployment" run configuration. However, I can't get requests to localhost:8000 to get through to the Django server. All I get are empty response errors. It would really help me to have an explanation of how PyCharm's two options (remote interpreter and docker deployment) really work and ideally have an up-to-date tutorial for setting up Django with it. Unfortunately I could only find outdated tutorials and JetBrain's help pages are either outdated or do not explain it in enough detail. Could someone help me out and guide me through this or point me to good resources? -
How to work on Python in iPad as if I'm working on a PC?
Is there any way to work with Python in iPad as I would on a PC? I will have quite some time with only my iPad and would like to continue with the same files. I currently use Jupyter notebook and Sublime text, but I don't mind any other alternative that works on iPad. I will be working on Python, Pandas, Django, Bokeh... just to give you an idea of what libraries I use. -
What to use instead of ng-change
I'm following along a Pluralsight course in Django and Angular development. I'm extremely new to both framework but have experience with other languages and frameworks. In the course we are shown how to use debounce as an option with a function that is called during ng-change. This function update uses http.put to send a put-request to a local REST API. However having worked with previous languages the idea of using a ng-change to send requests to a web service (even with debounce set to 500) seems to be a very silly idea since there will be a lot of unnecessary traffic being sent to the service. How could one do it better? I was trying to set the ng-click on the button to fire off the update, but it didn't seem to fire off the event for some reason... The debounce is missing from the code as I'm simply not sure if I should be using this approach.. card.html <div class="card" ng-hide="edit" ng-click="edit=true"> <h4> {{ card.title }} </h4> <span class="description"> {{ card.description }} </span> </div> <div class="card" ng-show="edit"> <div class="flex"> <label><strong>Title: &nbsp;</strong></label> <input type="text" ng-model="card.title" ng-change="update()" /> </div> <textarea ng-model="card.description" ng-change="update()" placeholder="Enter description here..."></textarea> <button ng-click="edit=false">Close</button> </div> card.directive.js: (function () … -
Django templates using JSON
Now, I'm using Django to create a website. In order to use JSON in HTML, I made it to response JSON to template. But when I use JSON data in HTML, The data hasn't appear. Here is my code: views.py def json_data(request): data = words.objects.all() return JsonResponse(list(data), safe=False) models.py class words(models.Model): word = models.CharField(max_length=20) value = models.FloatField(default=0) def __str__(self): return self.word url.py url(r'^api/json_data', views.json_data, name='json_data') template/result.html <script> var J = {% url 'json_data' %}; var JP = JSON.parse(J); document.write("JSON TEST"); for(var obj in JP){ document.write(obj, " : ", JP[obj], "<br>"); } </script> The result isn't show anything, even "JSON TEST". I can't understand why this happens. Which part did I make wrong? -
access a class attribute python django
I want to access a class attribute in a method which is in the class. But since this should be automatic, I use a for loop. The problem is how to append the attribute name that i get as a string to self so that I could access the attribute: self.str or self.'strthe code is here' -
Add methods to RelatedManager
I use the following property to access a ordered queryset from templates: class Question(models.Model): @property def descending_choice_set(self): """ Order choice_set by votes descending. """ return self.choice_set.order_by('-votes') But I would prefer to access it by question.choice_set.order_by_votes instead of question.descending_choice_set. For this behavior the RelatedManager must be overridden. How could this be implemented? -
How to render django-allauth templates
I could not understand as to why my django-allauth templates are not able to be rendered. I copied allauth directory to my project. I also have a bootstrap-themed catalog app which should be displayed after login. I expect signup and login forms from django-allauth to be displayed, and after login subsequently redirect to rendering bootstrap-themed catalog app's templates. In settings.py, among other required apps, I have added django-allauth modules after the catalog app in INSTALLED_APPS. INSTALLED_APPS=['catalog', 'allauth', 'allauth.account', 'allauth.socialaccount', ] Added Authentication Backends as: AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend" ) In settings.py , templates directory is set as: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'allauth/templates/account'),os.path.join(BASE_DIR,'catalog/templates/catalog')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'allauth.account.contextprocessors.account', 'allauth.socialaccount.contextprocessors.socialaccount', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'ecomstore.utils.context_processors.ecomstore', ], }, }, ] I let django-allauth which url to route to when login is successful. Add LOGIN_REDIRECT_URL = '/' Set the url routing in myproject as: urlpatterns = [ url(r'^accounts/', include('allauth.urls')), ] As indicated above, my question is why are django-allauth templates not rendered? -
Django templates: Show regroup groups in arbitrary order?
If we use the example from the django docs, cities = [ {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'}, {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'}, {'name': 'New York', 'population': '20,000,000', 'country': 'USA'}, {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'}, {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'}, ] How can I show the results grouped by an arbitrary sub/superset of countries in an arbitrary order? Can it be done in the template better than my current solution (see below), or is it better to manipulate the dataset in the view? e.g. say I want to show the groups in this order: ('Japan', 'USA', 'Australia') {% for country in country_list|dictsort:"grouper" %} doesn't work because: The desired order is not alphabetical I want to show "Australia" even if cities doesn't include any Australian cities I don't want to show India The reason for this that in my use case (not actually about countries and cities), I need to put my data into a table, grouped by ('Japan', 'USA', 'Australia') as columns, and grouped by some other field as rows. Currently doing it like this: {% regroup cities by country as country_list %} <ul> <li>Japan {% for country in country_list %} {% if country.grouper == "Japan" %} … -
How can I use django-import-export to import multiple users and their passwords?
I have figured out how to use import-export, but I don't know how to import users and cant figure it out. -
Django not searching for translation messages
Trying to figure out how Django i18n works. Already have read through the official and several other tutorials. The problem is that Django generates the .po file, but it doesn't contain messages from my models and Python scripts (well, I'm ready to live with the scripts, but models MUST be translated). Here are my settings: LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = ( ('ru', _('Russian')), ('en', _('English')), ) MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en' And here is the .po file ('locale' folder is located in the root of the project): # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-05-12 12:26-0400\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%" "10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%" "100>=11 && n%100<=14)? 2 : 3);\n" #: trackpost/settings.py:127 msgid "Russian" msgstr "" … -
parameter in url can not be read by form
I am reading the book “django by example” and try the example "bookmarks" in it. for the image book I am confused.Because the form can't access the parameters value from django. The code is below: views.py from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): if request.method == 'POST': form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) new_item.user = request.user new_item.save() messages.success(request,'Image added successfully') return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.POST) return render(request,'images/image/create.html',{'section':'images','form':form}) forms.py from django import forms from .models import Image import urllib from django.core.files.base import ContentFile from django.utils.text import slugify class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ('title','url','description') widgets = { 'url':forms.HiddenInput, } def clean_url(self): url = self.cleaned_data['url'] valid_extensions = ['jpg','jpeg'] extension = url.rsplit('.',1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('The given URL does not match valid image extensions') return url def save(self,force_insert=False,force_update=False,commit=True): image = super(ImageCreateForm,self).save(commit=False) image_url = self.cleaned_data['url'] image_name = '{}.{}'.format(slugify(image.title),image_url.rsplit('.',1)[1].lower()) #response = request.urlopen(image_url) response = urllib.urlopen(image_url) image.image.save(image_name,ContentFile(response.read()),save=False) if commit: image.save() return image create.html {% extends "base.html" %} {% block title %} Bookmark an image {% endblock %} {% block content %} <h1>Bookmark an image</h1> <img src ="{{request.GET.url}}" class = "image-preview"> <form action … -
Heroku can't find out that python is necessary
I have a project with the structure similar to what is described in Two Scoops of Django. Namely: 1. photoarchive_project is repository root (where .git lives). 2. The project itself is photoarchive. 3. Config files are separate for separate realities. The traceback and other info is below. The file runtime.txt is situated next to .git directory. That is in the very directory where git is initialized. The problem is: it can't even determine that python should be applied. Could you give me a kick here? .git/config [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] url = ssh://git@bitbucket.org/Kifsif/photoarchive.git fetch = +refs/heads/*:refs/remotes/origin/* [branch "master"] remote = origin merge = refs/heads/master [remote "heroku"] url = https://git.heroku.com/powerful-plains-97572.git fetch = +refs/heads/*:refs/remotes/heroku/* traceback (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project$ git push heroku master Counting objects: 3909, done. Delta compression using up to 4 threads. Compressing objects: 100% (3617/3617), done. Writing objects: 100% (3909/3909), 686.44 KiB | 0 bytes/s, done. Total 3909 (delta 2260), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. … -
Why isn't website receiving POST request?
I have been trying to create reload button, Once it gets clicked, with the support of javascript form is submitted: <div style="float: left;width:100%;height: 8%;background-color: #333333;min-height: 60px;"> <form id="rel_inv" name="reload_inventory" action="/account/" method="post"> {% csrf_token %} <input type="submit" name="reloadinv" value="inventory_reload" style="display: none;"></input> <div onclick="javascript:document.getElementById('rel_inv').submit();" name="reload_inv" style="width: 60px;height: 60px;cursor: pointer;text-decoration:none;display: block;"><img src="/static/Home/images/reload_i.png" style="width: 30px;height: 30px;margin-top: 25%;margin-left: 25%;"></div> </div> When div is clicked, page gets reloaded, However i still don't receive any POST requests in views.py - reload_inventory = "false" if request.method == 'POST': print("request has been received") if request.POST.get("reload_inv"): reload_inventory = "true" reload_inventory variable is sent to template via context. To check if variable was altered after sending POST request, I added alert to <script> - alert("{{ reload_inventory }}") Script was always alerting "false", and request.method was never POST when form was submitted... Final goal is to use {{ reload_inventory }} variable to get whether user requested inventory reload or not. If {{ reload_inventory }} was "true", Inventory function would be called and User's inventory would open up automatically. More simply, Once user clicks reload button, the page is reloaded with the new variable reload_inventory. If reload_inventory is "true", Inventory menu would be opened via javascript, If not, vice versa. So what could … -
Django limit the choices of a many to many relationship
I know the title says the question has been asked before but the situation is different. I have something called Agent: class Agent(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='agents') ... and a Group: class Group(models.Model): agents = models.ManyToManyField('agents.Agent', blank=True, related_name='groups') now with Django class based views (UpdateView maybe) I want create a view that a user can see only its agents and select only one of them to add it to a specific group. as far as I get was this @method_decorator(login_required, name='dispatch') class GroupAgentRegister(UpdateView): model = Group fields = ('agents',) template_name = 'register.html' context_object_name = 'group' def get_form(self, form_class=None): form = super(GroupAgentRegister, self).get_form(form_class) form.fields['agents'].queryset = self.request.user.agents.all() return form def form_valid(self, form): if self.object.agents.filter(user=self.request.user): form.add_error(None, ValidationError(u'Already Registered')) return super(GroupAgentRegister, self).form_invalid(form) return super(GroupAgentRegister, self).form_valid(form) the form rendering is fine except that I'm able to select multiple agents. but when I select a value and post it it replace the new selected agents with existing ones and it's not appended to the old ones. -
Django rest framework - nested serializer - retrieve valid records of nested serializer and error for invalid
I am retrieving multiple client records at a time using "RegistrationSystemSerializer" serializer here. class ClientRecordSerializer(serializers.Serializer): client_id = serializers.IntegerField() date_of_birth = serializers.DateField() class RegistrationSystemSerializer(serializers.Serializer): count = serializers.IntegerField() results = ClientRecordSerializer(many=True) If anytime anyone of client records is invalid then it is aborting entire process of extraction. i.e. suppose I have data like { "count" : 4, "results":[ { "client_id":"1234", "date_of_birth":"2012-02-06" }, { "client_id":"2345", "date_of_birth":"2013-02-06" }, { "client_id":"4567", "date_of_birth":"2014-02-06" }, { "client_id":"1239", "date_of_birth":"06-02-2017" }, ] } where "date_of_birth" of 4th client is in wrong format because a valid date can be only in "YYYY-MM-DD" format. If I apply above serializer in this data then it will not give me any data beacuse one of the nested record do not satisfy criteria. What I want is to get all three valid nested records from serializer but error for the fourth one. How to acheive the same using Django rest framework.