Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display user name and surname in main page after Django login
Instead of the user, I want to display the user name and surname in the main page, after the log in. But my user model is extended by another form which holds the name and surname fields. {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} This will display the user name. But my second form has a OnetoOneField with the User model. I tried something like user.form2.name but it's not a solution. -
Why an ajax call doesn't give is_ajax()=True?
My template.html: ... <button class="btn btn-success" onclick="save_post('publish')">Publish</button> ... My javascript.js: function save_post(action) { var tag_string=document.getElementById('id_tags').value; if (action=='publish' || action=='draft') { var url_post='/blog/post_new/' } else { var url_post='/blog/post_edit/' }; $.ajax({type: 'POST', url: url_post, data: { tagstring: tag_string, action: action }, success: function (lista) { //code } }); }; My views.py: @staff_member_required def post_new(request): context_dict=[] if request.method == "POST": if request.is_ajax(): #this gives False #code ... else: form = PostForm() return render(request, 'blog/post_edit.html', context_dict) My views is called by the url (browser), then the button call a javascript function and it call (with ajax) again the same view, this time with request.method = "POST" but request.is_ajax() gives False. Also should I use preventDefault() somewhere? Thank you -
How to stream large (~200mb) dynamically generated response in django?
I have to generate a csv response from a large data set. The csv data is generated dynamically and rendered using djangorestframework-csv. But due to large size of the response the memory shoots up drastically and the browser also hangs in handling such large response. class ImageLabelAnnotations(APIView): permission_classes = (IsAuthenticated, ) renderer_classes = (csvRenderer.CSVRenderer,) def get(self, request): result= [] < database queries to generate the response > return Response(result) Sending the file as attachment doesn't help either. I need to somehow stream this response to browser while keeping the memory in check as well on the server side. -
Admin class not defined in django
i try add my model into admin. but error run while i create class for model.admin i don't know why my class read is not defined. i using python 3.6 and Django 2.0 from django.contrib import admin from .models import Post # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') raw_id_fields = ('author') date_hierarchy = ('publish') ordering = ['status', 'publish'] admin.site.register(Post, PostAdmin) here my debug error : "C:\Program Files\JetBrains\PyCharm 2017.3\bin\runnerw.exe" C:\Users\FIANUAENA\PycharmProjects\mysite\venv\Scripts\python.exe C:/Users/FIANUAENA/PycharmProjects/mysite/manage.py runserver 8000 Unhandled exception in thread started by .wrapper at 0x05E1EE88> Traceback (most recent call last): File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\core\management__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\contrib\admin__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, … -
The view doesn't work same name template in diffrence app
The two apps are in the one project this is two apps tree ├─posts │ ├─templates │ │ modify.html │ │ write.html │ ├─users │ │ │ ├─templates │ │ bookmark.html │ │ index.html │ │ modify.html │ │ my_comment.html │ │ my_posts.html │ │ profile.html │ │ signin.html │ │ signup.html The modify.html make trouble one work but the other Thing doesn't work -
Django Intermediate Model User
I'd like to create a model in which a user owns a certain number of shares in multiple companies. It seems like I should use the Django intermediate model relationship, but I'm not sure how to apply an intermediate model to the built-in Django User Model. Right now, companies have a ManyToMany relationship with shareholders (users), how do I add number of shares to each specific company-shareholder relationship? class Company(models.Model): name = models.CharField(max_length=200) shareholder = models.ManyToManyField(User, blank=True) -
In a nested class in Python what's the best way to access the outer classes parent class?
I have a non trivial Django system and there's a lot of Meta class inheritance going on. Boiled down to it's essence that looks like this: class Base: class Meta: pass class Child(Base): class Meta(Base.Meta): # this pass class GrandChild(Child): class Meta(Child.Meta): # this pass The problem with this is it's easy to overlook the lines marked "this" when making changes to the inheritance structure. This is fundamentally the same problem as with Python2's super requiring the name of the parent class. And like with that what I'd like is a way of writing those lines in a way that doesn't explicitly reference the outer classes base. Something like: class Base: class Meta: pass class Child(Base): class Meta(super.Meta): # this pass class GrandChild(Child): class Meta(super.Meta): # this pass Is there anyway of doing this? -
Django serving content based on group
I have a survey app which consists the following model classes: Survey, Response, Question and Answer. What I want to do is restrict Questions based on the Group a user belongs to. I've read through the Django templates docs (amongst others), but they don't explain how to do this. My thoughts are to add a field to the model "Question" for "type" (of user). So for example, Type=1 Questions might be visible to everyone, while Type=2 Questions would be visible to a subset of users (specified by the Group they are added to). Is this the right approach? Are there any projects doing something similar I can take a look at (I haven't been able to find any). Any help would be appreciated. Thanks in advance. -
Django admin console keeps listing permissions that were removed from the model
I have a Patient model for which, by default, the 'add_patient', 'change_patient' and 'delete_patient' permissions are added to the database. I also wanted to add a 'view_patient' but I accidentally specified it as 'app.view_patient' because my app is called 'app' and in any other place but the models you need to put this identifier in front of the permission string in order to indicate a class-level permission. Turned out that this permission was internally translated to 'app.app.view_patient' because Django automatically attaches the 'app' identifier for model permissions. I realised my mistake so I tried to change the permission to just 'view_patient' but for some reason the admin console keep listing the previous permission even though I ran several model migrations where there is no additional permissions specified on the Patient model. I was wondering whether anyone has encountered this problem before, where the admin page does not sync well with the newly migrated models. Cheers, -
Append query result to another queryset
I have two models: class A(models.Model) username = models.CharField(max_length=128, primary_key=True) last_login = models.DateTimeField(db_index=True, default=get_default_datetime) class B(models.Model) user = models.CharField(max_length=25) email = models.CharField(max_length=25) My goal is to create a list with username, email, last_login for all 'username' in model A that match to 'user' in model B. So it looks like this: username email last login user1 s@abc.com 2018-01-01 00:01:01 user2 t@cde.com 2017-12-30 05:01:00 ... ...... ... and so on. I did this in my view.py: class userListView(ListView): template_name = 'user.html' context_object_name = 'user_list' def get_queryset(self): users = A.objects.values('username') for user in users: qs1 = A.objects.values('username', 'last_login') qs2 = B.objects.filter(user = user).values('user', 'email') queryset = sorted(chain(qs1, qs2)) return queryset However, this does not work. I only get one entry. What am I doing wrong here? I also tried to append qs2 to qs1. That did not work either.I was getting error that qs1 or qs2 has no attire of 'append'. -
Django REST Framework - nested serializer validation?
So I have models like so: class Leaderboard(models.Model): pass class Column(models.Model): leaderboard = models.ForeignKey(Leaderboard, related_name="columns", on_delete=models.CASCADE) related_columns = models.ManyToManyField(self) And serializers like so: class ColumnSerializer(ModelSerializer): related_columns = serializers.PrimaryKeyRelatedField(queryset=Column.objects.all(), many=True) class Meta: model = Column fields = ('leaderboard', 'related_columns',) class LeaderboardSerializer(ModelSerializer): children = ColumnSerializer(many=True) class Meta: model = Leaderboard fields = ('columns',) So what I'd like to do is verify that any columns added to related_columns for ColumnSerializer already belong to its Leaderboard parent. I have tried many times to access the Leaderboard or a Leaderboard ID (like by manually specifying id in fields) during creation of the ColumnSerializer to verify, but LeaderboardSerializer` is not initialized before Column so I cannot verify the details. Basically, I want to modify queryset=Column.objects.all() to be queryset=self.instance.leaderboard.columns.all() However I don't have access to Leaderboard inside Column. For example, if I access self.parent.instance/initial inside ColumnSerializer it is None until inside Leaderboard.validate_columns(). One thing I've thought of is to just do the validation on the Leaderboard side, but I still think it should be "doable" to do this validation inside Column in case I ever want to edit those directly, without first going through a Leaderboard... -
How can I get access to an objects attribute when it is part of a list of objects
I am using the python-keystoneclient module within a Django project basically to learn. The environment: python 3.6.3 django 1.10.8 python-keystoneclient 3.14.0 I have a query to the api that returns a list of objects projects = keystone.projects.list() for p in projects: print(p) http://172.16.100.10/identity/v3/projects/1c1a662d73c04f92acce6c50fb75dc3e'}, name=alt_demo, parent_id=default> http://172.16.100.10/identity/v3/projects/311f76914cba43e18bfb416c72d8ad5e'}, name=demo, parent_id=default> http://172.16.100.10/identity/v3/projects/4d4dabcc39ac4323a8665ba01efa65d7'}, name=PROJ-BOB3, parent_id=default, sandbox=True, telephone=+99999999999, tos=on, username=bjones> http://172.16.100.10/identity/v3/projects/916daf2b642944729d284643b355e5a2'}, name=service, parent_id=default> http://172.16.100.10/identity/v3/projects/ab80834046864705b47bfd9478cfe715'}, name=swiftprojecttest4, parent_id=efc1097d56b047099645cbdb53a89c13> http://172.16.100.10/identity/v3/projects/bad74eb9e68546208232310dab8144d0'}, name=admin, parent_id=default> http://172.16.100.10/identity/v3/projects/d52a43a6f1cb408592b02aaa3dbb618d'}, name=invisible_to_admin, parent_id=default> http://172.16.100.10/identity/v3/projects/f9c8ca81dbd34c07bce3b4bf19af102c'}, name=swiftprojecttest2, parent_id=default> http://172.16.100.10/identity/v3/projects/fbdb58e9120c49348a0eb5dfb7e984d0'}, name=swiftprojecttest1, parent_id=default> As you can see the second item in the list has more attributes than the rest When I use the following for p in projects: print(p.id) I get a result like this 1c1a662d73c04f92acce6c50fb75dc3e 311f76914cba43e18bfb416c72d8ad5e 4d4dabcc39ac4323a8665ba01efa65d7 916daf2b642944729d284643b355e5a2 ab80834046864705b47bfd9478cfe715 bad74eb9e68546208232310dab8144d0 d52a43a6f1cb408592b02aaa3dbb618d f9c8ca81dbd34c07bce3b4bf19af102c fbdb58e9120c49348a0eb5dfb7e984d0 If I try to do this for p in projects: print(p.createddate) I get this error ~/.virtualenvs/sandbox/lib/python3.6/site-packages/keystoneclient/base.py in __getattr__(self, k) 505 return self.__getattr__(k) 506 --> 507 raise AttributeError(k) 508 else: 509 return self.__dict__[k] AttributeError: createddate I was expecting this to print one line with True. if I use ipython and run p. with tabs I see that the other atrributes are not available In [100]: p. delete enabled human_id is_loaded name set_loaded description get id links NAME_ATTR to_dict domain_id HUMAN_ID is_domain manager parent_id update So the other … -
Importing Django Custom User Model From Another App Model
So I have an app called profiles and it has model named Profile from poros.abstracts.models import Model from django.db import models from poros.users.models import User class Profile(Model): user = models.OneToOneField( to=User, on_delete=models.CASCADE, related_name='profile', ) the Profile model has a field name user which has OneToOneField relationship with my Django custom user User. The problem now is it returns me an error: ImportError: cannot import name 'User' How can I solve this issue? -
ImportError: cannot import name '_remove_dead_weakref'
yesterday updated my ubuntu 17.04 to ubuntu 17.10. any comments? appear when I try to runserver in pycharm. #django project. bash -cl "/home/encuentrum/venv-encuentrum3/bin/python /usr/share/pycharm/helpers/pycharm/django_manage.py check /home/encuentrum/GitLab/encuentrum3/ENCUENTRUM/packers_" Traceback (most recent call last): File "/usr/share/pycharm/helpers/pycharm/django_manage.py", line 5, in from pycharm_run_utils import adjust_django_sys_path File "/usr/share/pycharm/helpers/pycharm/pycharm_run_utils.py", line 4, in import imp File "/home/encuentrum/venv-encuentrum3/lib/python3.6/imp.py", line 19, in from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name File "/home/encuentrum/venv-encuentrum3/lib/python3.6/importlib/init.py", line 57, in import types File "/home/encuentrum/venv-encuentrum3/lib/python3.6/types.py", line 171, in import functools as _functools File "/home/encuentrum/venv-encuentrum3/lib/python3.6/functools.py", line 23, in from weakref import WeakKeyDictionary File "/home/encuentrum/venv-encuentrum3/lib/python3.6/weakref.py", line 12, in from _weakref import ( ImportError: cannot import name '_remove_dead_weakref' -
How to deploy djang app in google cloud
I created a website Django app in pycharm. Now I have registered free trial version of Google cloud platform. I have searched the internet, but not getting how to deploy the website. -
what is more efficient way to use redis the node js side or the python side?
I have a project which has 3 side. Python for rest api, node js for web socket and lastly client side with react. Where I have to use redis? What is the best practice? This is chat application. Thanks for all answer. -
Where to stock simple calculations to show to the user in Django's folders
Sorry for the dumb question, but I wanted to know where I should put my calculations to show to the user. I need to put the % of the user's life left. I need to calculate it. Where do I put the calcul ? The % is displayed in my base template (in static folder). Should I put this in my account app models or something like that ? Thanks you ! -
How to return User's username from ForeignKey in __unicode__ return?
I am trying to return User's username in Debt class unicode method. class UserProfile(models.Model): user = models.OneToOneField(User) balance = models.FloatField(default=0.0) def __unicode__(self): return self.user.username // this one works class Debt(models.Model): who = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="who") whom = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="whom") ammount = models.FloatField(null=True) def __unicode__(self): return self.who.user.username //this one does not work However, return self.who.user.username gives invalid literal for int() with base 10: 'Julius' error. Where is the mistake? -
How to improve the code on this safety check
I have some stores, which sells products (each store have it's own), and I was implementing a safety-check to prevent one store from messing around other store's products (in case the user is some kind of smarty-pants). Let's say the user have permission to edit this product (Id 75) http://localhost:8000/produtos/edit/75/ But not this one (Id 100) http://localhost:8000/produtos/edit/100/ I was hoping to create a "_check_permission" method that could be used both in get and post, but seems like I still need to call another "if permission is not None" to actually trigger message to the user. Any suggestions on how to improve this? Seems like a lot of code redundancy, and not very pythonic (less code). def get(self, request, produto_id=None): produto = Produto.objects.get(pk=produto_id) permission = self._check_permission(produto, request) if permission is not None: return permission form_editar_produto = EditarProdutoForm( prefix='produto', instance=produto, ) return render(request, self.template, locals()) def post(self, request, produto_id=None): produto = Produto.objects.get(pk=produto_id) permission = self._check_permission(produto, request) if permission is not None: return permission form_editar_produto = EditarProdutoForm( request.POST, prefix='produto', instance=produto, ) if (form_editar_produto.is_valid()): revenda = Revenda.objects.get(pk=request.user.id) form_editar_produto.save(revenda, commit=False) return redirect("produtos") else: return render(request, self.template, locals()) def _check_permission(self, produto, request): if produto not in request.user.produto_set.all(): return HttpResponseForbidden("Produto indisponível nesta revenda.") -
How to Include while loop inside template file in Django
I need to render block of html code 5 times in template file. Like in php I tried something like below, {% extends 'stories/base.html' %} {% block body %} <h1>This is rating page</h1> <section class='rating-widget'> {% with count = 0 %} {% while count < 5: %} <div class='rating-stars text-center'> <ul class='stars'> <li class='star selected' title='Poor' data-value='1'> <i class='fa fa-star fa-fw'></i> </li> <li class='star selected' title='Fair' data-value='2'> <i class='fa fa-star fa-fw'></i> </li> <li class='star selected' title='Good' data-value='3'> <i class='fa fa-star fa-fw'></i> </li> <li class='star selected' title='Excellent' data-value='4'> <i class='fa fa-star fa-fw'></i> </li> <li class='star selected' title='WOW!!!' data-value='5'> <i class='fa fa-star fa-fw'></i> </li> </ul> </div> {% count += 1 %} {% endwhile %} {% endwith %} </section> But I couldn't get expected result. It gives me syntax error "'with' expected at least one variable assignment". Is this possible or what is the proper way to implement this kind of loop in django? -
Debug in Django (show what's happening in the background)
Is there a way to properly debug in django. I mean to show everything not only when something doesn't work right. For now my console (Powershell with manage.py runserver) only shows me the urls (pages) where I am. Here is an example: Can I show whats happening in the background. I.e. I submit a password reset. The console only shows how the next page is called and not what it actually did. I tried django_debug_toolbar, but I am not sure if its something I need. -
Displaying content in home page in django
I am following the Django tutorial. I have a /films page and /films/id page displaying successfully. I would like to divert slightly from the tutorial and one step of this is to display the content which is currently appearing in /films in the website home e.g. http://127.0.0.1:8000/ I currently have: index.py: def index(request): latest_film_list = Film.objects.order_by('-pub_date')[:5] context = {'latest_film_list': latest_film_list} return render(request, 'films/index.html', context) index.html: {% if latest_film_list %} <ul> {% for film in latest_film_list %} <li><a href="/films/{{ film.id }}/">{{ film.title }}</a></li> {% endfor %} </ul> {% else %} <p>No films are available.</p> {% endif %} films/urls.py: urlpatterns = [ path('', views.index, name='index'), # # ex: /films/5/ path('<int:film_id>/', views.detail, name='detail'), # # ex: /films/5/results/ path('<int:film_id>/results/', views.results, name='results'), # # ex: /films/5/vote/ path('<int:film_id>/vote/', views.vote, name='vote'), ] mysite.urls.py urlpatterns = [ url(r'^films/', include('films.urls')), url(r'^admin/', admin.site.urls), ] I realise I probably just need to add/adjust the films/urls.py file but have been unsuccessful so far. Home currently displays a 404. -
Good templating choice for working with django and node
I've got some html templating needs that I'd like to be able to serve out of node & django. This looks like a good choice, and I switch to jinja2 on the django side: https://github.com/sstur/jinja-js Any other choices? -
django app with uwsgi taking long response with requests.post within the views
I'm using uwsgi to serve my django application and within my views.py I use requests.post to connect to another server endpoint Running on manage.py runserver, the views working fine but it takes forever when I use uwsgi I'm pretty sure requests.post who causing this, as I comment my line that has requests.post, its working okay Following are my uwsgi.ini [uwsgi] env = DJANGO_SETTINGS_MODUL=project.settings harakiri = 1200 # respawn processes taking more than 20 seconds max-requests = 5000 daemonize = ./maspa_backoffice.log master = true workers=16 vacuum=true Is it possible this is because sort of thread locking between requests and uwsgi? -
Create a property that work similar to Django fields
I created a function that instantiates a property that encapsulates some communication: def orion_field(name, field=None): def getter(self,): return self.get(name) def setter(self, value): self.set(name, value) return property(getter, setter) I want to include it in my Django models in a similar way to Django fields: class KPI(models.Model): orion_id = models.CharField(primary_key=True, unique=True, max_length=10) data = JSONField(blank=True, default={}) name = orion_field("name") def set(self, attribute, value): self.data[attribute]= value # Ugly code removed that send stuff to server def get(self, attribute): # Ugly code removed that may(or may not) bring stuff from server return self.data[attribute] The communication code works great but I noticed that these new properties work at class level. orion_entity1 = KPI() orion_entity2 = KPI() orion_entity1.name = "Babar" print(orion_entity2.name) >>> Babar I suppose at some point Django converts class fields insto instance fields. I searched their code but I got lost.