Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save django session before view ends
I'm sending an AJAX request every time the user checked an input. The request activates a view, and user's choice is added to the session. Later on at the view, I'll use the user's inputs to update an algorithm. The problem is, when a user clicks two inputs in a row (in less then a second), only one choice is saved to the session. request.session.modified = True is not helping. request.session.save() should have resolve the problem (http://kechengpuzi.com/q/s13748166), but unfortunately its not working.. def user_input(request): if request.method == 'POST': request.session.modified = True object_id = request.POST.get('object_id') request.session['user_input'].append(int(object_id)) request.session.save() print('input checked. ', request.session['affiliation']) return HttpResponse( json.dumps(response_data), content_type="application/json",) else: return HttpResponse( json.dumps({"failed": "request POST didn't go through"}), content_type="application/json") input: 1 2 3 4 (choose again without waiting for response) output: [1] [1,2] [1,2,3] [1,2,4] (I need it to be [1,2,3,4]) -
How to use gesture control to control my django apps?
Is their any library we can integrate with django app to add gesture control to my app like sending message, pause video close tab?? Please provide me details cause i am totly new to this topic! -
Django: Change admin interface
I just deal with Django and would like to create a program. My goal is that in the admin interface, you can only create questions and people but no responses. Only one reponse for each question/person-pair is possible. My goal is that in the admin interface, when I create or edit a person, that reponses to each question is created automatically and that I only have to choose "Agree", "Disagree" or "Neutral" then for every question in the admin menu for the person. The question now is how to edit the admin.py. Here, for your information, you can find my models. I hope someone can help me! from django.db import models class Question(models.Model): these_title = models.CharField(max_length=40) these_text = models.TextField(max_length=200) class Person(models.Model): name = models.CharField(max_length=50) information = models.TextField(max_length=300) website = models.URLField(blank=True) class Response(models.Model): question = models.ForeignKey(These, on_delete=models.CASCADE) person = models.ForeignKey(Kandidat, on_delete=models.CASCADE) possible_responses = ( (1, 'Agree'), (0, 'Neutral'), (2, 'Disagree'), ) response = models.IntegerField( choices=possible_responses, blank=True, null=True, ) -
How do I set initial form values of CreateView view using POST only (and not GET)?
Users click a button that takes them to a new form via a POST request, which contains a pk. This is used to pre-populate the new form with some extra data. No data has been saved to database at this point. I don't want to pass this pk along the URL so can't call view using GET. I've tried overriding the get_initial() method in CreateView but this only seems to be called after a GET request. I've also tried def post() which gives me easy access to the fields but means I have to write more code to handle form validation etc (which is handled automagically by the vanilla CreateView). So, what's the best way to handle rendering and saving of a form when both requests are made via POST? -
tastypie overid create_response() method
I tring to override tastypie create_response because I have some verification to do before sending response to user. this is my code: class MyNamespacedModelResource(NamespacedModelResource): def create_response(self , request , data): r = super(MyNamespacedModelResource , self).create_response(request , data , response_class=HttpResponse) # ... some treatements... return r And I have user NamespaceModelResource who work fine before. When I tring to add new user ( with post method) , I have got this error: create_response() got an unexpected keyword argument 'response_class' -
Cannot kill gunicorn processes
I am using a digitalocean ubuntu 14.04 vps. When I run sudo lsof -i:9000 I get varying results such as COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME gunicorn 23148 django 5u IPv4 51019 0t0 TCP localhost:9000 (LISTEN) or COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME gunicorn 23174 django 5u IPv4 51179 0t0 TCP localhost:9000 (LISTEN) gunicorn 23175 django 5u IPv4 51179 0t0 TCP localhost:9000 (LISTEN) where the number of gunicorn processes varies from 0-4, even if I run lsof immediately after the previous attempt. Simply running pkill gunicorn is failing, I believe because the PIDs are constantly changing (as shown above). How can I kill these processes permanently? If it makes a difference, I am user "root", and do not have a login for user "django" -
How to Parse JSON object in Django View from Ajax POST
I'm currently submitting data via a POST request using the below jquery ajax method and I'm successfully getting a return result in my console (see below) that displays the JSON request that was submitted to the server. However I CANNOT figure out how to parse the JSON object in my Django view. What do I write my view so I can Parse my JSON object and get a hold of "schedule_name" to execute the below command in my Django view. Please see a copy of my view below. Schedule.objects.create(schedule_name = Schedule) $.ajax({ type: "POST", url: "{% url 'addSchedule' building_pk %}", dataType: "json", data: {"json_items" : JSON.stringify(Schedule_Info)}, success : function(data) { $('.todo-item').val(''); // remove the value from the input console.log(data); // log the returned json to the console console.log("success"); // another sanity check alert("Sucess"); }, JSON output in console after submitting request json-items: "{ "nameOfSchedule":{"schedule_name":"Schedule"}, "Rooms":[ {"room_rank":"1","room_name":"Room 101 "}, {"room_rank":"2","room_name":"Room 102 "}, {"room_rank":"3","room_name":"Room 103 "}, {"room_rank":"4","room_name":"Room 104 "} ], "Users":[ {"user_name":"test1@yahoo.com"}, {"user_name":"test2@yahoo.com"} ] }" Django View def addSchedule(request, building_id): building_pk = building_id b = Building.objects.get(pk=building_pk) floor_query = b.floor_set.all() master_query = floor_query.prefetch_related('room_set').all() if request.is_ajax() and request.POST: data = request.POST ### Input the schedule name in the datase by parsing the JSON object … -
what are all the uses of manage.py in Django and why we should use it
hello everybody I am new in django and I have noticed that we use a lot of manage.py so can anyone gives me some information about it and how we can actully use it -
How to real-time check the django view operating process
Here is the thing, When I submit a form from template to view ,since the process of this view will cost a lot time. I don's think our user enjoy to wait. So, I want to this: when user click the submit button,the browser will redirect to a new page or just show a sub-page in the same window that can print the executing information. Before I post this question, I did a little research, looks like the celery can do this thing, am I right? If there is same problem already be asked in stackoverflow ,PLZ give me the link. Thank for your time! (English is not my mother language, so I don't know if we have any term to describe this function,if we do,PLZ give me a hint ) -
Django query filter parameters and Q
Im trying to make a django query filtering with one parameter and also using "Q" like this : variables = Indicator.objects.filter( type = constants_type_indicator_variable.variable, Q(current_state = constants_current_state.valid) | Q(current_state = constants_current_state.current_registered) | Q(current_state = constants_current_state.re_opened) | Q(current_state = constants_current_state.open_registered) ) But im getting this error in the first "Q" line : non-keyword arg after keyword arg If i only use the "Q" without filtering by that "type" field it works, but togheter it crashes... Any idea why ?, thanks in advance. -
Django - Get sum of two dates for unique fields
I have a model that has type(CharField), start_time(DateTimeField) and end_time(DateTimeField). I would like to calculate the sum of the total time (end_time - start_time) for each type in seconds using an ORM query. ie) type1, 2016-01-01T10:00:00Z, 2016-01-01T10:00:10Z type2, 2016-01-01T10:00:00Z, 2016-01-01T10:00:10Z type1, 2016-01-01T10:00:00Z, 2016-01-01T10:00:10Z OUTPUT: type1 = 20, type2=10 This is what I have so far for the query: latest_downtime_list.values('type').order_by('type').annotate(total=Sum('???')) The problem I am having is being able to take the difference of the two datetimes and converting it to seconds. -
Template url with Django class-based view
I'm working with class-based views in Django, and I've made a simple view in which I show all the posts of the blog class PostList(ListView): model = Post template_name = "blog/post_list.html" Now I need to put a link that redirects to the homepage (that is PostList). I worked with function-based views before; the function was def post_list(request): #code and the link in the template was <a href="{% url 'blog.views.post_list' %}">Homepage</a> I tried to put "PostList" instead of "post_list", but I'm clearly missing something here. How could I do that? -
Ubuntu 16.04 LTS Django CSRF cookie not set
I have Ubuntu(64-bit) on VirtualBox(5.0.10) for the test environment. When i try to execute an Ajax post request, i get 'Forbidden (CSRF cookie not set.)'. But the same post action in my web application works fine under the development environment on OS X. I doubt that it is a bug in the new Ubuntu release. Anyone has any idea why could this happen? Thanks. -
django-subdomains config localhost
I'm having trouble getting mine configured correctly. Have sites enabled and site domain for "SITE_ID = 1" (db object 1 domain) set too "mysite.app" I have these subdomains setup ROOT_URLCONF = 'mysite.urls' SUBDOMAIN_URLCONFS = { None: 'frontend.urls', # no subdomain, e.g. ``example.com`` 'www': 'frontend.urls', 'api': 'api.urls', } etc/hosts file 127.0.0.1 api.mysite.app 127.0.0.1 www.mysite.app 127.0.0.1 mysite.app api/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), ] api/views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('API') The frontend app urls and views is identical except for returning string "FRONTEND" in the HttpResponse object. I can tell django-subdomains is working becuase it does go to the "frontend" app when I hit "mysite.app:8000" vs the mysite.urls as seen in the root_url_conf. It displays "FRONTEND" But no matter what I do I can't get "api.mysite.app:8000" to hit the api urls file to display "API" Am I missing something? I'm very new to django. Any help is appreciated. Thanks. -
Django select only rows with duplicate field values and update them
I want to select all rows in a table from a Django migration were a particular field say name is duplicated. And update those values with a dynamic key so there are no duplicate anymore. -
Sign up View in Django with Bootsrap
I am a self learned programmer (beginner) trying to write a Login Class Based View. Through some tutorials I have been able to write a code which as follows: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views import generic from django.views.generic import View from .forms import UserForm class UserFormView (View): form_class = UserForm template_name = "signup.html" #display signup blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # Returns User objects if credentials are correct user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("home") return render(request, self.template_name, {'form': form}) Here is the forms.py: from django.contrib.auth.models import User from django import forms class UserForm (forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password' ] Now, I have a login.html page designed using bootstrap. I am now stuck how to integrate my views to the html page. Using {{ form }} in a plane html is working bt not in bootstrap designed page. Please help -
django admin foreign key display behavior
Lets say I have models: class Foo(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Bar(models.Model): foo = models.ForeignKey(Foo) Now if I go to django Bar's admin, I get dropdown field with Foo's names. I know that name comes from __unicode__ function in Foo class. How can I change that name displayed in admin? I don't want to modify my __unicode__ function. I would prefer something like: class Foo(models.Model): .... def unicode_for_admin_display(self): return 'some words ' + self.name -
How to upload and download files in HDFS and get url using DJango
I am designing video sharing website using Django and HBase as my database. I want to upload and download videos in HDFS and store it's URL in database. Now my site is using default file system and I store video file's URL's in format file:///pathToFile and use it to play videos in browser. I just want to use HDFS instead of default file system and I want to find a way to upload, download files in HDFS and get their URL's to play them in browser. I'm using DJango and my OS is Ubuntu. -
Trouble overriding the Django Admin template files
I have seen this question answered but I can't get it to work on my site. I have installed a site using Django 1.8 as I wanted to use the django-admin-bootstrapped plugin. I am also using the template provided by Heroku. What I would like to do is override at the very least the base_site.html to change the site title and page title. However, I have tried several locations for this file including the following: PROJECT ROOT |--templates |--admin |--base_site.html PROJECT ROOT |--templates |--admin |--<appname> |--base_site.html PROJECT ROOT |--<appname> |--templates |--admin |--base_site.html PROJECT ROOT |--<appname> |--templates |--admin |--<appname> |--base_site.html None of which work. I have the following in my settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], 'debug': DEBUG, }, }, ] I am just wondering if I am doing something fundamentally wrong or if I just haven't found the magic location for the templates folder (or order of folders etc). On a related note, is there anyway of debugging where the templates are being pulled from or is it just guesswork based on where they are supposed to be coming from? -
Django : Adding extra feature in the User model of auth App
I want to add extra feature in the User model of auth app but I don't want to get my hand dirty with the django source code or I don't want to create a new User model which extends the User model of auth app. Is it possible? if yes then how ? P.S I have seen django-eav but I want to permanently store the value of that feature in the database and display it in the admin site -
How to administrate template from django admin
I'm working on a site to better learn the Django-framework. I've currently set up views and links to template files to display content on the main page. In my views.py file I've added a dictionary that is displays the dict value for each key in in the index.html page when it gets rendered: views.py: def Index(request): projectmessage = { "projectMessage":"This is text from a dictionary value. written in views.py", "projectTitle":"Title from dict", "projectText": "Text from dict", } return render(request,'wbdev/index.html', context=projectmessage) Relevant lines in index.html: <h3>{{ projectTitle }}</h3> <p>{{ projectMessage }}</p> I'm wondering if this could be made visible on the django admin page so that I can change the dict text directly from the GUI. Could this be done or am I way off in the sense that this is not the intended for the django admin page? From what I've red django admin parses the models.py file to set up text fields and buttons. I've followed the official django tutorial and some of the "How to tango with django" book but I cant wrap my head around how I should proceed in getting the functions that I want. I'm sorry for the noob question. I will return to my … -
How can i show meal based on categories
I am using django rest framework for Rest API. I have restaurant, meal and meal category model. I want meal to be shown based on categories so that it will be appealing to show in an app where user can be shown meal based on the categories. Also filtering will be easy, i believe. For now i have designed my api as { "meal": [ { "id": 1, "name": "Mushroom drumstick", "slug": "mushroom-drumstick", "meal_category": 1 }, { "id": 2, "name": "Ham Cheesy Burger", "slug": "ham-cheesy-burger", "price": 180, "restaurant": 1, "meal_category": 2 } ], "name": "Kathmandu Fast Food Center", "slug": "kathmandu-fast-food-center", "address": "Koteshowor-35", "city": "Kathmandu", } But i want my json to look like this { "id":1, "name":"kathmandu fast food center", "slug": "kathmandu-fast-food-center", "address": "Koteshowor-35", "city": "Kathmandu", "meal_category":[ { "Non veg":[ "meal":[ { "name":"Ham Burger" }, { "name":"Chicken BBQ" } ] ], "Veg":[ "meal":[ { "name":"mushroom soup" }, { "name":"Aloo Drumstick" } ] ] } ] } My model design class Restaurant(models.Model): name = models.CharField(max_length=150, help_text="name of restaurant") slug = models.SlugField(max_length=150) class Meal(models.Model): restaurant = models.ForeignKey(Restaurant) meal_category = models.ForeignKey('MealCategory') name = models.CharField(max_length=120, help_text="name of the meal") slug = models.SlugField(max_length=120) class MealCategory(models.Model): name = models.CharField(max_length=80, help_text="name of the category of meal") slug … -
Django: Disable automatic language path prefix
I have a Django website with USE_I18N = True USE_L10N = True and added middleware: 'django.middleware.locale.LocaleMiddleware' Currently the website will add a language prefix (i.e. /en/) to my path in case the prefix is missing. example.com/page/ (301)=> example.com/en/page/ I want to disable that behavior. If the language prefix is missing in the users URL I want a clean 404. How can I do that? -
How to create django application without modifications in project settings.py
I want to make my django application really easy to install in the django project im working on. What I want to achieve is to install my package via pip eg. pip install pkg_form_gitrepo and add its name to INSTALLED_APPS in the project settings.py and add one line in the project urls.py. However now I have to add bunch of code to my django project settings.py eg. edit MIDDLEWARE_CLASSES, REST_FRAMEWORK and MEDIA_ROOT variables ect. also add 5 or more ulrs in project ulrs.py. This is what makes my application not so easy to install. I wonder where (if possible) I should those config changes. -
Django crispy-forms disable browser's 'Save Password' popup
I have a Django ModelForm (with a password input), rendered by the crispy-forms module. Every time I submit the form, browser asks if it should remember the password. Anyway it is only a ModelForm (not a LoginForm). How to get rid of this popup? I found a possible solution here: Disable browser 'Save Password' functionality ...but how to add a attribute to a crispy-form (not to a input)?