Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can not find the directory which is installing
In my Mac, I use sudo easy_install the Django: aircraftdeMacBook-Pro:~ ldl$ sudo easy_install django Password: Searching for django Reading https://pypi.python.org/simple/django/ Best match: Django 1.11.2 Downloading https://pypi.python.org/packages/c0/31/4bffd9183066eea645430114419c30b030b599320da8246701b81c6a78d2/Django-1.11.2.tar.gz#md5=f089f1f86d25f2b78f6cf36478d4edd1 Maybe the Django is large to install, but I stuck in there too much time, so I want to use su -du Django_directory to look if it is installing. But I use whereis django, I get nothing: aircraftdeMacBook-Pro:~ ldl$ whereis Django aircraftdeMacBook-Pro:~ ldl$ How can I find it in my Mac? -
How to search value from database as per user input using Python and Django
I need one help. I need to search value from table as per user input using Python and Django. I am explaining my code below. home.html: <form method="post" action="{% url 'search' %}"> {% csrf_token %} <label>Search by Room name: </label> <input name="rname"> <input type="submit" value="Submit"> </form> Here I need to search value as per roomname and my model file is given below. class Meeting(models.Model): lname = models.CharField(max_length=200) rid = models.IntegerField() roomname = models.CharField(max_length=200) noseats = models.IntegerField() projectorscreen = models.CharField(max_length=200) videoconf = models.CharField(max_length=200) Here I need when user will type any text and click on search button as result search string related record will fetch. view.py: def search(request): per=[] if request.method == 'POST': rname=request.POST.get('rname') return render(request,'booking/home.html',{'people': per}) Here I also need to return the total record to people key. Here also I need 3 type of search which are equivalent to following sql search. 1- $searchKey=request.POST.get('rname'); $keyword = '%'.$searchKey.'%'; "select * from Meeting where roomname like '".$keyword."'"; 2- $searchKey=request.POST.get('rname'); $keyword = '%'.$searchKey; "select * from Meeting where roomname like '".$keyword."'"; 3- $searchKey=request.POST.get('rname'); $keyword = $searchKey.'%'; "select * from Meeting where roomname like '".$keyword."'"; Please help me. -
Django sort topics into first letter blocks with pinned items at the top
I am trying to make a page that displays all the boards on my forum site and sorts them into blocks based by the first letter. The output looks something like this: A Apple Attack B Banana etc... {% regroup boards|dictsort:"name" by name.0 as item_letter %} <ul> {% for letter in item_letter %} <h2>{{ letter.grouper|title }}</h2> {% for i in letter.list|dictsort:"name" %} <li>{{ i.name }}</li> {% endfor %} {% empty %} <p><a href="/boards/new">Create a board</a></p> {% endfor %} </ul> However some boards are pinned and should appear at the top of the block: A (pinned) Attack Apple etc... The main issue here is the code above overrides the order of the queryset (as it is currently designed to) and pinned items do not appear at the top of their blocks. How should I rework this? boards = Board.objects.all()..order_by('-pinned') -
How to parse .json within Django app in views.py
I am having json file in my django app. i want to know the easy method to parse json ? I tried one method but i think there is better solution will avail than this, json_file_path = os.path.join(BASE_DIR, 'static', "utils/config/AccessConf.json") data = open(json_file_path, 'r') parsed_json = json.loads(data.read()) print parsed_json this code worked for me . but is there any better solution available? -
Django Network Error (tcp_error)
I am using the django-admin, but i keep getting this response header: Connection:keep-alive Content-Length:0 Content-Type:text/html Date:Tue, 20 Jun 2017 09:53:32 GMT ETag:"56138860-0" X-Content-Type-Options:nosniff X-Frame-Options:SAMEORIGIN X-XSS-Protection:1; mode=block and Request URL:http://52.43.93.333/real-admin-interface-2017/mooimom_id/product/85/change/?_changelist_filters=o%3D-1 Request Method:POST Status Code:503 Service Unavailable Remote Address:52.43.93.333:80 Referrer Policy:no-referrer-when-downgrade and this frontend output Network Error (tcp_error) A communication error occurred: "Operation timed out" The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests. You may wish to try again at a later time. For assistance, contact your network support team. I am using Apache, Ubuntu and AWS. My RDS is external AWS machine (not the same EC2 machine). I have already changed the Timeout to 999 and KeepAliveTimeout to 15 in the apache.conf, but i still keep getting this error only for few objects that have a lot of data to save. -
django split settings with inheritance: symbols not defined
I'm trying to split the django settings into base and testing, so that pytest can run with a specific module (e.g. ue a simpler password hashing algorithm or remove password validators). This is the settings module settings ├── __init__.py ├── base.py └── testing.py init.py: from settings.base import * base.py is the usual settings.py and testing.py should overwrite some specific values of base.py: from settings.base import * print(INSTALLED_APPS) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'different-static') ./manage.py runserver works because it's using DJANGO_SETTINGS_MODULE='settings', which goes to init and reads base. However, If I export DJANGO_SETTINGS_MODULE='settings.testing', it can't find symbols like INSTALLED_APPS or STATIC_ROOT. NameError: name 'INSTALLED_APPS' is not defined Any hint on what I'm doing wrong? -
Django ORM extremely slow
my Database had only 2 rows. and when execute below query. taken time was about 2 seconds. start = datetime.datetime.now() parks=Park.objects.filter(id='test') end = datetime.datetime.now() print('parks : '+str(parks)) print('duration : ' + str(end-start)) sql query on mysql command line was 0.1s. django shell was also fine. could you help me my case? -
How to authenticate part of API view, request type based in Django rest framework
I am new to Django rest framework and struggling with api view token authentication. Following is my code @api_view(['POST']) @authentication_classes((TokenAuthentication,)) @permission_classes((IsAuthenticated,)) def create_user(request): """ API to add user """ if request.method == 'POST': request_body = request.data['users'] created_user_ids = [] # Data must be provided and validated validation = UserSerializer(data=request_body, many=True) validation.is_valid(raise_exception=True) created_user_ids.append(validation.save()) return Response( data={'users': [{'id': user_id} for user_id in created_user_ids]}, content_type='json', status=status.HTTP_201_CREATED ) I need to apply tokenauthentication on part of the view not on whole view. Authentication should be based over type of the request. For example If type is POST there should not be any authentication but for the same view if request came in as PUT, GET, PATCH etc it should authenticate request. -
django rest framework CSRF
can anyone explain how we can use csrf protections. My frontend is written in Angular2. Frontend and backend is hosted on different server, how can we access that cookie in client side? -
Creating a dynamic table form in django
I'm currently working on a project to help create dynamic surveys. I'm trying to create a table which will provide the answerer (the person answering the survey) different options, where each column is an option. I want it to look something like this. The main part is that there is a select button at the bottom at each column (except the first one). For now, I thinks its enough that the column number which is selected, will be saved. Since the table will vary in sizes, my idea is that the user that makes the survey, will input something as 'el1, el2, el3; el4, el5, el6; el7' And that this will create a table like this. I know its very fragile, but I'll handle that later. The number of rows and columns will vary, but one can assume that the input is given correctly. I've done some research trying to find a solution that works, and some of the options I've thought about is: Subclassing a widget, and modify it to represent a table. This way I can simply print the field as shown in template below. Pass a variable to the template, which represents a form. This way I … -
Django Many to Many def dont work
i have a problem, pls tell how fix this, deadline soon why this def dont return anything? VIEW def subs_to_event (request,pk=None): event = Event.objects.filter(pk=pk) Event.make_sub(request.user,event) return redirect('events:cards') Model have error recently-get() returned more than one Event -- it returned 2! I fix this with try-catch,now error disappear but def dont do anything MODEL class Event (models.Model): name = models.CharField(max_length=100) date = models.DateField(default='') dicript = models.CharField(max_length=50, default='Описание отсутствует') category = models.ForeignKey(Category,on_delete=models.CASCADE) adress = models.TextField(max_length=300) user = models.ForeignKey(User,related_name="creator",null=True) subs = models.ManyToManyField(User, related_name='subs',blank=True) @classmethod def make_sub(cls, this_user, sub_event): try: event, created = cls.objects.get_or_create( user=this_user ) except cls.MultipleObjectsReturned: sub_event = cls.objects.filter(user=this_user).order_by('id').first() sub_event.subs.add(this_user) -
Django admin doesn't show checked checkboxes in data edit option
class DataAddForm(forms.ModelForm): CostPerformance = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=DataAdd.CostPerformance_Choices) BusinessImpact = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple(),choices = DataAdd.BusinessImpact_Choices) Datasizerange = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple(),choices = DataAdd.Datasizerange_Choices) Endgoal = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple(),choices =DataAdd.Endgoal_Choices) class Meta: model = DataAdd fields = '__all__' This is forms .py class DataAddAdmin(admin.ModelAdmin): form = DataAddForm inlines = [ChoiceAdmin] list_display = ('id','CostPerformance','BusinessImpact','Datasizerange','Endgoal') admin.site.register (DataAdd,DataAddAdmin) This is admin.py I have defined choices in DataAdd modelWhile adding data on admin On editing an object it doesn't show the existing checkboxed values in the admin formWhile editing -
Twisted Web serving Django project
I have fresh Django project without any application just the defaults (e.g. admin) wsgi.py import os, sys from django.core.wsgi import get_wsgi_application sys.path.append('MY_DJANGO_PROJECT_PATH') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MY_DJANGO_PROJECT.settings") application = get_wsgi_application() I run my Twisted Web server within MY_DJANGO_PROJECT_PATH and the server start on port 8080. cd MY_DJANGO_PROJECT_PATH twistd -n web --wsgi=MY_DJANG_PROJECT When I open it to the browser (http://127.0.0.1:8080/), I got an error WSGI application error File "/Library/Python/2.7/site-packages/Twisted-15.5.0-py2.7-macosx-10.12-intel.egg/twisted/web/wsgi.py", line 315, in run appIterator = self.application(self.environ, self.startResponse) exceptions.TypeError: 'module' object is not callable Does anyone help me with this? Thanks in advance. -
Extracting Queryset of latest records based on filtered columns in Django
I searched solution for my problem from stackoverflow and django documentation, but no luck. This table below is very simplified version of my sqlite table in Django app: Table User: +----+------+---------+ | ID | User | Type | +----+------+---------+ | 1 | A | Admin | | 2 | B | Admin | | 3 | C | User | +----+------+---------+ Table Userlog: +----+---------+------------+------------+ | ID | User_ID | Login type | Login date | +----+---------+------------+------------+ | 1 | 1 | Desktop | 2017/01/01 | | 2 | 1 | Server | 2017/01/05 | | 3 | 2 | Desktop | 2017/01/11 | | 4 | 1 | Server | 2017/02/03 | | 5 | 3 | Desktop | 2017/02/09 | | 6 | 2 | Server | 2017/02/21 | | 7 | 1 | Desktop | 2017/03/18 | | 8 | 3 | Desktop | 2017/03/31 | +----+---------+------------+------------+ I tried different approaches like that: q = Userlog.objects.values('login_date').annotate(last_date =\ Max('login_date')).filter(pc_type='Desktop', user='Admin', login_date=F('last_date')) But cannot extract latest dates for filtered columns. I need Django QuerySet expression to get the result below: (Latest login dates of Admins logged using Desktop) +----+---------+------------+------------+ | ID | User_ID | pc_type | login_date | +----+---------+------------+------------+ | … -
Creating file and saving in Django model (AttributeError?)
I have a huge string that I want to save as a file in a Django model. In order to do that, I have written the following code: with open("new_file", 'w') as outfile: outfile.write(myString) outfile.close() my_obj = Model_Type(obj_name = name, my_file = outfile) my_obj.save() This raises an error, '_io.TextIOWrapper' object has no attribute '_committed' but after searching online for solutions, I've come to a dead end. Any advice will be gratefully appreciated! Thanks! -
Django Replace choices value in ModelForm Widget
i have a model that let me to choice between some predefined values. in models.py class Customer(models.Model): GENDER = ( ('m' , 'Male') , ('f' , 'Female') ) PersonGender = models.CharField(max_length=20,choices=GENDER) and i have a ModelForm to handle my form , it's ok , but i want to define another ModelForm To Change "GENDER" values for some reasons. i define another ModelForm in forms.py GENDER = (('male' , 'Male' ), ('female' , 'Female') ) class MySecondaryForm(forms.ModelForm): class Meta: model = Customer fields = '__all__' widgets = { 'PersonGender': forms.Select(choices=GENDER) } with this configuration Drop-down menu not changes to new values. i can fix it with below configuration: GENDER = (('male' , 'Male' ), ('female' , 'Female') ) class MySecondaryForm(forms.ModelForm): PersonGender = forms.ChoiceField(choices=GENDER) class Meta: model = Customer fields = '__all__' with above configuration Drop-down values changes to my new , but i want to know how can i change it inside the Meta Class in "widgets" ? -
Django and Pymongo - Take multiple inputs and update a single field in all the objects
Update multiple documents in django-mongodb with user inputs I have a form which is meant to update all the price attribute of the objects in the product_details collection of my mongoDB.It is like Bulk price updating feature.I have tried few but finding it difficult. Please suggest the method to do so in django. How can I update the price of multiple products using the same form and view? price.html <form class="col s12" action="{% url "bulk" %}" method="POST">{% csrf_token %} <button class="btn waves-effect waves-light" type="submit" name="action">Update<i class="material-icons right">cloud</i> </button> {% for r in result %} <div class="col s6 m7"> <div class="card horizontal"> <div class="card-image" > <img class ="materialboxed" width="650" src="{{r.ppro}}" style="width:100px; height:150px; max-width:100%; max-height:100%;" > </div> <div class="card-stacked"> <div class="card-content"> <p style="font-size:15px;">{{r.ptitle}}<br>{{r.price}}</p> </div> <div class="card-action"> <div class="input-field col s4"> <input id="input_text" type="text" name=price value="{{r.price}}" data-length="10"> <label for="input_text">Price</label> </div> </div> </div> </div> </div> {% endfor %} </form> </div> views.py def bulk_price(request): product_list= user_db.product_details.find({"shop_id":request.session["_id"]}) user_data = user_db.store_details.find_one({"_id":request.session["_id"]}) if product_list is not None: return render(request,'price.html',{'result':product_list,'status':user_data['status']}) return render(request,'price.html') mongoDB structure of product_details object -
Django Migration 'NoneType' object has no attribute 'lower'
I'm trying to make an oAuth store using the model: from django.db import models from oauth2client.contrib.django_util.models import CredentialsField from south.modelsinspector import add_introspection_rules class oAuth(models.Model): siteid = models.CharField(max_length=100L, primary_key=True) credential = CredentialsField() add_introspection_rules([],["^oauth2client\.contrib\.django_util\.models\.CredentialsField"]) When I run schemamigration + migrate I keep getting : FailedDryRun: ! Error found during dry run of '0001_initial'! Aborting. Traceback (most recent call last): File "/ruler/ruler-rt/src/env/local/lib/python2.7/site-packages/south/migration/migrators.py", line 175, in _run_migration migration_function() File "/ruler/ruler-rt/src/env/local/lib/python2.7/site-packages/south/migration/migrators.py", line 60, in <lambda> return (lambda: direction(orm)) File "/ruler/ruler-rt/src/doubleclick/migrations/0001_initial.py", line 14, in forwards ('credential', self.gf('oauth2client.contrib.django_util.models.CredentialsField')(null=True)), File "/ruler/ruler-rt/src/env/local/lib/python2.7/site-packages/south/db/generic.py", line 47, in _cache_clear return func(self, table, *args, **opts) File "/ruler/ruler-rt/src/env/local/lib/python2.7/site-packages/south/db/generic.py", line 356, in create_table for field_name, field in fields File "/ruler/ruler-rt/src/env/local/lib/python2.7/site-packages/south/db/generic.py", line 665, in column_sql field = self._field_sanity(field) File "/ruler/ruler-rt/src/env/local/lib/python2.7/site-packages/south/db/mysql.py", line 273, in _field_sanity type = self._db_type_for_alter_column(field).lower() AttributeError: 'NoneType' object has no attribute 'lower' I actually managed to get the model to migrate correctly but I can't seem to recreate that. -
Django app can not find json file in the same directory
My json file is in the same directory of view.py file However, when I open the html in browser, the IO error happens. When I run view.py through pycharm, it works fine. -
Getting results of dropdown lists
im a beginner in using Django. I need to create a Game for my University project. I have some different questions, which have always 4 different answers. The answers will once have different values for the player, but im not that far, yet. I did this in a dropdown list: class Player(BasePlayer): Antwort1 = models.IntegerField( choices=[ [1, 'Mitfahrgelegenheit'], [2, 'BlaBlaCar'], [3, 'FlixBus'], [4, 'Mitfahrzentrale'], [5, ' '] ], default=5) Antwort2 = models.IntegerField( choices=[ [1, 'Mitfahrgelegenheit'], [2, 'BlaBlaCar'], [3, 'FlixBus'], [4, 'Mitfahrzentrale'], [5, ' '] ], default=5) Antwort3 = models.IntegerField( choices=[ [1, 'Mitfahrgelegenheit'], [2, 'BlaBlaCar'], [3, 'FlixBus'], [4, 'Mitfahrzentrale'], [5, ' '] ], default=5) and so on... How can I get the results out of the choices? If I put {{% form.answer1 %}} in my result page, the result in fact is the answer, but shown as a drop down list. thanks for your help and best whises, Julian -
Django order_by for BooleanField to create "pinned" items
I am trying to create a post list that shows pinned posts at the top. However applying order_by to a BooleanField does not work. posts = Post.objects.all().filter(visible=True).order_by('pinned') How do I sort the queryset to have pinned items first? -
Change date format from mm/dd/yyyy to dd/mm/yyyy in openedx studio course details
How can I change the format of the date in Openedx cms (studio), in course details? The URL of the details page of a course: {hostUrl}:18010/settings/details/{CourseId} This format is used only in the view. When the settings are saved the data is send in other format: yyyy-MM-ddTHH:mm:ssZ Sample: end_date:"2017-07-09T00:00:00Z" I have tryed changing the format in edx-platform/cms/static/js/views/course_info_update.js $(this.dateEntry(event)).val($.datepicker.formatDate("dd/mm/yy", new Date(targetModel.get('date')))); And redeploying but nothing happens. -
Django query alias on field values
I have a charfield in a model, call it char_field = CharField(allow_blank=True, max_length=10) now assume there are 3 entries in this table and the values of char_field are 'val1', '', ''. that is only one row has a value rest two have empty string. now if someone provide a string(any random string) which doesnt exist in anyrow for this field then i have to write a query which return last 2 rows i.e.empty string value row. pseudo logic would be: if (input == 'some_random_string_which_doesnt_exist_in_anyrow') then return all rows where char_field == '' # empty string now My question is it even possbile in a django query or even a raw SQL query? -
Django RestFramework Foreign key Serializer Error
Models.py class List(models.Model): name = models.CharField(max_length=100) def __str__(self): return '%s' % (self.name) class Card(models.Model): lis = models.ForeignKey(List, related_name="card_lists") title = models.CharField(max_length=100) description = models.CharField(max_length=100) story_points = models.IntegerField(null=True, blank=True) business_points = models.IntegerField(null=True,blank=True) def __str__(self): return '%s,%s' % (self.title,self.description) Serializers.py from rest_framework import serializers from .models import List,Card class ListSerializer(serializers.ModelSerializer): class Meta: model = List fields=['id','name'] class CardField(serializers.RelatedField): def to_representation(self, value): return { 'List_id': value.id, 'name': value.name } def to_internal_value(self, data): return List.objects.get(id=data) class CardSerializer(serializers.ModelSerializer): lis = CardField(read_only=True) class Meta: model = Card fields = '__all__' # exclude = ('id') Error:- 'List' object has no attribute 'lis' -
Show a form at specific parameter value
I was wondering: is it possible to return an object when a parameter is true? I have multiple forms in django, and i want to show Form1 when the parameter in the url is set to 1. It won't work for now when i do this: def get_form(request, step): if parameter == 1: form = get_form_form1(request) return HttpResponse(form) get_form_form1(request) is defined like a normal form script, returning a template.