Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get instance name in bound method?
I made an 'Club' class, and several instances. then I set student as foreign key for club. like this. in models.py class Club(models.Model): club = models.CharField(max_length=30) def __str__(self): return self.club class Student(models.Model): student = models.CharField(max_length=30) clubs = models.ManyToManyField(Club, related_name='inclubs') class_s = models.ForeignKey(Class, on_delete=models.CASCADE) isfilled = models.BooleanField(default=False) atclub = models.ForeignKey(Club, on_delete=models.CASCADE) def __str__(self): return self.student def atclub(self): return self.atclub I want to get which club student involved. so I wrote, in my results_view.html <head> <meta charset="UTF-8"> <title>동아리 신청 확인</title> </head> <body> <ul> {% for student in a %} <div style="text-align:center"> <li>{{student.student}}--{{student.atclub}}</li> </div> {% endfor %} </ul> <a href="{% url 'club:index'%}">Go to the main</a> </body> </html> but the result is, (page view) (student name)--<bound method Student.atclub of <student name>> I want to get club name instead of bound method. How can I solve this? -
Django Transaction Management with DEBUG = True
Transactions are working correctly in production environment (django 1.9 + Ubuntu + PosgreSQL) but thay have no effect in development environment with DEBUG = True. E.g. with transaction.atomic() do_stuff() raise Exception() Changes made by do_stuff() are still there in dev environment but not in production environment. I can't find any explanation of this behaviour in django docs. Why is this happening? -
django : How to create & call a Constructor on every request?
I want to call a request validator method every time a POST request is called. So Code I want to have like : import validator class ViewClass(): def __CONSTRUCTOR__(self, request): validator.validate() def request_function_one(request): if request.method == 'POST': return HttpResponse('Request 1 is Valid') def request_function_two(request): if request.method == 'POST': return HttpResponse('Request 2 is Valid') How can I achieve this using Python & django ? -
use javascript sessionStorage in django
i want pass session values from javascript to django views.py i tried with this code // foo.js sessionStorage.setItem('foo', 'foo') With this code, I found Chrome to store the value in the session storage. and then i move to django views.py # views.py def bar(reqeust): print(request.session['foo']) # raise keyError this code raise key error. How do I pass session values from .js to views.py? -
Python virtualenv no module named django
In my ec2 machine i need to run a django project, I do the below thinks: Install python 3.4: sudo yum install python34 ok, now i create a virtual enviroment for python 3: virtualenv -p python3 .venv3 at this point activate my venv: source .venv3/bin/activate all done! Now i have to install django: pip install django the installation was ok but when i try to check my django version: python -c "import django; print(django.get_version())" system return the error "No module name django found" How is possible? In my machine there is also python 2.7 installed. I try outside the virtualenv to remove django with: sudo python -m pip uninstall django all done, but in my .venv3 enviroment the issue is still present. How can i fix the problem? thanks in advance -
Returning the related field using in views.py Django
I have the following code: models.py class Model_ItemName(models.Model): item_name = models.CharField(max_length = 50) # e.g. "Power Ranger" class Model_Cart(models.Model): item_name = models.ForeignKey(Model_ItemName) views.py Model_Cart.objects.select_related("item_name").values("item_name")[0]["item_name"] # <---- Expect to return "Power Ranger" My goal is to retrieve the value of the "item_name" (say "Power Ranger") from the Model_ItemName. I was referring to this post for the solution, but my existing code returns the id number of that "item_name" instead. What am I missing here? -
Decorator to override save to write in Multiple databases
I am planning to have models in our application to write into two databases. I wanted to write a decorator to use it for all models. I am using the below code class save_multi_db(models.Model): def __call__(self, cls): class Wrapped(cls): def save(self, *args, **kwargs): redis_connection = redis.Redis(connection_pool=settings.MAPPING_REDIS_POOL) if int(redis_connection.get('write_to_db')): super(cls, self).save(using='prod') super(cls, self).save(using='default') else: return cls.save() return Wrapped I have classes like below @save_multi_db() class ModelA(models.Model): #model A class MobelB(ModelA): class Meta: db_table = 'name' This is perfectly working fine if I am using the decorator to a single model. But in the same models.py if I use the decorator on another model. I am getting the below error (fields.E300) Field defines a relation with model 'Wrapped', which is either not installed, or is abstract. -
uploaded files but showing "[ ]" instead of uploaded files
New to django filehandling, all the process is going well with no errors but no files are stored after uploding. it stored the value "[ ]" in document column insted of uploded document. I uploded only one document. view:- class Build_Kb(FormView): template_name = "template.html" form_class = Build_form success_url = '/thanks/' def form_valid(self, form): title=form.cleaned_data.get("title") knowledge=form.cleaned_data.get("knowledge") document=self.request.FILES.getlist('document') share_with=form.cleaned_data.get("share_with") instance = Buildkb.objects.create(title=title,knowledge=knowledge,document=document) for user in share_with: instance.share_with.add(user) instance.save() messages.success(self.request, "Knowledge saved succesfully") return redirect("/") model class Buildkb(models.Model): title=models.CharField(max_length=500,blank=True) knowledge=models.TextField(blank=False) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) share_with=models.ManyToManyField(User) -
Mocking pymongo for unit testing
I have a simple application in Django REST, I am using Pymongo to connect to MongoDB. My directory structure is like this:- appauth/ ├── apps.py ├── controllers.py ├── databases │ ├── initialize_databases.py │ ├── __init__.py │ ├── mongo_connector.py │ ├── redis_connections.py │ ├── redis_connector.py ├── handlers │ ├── handlers.py │ ├── __init__.py ├── helpers │ ├── helpers.py │ ├── __init__.py │ ├── permission_loader.py ├── __init__.py ├── model │ ├── __init__.py │ ├── users.py ├── tests.py ├── urls.py I have initialised my Mongo connection in mongo connector and imported it to initialise_databases. Then I am importing it from there throughout my application as and where I need it. My main problem is, when I want to unit test, how do I specifically mock the db code. For ex: def login() //code// last_filled = db.UserSurvey.find_one({'user_id': user_id}) //code// db.UserSecurityData.count({'user_id': user_id}) user_role = db.User.find_one({'_id': user_id}) In my tests, if do something like @patch('pymongo.collection.Collection.find_one') @patch('pymongo.collection.Collection.update') def test_03_validate_login(self, mocked_update, mocked_find): mocked_find.return_value = user_findone_return //user_findone_return is a variable mocked_update.return_value = user_findone_return res = self.usr_obj.validate_login(user.email, user.password) self.assertEqual(res["gender"],'Male') self.assertEqual(res["password_expires_in"],45.0) The test works perfectly with correct return values.But this seems to mock all find_one calls. My question is how to I mock different collections and their queries. My DB settings:- … -
can't find why this exception occure?
I am using django==1.11.5 and python2.7 and donno how to fix this problem, can anyone help me? yes I know that there a lot of answers for this quiestion, but all of them doesn't work in my case ./manage.py runserver django-configurations version 2.0, using configuration 'BaseConfiguration' Unhandled exception in thread started by <function wrapper at 0x109c1b1b8> Traceback (most recent call last): File "/Users/sabo/projects/envs/pillows/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/sabo/projects/envs/pillows/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/sabo/projects/envs/pillows/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/sabo/projects/envs/pillows/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/sabo/projects/envs/pillows/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/sabo/projects/envs/pillows/lib/python2.7/site-packages/django/apps/registry.py", line 78, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant -
What I do wrong? Django objects filter
I try show post only from 30 days. What I do worng? @login_required def dashboard(request): days = 30 posts = Post.objects.filter(Post.publish < timezone.now() - timedelta(days=days)) #posts = Post.objects.all() return render(request, 'account/dashboard.html', {'section': 'dashboard', 'posts': posts}) error TypeError at /account/ unorderable types: DeferredAttribute() < datetime.datetime() -
why {%extends %} , {%block body_block%},{%endblock%} seen in webpage in browser?
enter image description here here {%extends %} and {%block body_block%},{%endblock %} are seen but they shouldn't .How to fix this? -
Django translation not working on production
I've made translation of the site for different cities and it works fine on dev machine. But when published on production server it didn't show any translation. But it shows available languages and current language correctly. Here's my settings.py: USE_I18N = True USE_L10N = True LANGUAGES = [ ('ru-spb', _('SaintP')), ('ru-msk', _('Moscow')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'nordicsite/locale'), ) Here's template for language check: {% load i18n %} {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {{server}}<br/> {% trans 'Test 2' %}<br/> {{LANGUAGE_CODE}}<br/> {% for language in languages %} {{ language.name_local }} ({{ language.code }})<br/> {% endfor %} <br/> {% for path in paths %} {{path}}<br/> {% endfor %} Output for dev: Тест 1 Питер Тест 2 Питер ru-spb Русский (ru) Русский (ru) /*****/nordicsite/locale Output for production: Test 1 Test 2 ru-spb Русский (ru) Русский (ru) /*****/nordicsite/locale What can be wrong? -
Need input help in a Django Project
I know my question is not related to 100% coding but your input will help me a lot. Im creating a Leave Management Project where user can submit leave application to admin and admin can accept or reject it and user would get confirmation message. Problem is how can i make user send something to admin with in the site! and that to a responsive message! Should i use Postman? But that for messaging purpose! Please be giving input on this matter. -
Documenting django rest framework API end points using sphinx
I just got started with sphinx, went through it's documentation I was able to document my class models in models.py which is pretty much straight forward. The next thing I want to do is documention in views.py. Does sphinx have a standard way of documenting HTTP methods? if so kindly share snippets on how to implement such. -
Redirecting is not properly in django admin panel
I have a method that has the task of redirecting the page in the admin panel from: http://127.0.0.1:8000/admin/events/event/ to: http://127.0.0.1:8000/admin/events/event/?date__lt=2018-6-11 I got an information instead of page: The page isn’t redirecting properly Here is my code: admin.py def changelist_view(self, request, extra_context=None): if not request.method != 'GET': url = '{}?date__lt={}'.format(reverse('admin:events_event_changelist'), date.today()) return HttpResponseRedirect(url) Please some hint where can be a wrong code. -
`django-constance` in the distribution, it do not generate the data.
django-constance in the distribution, it do not generate the data. This is my distribution MySQL. there is no data in it. this is the configurations of my constance in settings.py CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_IGNORE_ADMIN_VERSION_CHECK = True CONSTANCE_ADDITIONAL_FIELDS = { 'coupon_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': ((0, "时+分+秒"), (1, "时+分"), (2, "时"), (3, "忽略")) }], } CONSTANCE_CONFIG = { '站点名称': ('南京诗远启', '网站标题'), # key: (default, help_text) 建议全部使用str格式作为value.统一点 '站点描述': ('南京诗远启', '站点描述'), '电子券固定代码': ('DreamGo', '电子券固定代码'), '电子券时间': (0, '电子券时间格式', 'coupon_select'), '分配短信清零时间': (1, '分配短信清零时间'), 'PayPal支付密钥': ('abcdefghijklmn', 'PayPal支付密钥'), } CONSTANCE_CONFIG_FIELDSETS = { '站点设置': ('站点名称', '站点描述'), } I also use python3 manage.py migrate database to migrate the table. But why the constance_config table do not have the configuration data? -
convert list of class objects into json in python or django
my_objects = [] my_objects.append(Needed("bye",9)) my_objects.append(Needed("tata",8)) my_objects.append(Needed("hi",10)) i have list of object(example 5 objects in list) like this class Needed: def __init__(self, name, number): self.name = name self.number = number and i need to convert this into json order by count like below { "results":[ { "name":"hi", "number":"10" }, { "name":"bye", "number":"9" }, { "name":"tata", "number":"8" }, ........... ........... ] } so how to achieve this in django -
Check to see if a JSON object value contains a phrase - django
I have a django project. I implimented Firebase into the project. Firebase created and returns objects in JSON format. Now, I want to have a search system through existing users and return an object that has all of the stored username values from the list and then display all of the results. Here is a sample of a Firebase JSON object format: OrderedDict([ ('info', { 'bio':'jogn from the office', 'company':'MySplit', 'dob':'1993-03-23', 'first_name':'jim', 'gender':'M', 'last_name':'helpert', 'phone':'+19515394856' } ), ('location', { 'city':'Mis Viejo', 'state':'CA', 'street':'27806 cheller', 'zip_code':98892 } ), ('status', { 'active':'1', 'group':'dev', 'premium':'1' } ), ('username', 'jimhelpert' ) ]) I want to search and return an object with all the usernames that contain jim I cant find how to make the query that would return all objects with username that contains the phrase... here is the view.py: user_id = request.session['uid'] user_profile = database.child('users').child(user_id).child('profile').get() print(user_profile.key()) print(user_profile.val()) print(user_profile) print(type(user_profile)) parameters = { 'user_profile':user_profile.val(), } return render(request, 'users/user_home.html', parameters) -
Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<post_id>\\d+)/$']
I am going through a Django tutorial and getting this error when trying to edit posts in my blog app. I use Django Version: 2.0.6 and Python Version: 3.6.5. models.py from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=100) text = models.TextField() def __str__(self): return self.title urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^new_post/', views.new_post, name='new_post'), url(r'^edit_post/(?P<post_id>\d+)/$', views.edit_post, name='edit_post'), ] A template that causes the error in line 3 - edit_post.html. The error message highlights {% url 'edit_post' post.id %} {% block content %} <form action="{% url 'edit_post' post.id %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name="submit">save changes</button> </form> {% endblock content %} A template (index.html) with a link to edit_post.html {% block content %} <form action="{% url 'new_post' %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name="submit">Make a new post</button> </form> <ul> {% for post in posts %} <li> {{ post.id }} - {{ post.title }} <p>{{ post.text }}</p> <a href="{% url 'edit_post' post.id %}">edit post</a> </li> {% empty %} <li>No posts have been added yet.</li> {% endfor %} </ul> {% endblock content %} views.py def edit_post(request, post_id): post = BlogPost.objects.get(id=post_id) text = post.text title = post.title if … -
One way background notification from server to client (Django to tell Angular 4 what to happened at the back)
Been looking at this for quite sometime. First, it is not a two way communication. Just the server have to send 1,2 or 3 to the client whenever something happens at the back. Full Scenario: Certain employees are allowed to do something that generates XML/JSON files at the back. The rest of the employees make use of those newly created, updated data. The problem is the client might retain a copy even though it has been updated because I get copy of latest generated files when a user logs in or manually checks for any newly generated data. Now, I want the backend to notify the front-end that there was a change and fetch new content silently. Current Solution: My current solution is to check for changes every hour and notify the user to logout-login or manually fetch data with timers like this: import 'rxjs/add/observable/timer' import { Observable } from 'rxjs/Observable'; Observable.timer(0,3600000).subscribe(() => { this.fileConsumerService.checkNew().subscribe(data=> { if(data==true){ alert('New data has been generated. Please click on Update button or relogin') } }) }); While it is working, I am not really comfortable with the solution. Sometimes, the check happens much later after data was pushed, thus employees work on older data. … -
Get item from Django database model
Hello I'm new to django and i'm trying to get the item from the database. The problem is the item is saved as a list in django. And item[i] is not helping either. Please help me figure it out how to get the data in shell i have tried for x in NewsItem.objects.all(): print(x.tag) this will print ['babi kutil', 'babi hutan', 'babi liar', 'hutan indonesia'] ['ibu aniaya anak'] ['pilkada serentak 2018', 'bandung', 'nurul arifin', 'pilwalkot bandung 2018'] ['narkoba di surabaya', 'bnnp jatim'] ['pilkada serentak 2018', 'banten'] But i want to get each item not as a list. -
Django form data headers
Django form data is send in the POST header, but around stackoverflow it is advised to store the actual data in the body. can someone explain the difference, and tell me why django does it differently/explain me what I misunderstood. -
displaying selected json keys in django template
I have a django project. I also have a json ojbect that I want to pass to the template and display selected information from the object in the template itself. Here is the object (user): OrderedDict([ ('info', { 'bio':'brother of founder', 'company':'MySplit', 'dob':'1993-03-23', 'first_name':'hani', 'gender':'M', 'last_name':'jandali', 'phone':'+19515343666' } ), ('location', { 'city':'Mission Viejo', 'state':'CA', 'street':'27806 Soller', 'zip_code':92692 } ), ('status', { 'active':'1', 'group':'dev', 'premium':'1' } ) ]) This is the template that I have: <p> {{ user_profile.location.street }} </p> -
How to secure a created directory in django so that only django app can access it
I've created a directory in Django 'mydir' and have few files in it. How to secure these files so that only django can access it and no one else?