Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render a ChoiceField value in a Template?
I'm having trouble getting a ChoiceField value in my template. Here's the form definition (a single radio select field that describes if the product is "fancy" or not): CHOICES = ( (True, "Yes"), (False, "No"), ) class ProductCreateForm(forms.ModelForm): fancy = forms.ChoiceField( required=True, label="Is this product fancy?", widget=forms.RadioSelect(), choices=CHOICES, ) When I do this in the shell, I'm getting None: from django.template import Template, Context p = Product.objects.first() form = ProductCreateForm(instance=p) t = Template("{{ form.fancy.value }}") c = Context({"form":form}) p.fancy is False >>> True print(t.render(c)) >>> None Even if I try to just render the field, none of the radio buttons are selected: t = Template("{{ form.fancy }}") c = Context({"form":form}) print(t.render(c)) >>> #showing only the two input tags for brevity >>> <input type="radio" name="basic" value="True" required id="id_basic_0" /> >>> <input type="radio" name="basic" value="False" required id="id_basic_1" /> Is {{ form.field.value }} the right way to get a ChoiceField value out of the form? Why isn't it rendering the radios with the correct checked attribute on {{ form.fancy.0 }}? I'm using django 1.11. -
Accessing model/class information within context processor
In my Django app I have a series of generic views (create, update, delete, detail, list) that most of my actual views inherit from. All of these views add a number of pieces of useful information to the context (the singular and plural names of the model, the urls for creating, listing, etc). But the views more-or-less all duplicate the same code. For that reason I'd like to move these things to a context processor and remove the code duplication. My issue is, I can't seem to determine the things I would need from the request that's passed to the context processor (ie: if I could access the model instance, model class, form class, etc), then Id be fine. The code below shows what the get_context_data looks like within the views - how would I replicate this in a context processor? Thanks. def get_context_data(self, **kwargs): """Passes context variables to the HTML templates.""" context = super(CodexAnonDetailView, self).get_context_data(**kwargs) context['model_name'] = model_ngettext(self.model, 1) context['model_name_plural'] = model_ngettext(self.model, 2) context['object_create_url'] = reverse('%s:%s_create' % (resolve(self.request.path).app_name, self.model.__name__)) context['model_list_url'] = reverse('%s:%s_list' % (resolve(self.request.path).app_name, self.model.__name__)) -
Check all varibales if one of them contains number
I need to check all variables if one of them contains number 6 def func(a, b, c, d, e, f): If True print Yes If False print No -
AWS ECS - Ngnix link to container configuration?
I have two containers for my application, one which serves my Django app and one for nginx. I have linked the containers via the link feature in the task. I'm having issues with my ngnix config connecting to the linked container. my ngnix config as per below: upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /static/; } location /media { # your Django project's media files - amend as required alias /media } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://web/; } listen 8000; server_name localhost; } and when I try to run the config root@a31f68f75c28:/# /etc/init.d/nginx start 2017/09/19 09:52:35 [emerg] 448#448: host not found in upstream "web:8000" in /etc/nginx/conf.d/django.conf:3 nginx: [emerg] host not found in upstream "web:8000" in /etc/nginx/conf.d/django.conf:3 looking at the error nginx can't see the inapt container. here is the task definition { "networkMode": "bridge", "taskRoleArn": null, "containerDefinitions": [ { "volumesFrom": [], "memory": null, "extraHosts": null, "dnsServers": null, "disableNetworking": null, "dnsSearchDomains": null, "portMappings": [], "hostname": null, "essential": true, "entryPoint": null, "mountPoints": [], "name": "it-app", "ulimits": null, "dockerSecurityOptions": null, "environment": [], "links": null, "workingDirectory": "/itapp/itapp", "readonlyRootFilesystem": null, "image": "*****.dkr.ecr.eu-west-1.amazonaws.com/itapp", "command": [ "bash", "-c", "python manage.py collectstatic --noinput && … -
How Do I Add Images To My Blog Posts?
I am new to Django and followed djangogirls.com's tutorial that makes a blog. In the model of a (blog) post there is a TextField that contains a post's text. However, I am trying to make it so that I can put a variable number of pictures within that text, and at any position within it. I wrote html into a blog's text and used template tags to turn off auto-escaping. This allowed me to include images wherever I wanted, but I want to know if there is a better way to implement this? Even if someone can point me in the right direction, it would be greatly appreciated. I'm happy to post code, I just didn't know what code would be helpful. -
Reducing redundant codes in serializers.SerializerMethodField()
my post serializer returns top comments and the number of comments I marked the redundant code below. class PostDetailSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField() comment_count = serializers.SerializerMethodField() class Meta: model = Post fields = ( ... 'comments', 'comment_count', ) # showing the most recent comments def get_comments(self, obj): content_type = obj.get_content_type << object_id = obj.id << comments = Comment.objects.filter_by_instance(obj)[:2] << return CommentSerializer(comments, many=True).data # showing the number of comments def get_comment_count(self, obj): content_type = obj.get_content_type << object_id = obj.id << comments_count = Comment.objects.filter_by_instance(obj).count() << return comments_count It works fine by itself but I don't want to query N x 2 rows whenever it hits the PostDetailSerializer expected output is below ..... "comments": [ { ... "content": "Edited!", ... }, { ... "content": "New wwaa!", ... } ], "comment_count": 4 -
How can I compare real data in db and ideal ones?
I wanna test,and compare top 3 real data in db and ideal ones. I wrote in test.py like from django.test import TestCase from app.models import User # Create your tests here. class UserModelTests(TestCase): def test_is_empty(self): saved_user = User.objects.first(3) self.assertEqual(saved_user, XXXX) saved_user has 'name': Tom,'user_id': 1,'nationarity': America, 'dormitory':'A', 'group': 3 'name': Bob,'user_id': 2,'nationarity': China, 'dormitory':'B', 'group': 4 ・・・・,so I wanna compare Tom&1&America&A&3 are typed by myself and real db data.I really cannot understand how to write in place of XXX.Data I wanna compare is 4 kinds I confused.How should I write this? -
How do I assign the Permissions Groups of the Djanog admin site to each user?
Five types of permissions are required in the current project. General user, super user (developer), staff (employee), car dealer 1, car dealer 2 Normal users and super users are the same users you know. The staff should inherit the permissions of the Permissions Groups named 'Staff' by assigning Permissions Groups called 'Staff' on my Django admin site. example) class StaffAdmin (admin.ModelAdmin): def has_add_permission (self, request): return request.user.groups.filter (name = 'Staff'). exists () def has_change_permission (self, request, obj = None): return request.user.groups.filter (name = 'Staff'). exists () def has_delete_permission (self, request, obj = None): return request.user.groups.filter (name = 'Staff'). exists () I've heard that you can solve this problem with ModelAdmin through multiple explorations. However, to apply the above example, the user must have the groups attribute. However, because all users must be identified by their mobile_number, I can use AbstractBaseUser custom, so how can I put the groups (the permissions groups of the Django admin site that I directly assigned permissions on) to the user? Finally, is it possible to divide the five permission levels into a single user model class? If you can solve these two problems, please save. I look forward to the answers of your esteemed global … -
django db substring match, keeping substrings in db
What I'm trying to do is keeping a list of id in my DB with a field "level" associated with each of it, example: id:abcd123->level:1 id:xyzw9876->level:2 id:qwerty12->level:1 ecc.. so I can check the current id I'm working on which level corresponds. But some of the ids should be a regular expression, example: id:abc*->level 2 so if a query for the id abcd432 I get a match and get the corresponding level (2 in this case). How could I do in Django with Postgres DB? -
Django Rest Framework JWT
I have done all the tutorials from Django-Rest-Framework and read the JWT documentation. Everything works fine, but now I don't know what to do further, how to use JWT to authenticate the user. I can't find an example using both and I'm not referring to curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' just for testing. What do I have to do further? -
Can I convert my hardcoded request.post to suds lib?
Is it possible to convert a hardcoded request.post to use with suds-jurko instead? Or is there any better solution out there? Preferrable with good decumentation/examples. How a harcoded request.post look like. Authenticate and get a session ID for further queries. def GetSession(IP): request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' request = request + ' <soapenv:Body>' request = request + '<login>' request = request + '<username>username</username>' request = request + '<password>password</password>' request = request + '</login>' request = request + '</soapenv:Body>' request = request + '</soapenv:Envelope>' request = u"""""" + request + """""".format() encoded_request = request.encode('utf-8') headers = {"Host": ""+ IP +"", "Content-Type": "text/xml; charset=UTF-8", "Content-Length": str(len(encoded_request)), "SOAPAction": ""} response = requests.post(url="http://"+ IP +"/Service", headers=headers, data=encoded_request, verify=False) return response.content With the session ID do more queries. Like this getting a list: def GetList(session, IP): request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' request = request + '<soapenv:Header>' request = request + '<session>'+ session +'</session>' request = request + ' </soapenv:Header>' request = request + ' <soapenv:Body>' request = request + '<getList/>' request = request + '</soapenv:Body>' request = request + '</soapenv:Envelope>' request = u"""""" + request + """""".format() encoded_request = request.encode('utf-8') headers = {"Host": ""+ IP +"", "Content-Type": "text/xml; charset=UTF-8", "Content-Length": str(len(encoded_request)), "SOAPAction": ""} response = requests.post(url="http://"+ IP … -
How to update money field
I have 3 models: user, task, billing. There 2 types of users: CUSTOMER and EXECUTER. There are fields: balance in users and money on tasks. I need to update balance of user after creating task and assigning it to user. I tried: I made this func on users.models: def update_balance(self, money, **kwargs): self.balance += money self.save() On api.views I tried: def assign (self, request, pk): reporter = User.objects.get(id="7") reporter.balance = F('balance') + Task.money reporter.save() Project structure is: freelance api __init__.py apps.py models.py serializers.py urls.py views.py billing __init__.py admin.py apps.py models.py tests.py views.py base statics templates users __init__.py settings.py urls.py wsgi.py task migrations __init__.py admin.py apps.py models.py tests.py views.py users migrations __init__.py admin.py apps.py models.py tests.py views.py -
How to make a Passoword-Change-Class-Form
So i wanted to make a password change view for my Custom-Userclass. yea it dosnt work and i cant figure out why, my Form.py class ChangePassword(PasswordChangeForm): class Meta: fields=('old_password', 'new_password1', 'new_password2') model = User def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) Here is my UserClass: class UserZ(authmodels.User,authmodels.PermissionsMixin): status = models.CharField(max_length=100, blank=True) avatar = models.ImageField(upload_to='images/avatar', null=True, blank=True,default='/static/img/Weramemesicon.png') def __str__(self): return self.username Here is my view,py class password(LoginRequiredMixin,CreateView): form_class = forms.ChangePassword success_url = reverse_lazy('login') template_name = 'accounts/passwort.html' Changin everything else works.It tells me "TypeError at /accounts/password/" -
user format to ugettext
How to use format to ugettext? # is not valid code from django.utils.translation import ugettext as _ def index(req): return _('Hello world {}').format('Users') ore use (сreate more duplicate): _('Hello world {}'.format('Users')) -
Django CustomTags Using Session
I'm trying to use Django to output a html page based on whether the session is set or not. when I submit my Django Form (via my view) I set the session like this: def index(request): users = Users.objects.all() totalUsers = len(users) form = CreateUserForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() form = CreateUserForm() context = { "form": form, 'users': users, "totalUsers": totalUsers, } request.session.set_expiry(300) request.session['loggedIn'] = True return render(request, 'SmartCity/index.html', context) I know this is successful because I can see the value set in the DB. In my CustomTags.py file, I want to more or less check the session variable "loggedIn" is set, and if it is, return one thing, otherwise, return something else. This is how I thought to achieve it, but it's not working: from django import template register = template.Library() @register.inclusion_tag('SmartCity/index.html', takes_context=True) def hello_world(context): request = context['request'] loggedInStatus = request.session.get('logged_in', 'False') if loggedInStatus == True: return "Hello world" The error I receive is: https://preview.ibb.co/dqAe8k/2017_09_19_18_06_57.png I could totally be on the wrong track... I would appreciate any advice you might be able to give a Django beginner :) -
Is it possible to convert a hardcoded request.post to suds-jurko request
Is it possible to convert a hardcoded request.post to use with suds-jurko instead? Or is there any better solution out there? Preferrable with good decumentation/examples. Cheers! =) -
How to set Django model IntegerField as a primary and to start at 100, also be Auto Increment?
How to set model field that starts at integer 100 and auto increment as well as it needs to be a primary key. here is my models.py file from django.db import models class URLShortner(models.Model): # that integerfield here original_url = models.CharField() shortned_url = models.CharField() def __str__(self): return self.original_url Also, a ModelForm which only accepts original_url and auto assign to integerfield. Please help me. :) -
WebInterface for a complex programmable logic controll device
my project is to develop a webinterface for a complex machine. - The web interface should be applied for maintaining and diagnostics. - The webserver should run on a embedded device. - On the embedded device a process which takes all the required data from the complex machine and delivers the data to the webserver/webinterface is needed. - Another requirement is, the webinterface should be available for a long product live cycle. - The webinterface should show realtime data and allow to manipulate data from the complex machine. So i`m completely new at this topic. I found out the Webframework Django and for realtime data the module channels (Websocket) would be fit for this. What experience is available for Django/Channels or other Solutions to fulfill my requirements ? -
Creating multiple users at once using Form
) I am trying to give the ability to my user to create a team and create 3 users in one time that will populate that team. Could you please help me to figure out why it is not working please ? forms.py : class InviteForm(forms.Form): Email1 = forms.EmailField() Email2 = forms.EmailField() Email3 = forms.EmailField() Views.py def TeamRegisterTest(request): if request.method == "POST": form = InviteForm(request.POST) if form.is_valid(): for i in form: mail = i.value() user_create = MyUser.objects.create(email = mail) user = user_create.save(commit=False) password = MyUser.objects.make_random_password() user.set_password(password) user.is_active = False user.is_employee = True user.save() else: print("The entered form is not valid") else: form = InviteForm() return render(request,'team_register.html', {'form':form}) I get a save() got an unexpected keyword argument 'commit', I guess that it is because commit is only for ModelsForm how can I save without commiting in order to continue to edit attribute ? Thx you ;) -
Django makemigrations is ignoring keys with underscore for CharField
I'm currently working on a chat application in Django and tried to set up a model for text messages. When I create the model with python manage.py makemigrations the fields msg_to and msg_from are ignored and won't appear in the sqlite database after python manage.py migrate. When I change them to msgfrom and msgto they appear. Can anyone proof this behavior or explain to me why this is happening? class Chat_message(models.Model): msg_from = models.CharField(max_length=150, default='') msg_to = models.CharField(max_length=150, default='') msg = models.TextField() timestamp_sent = models.DateTimeField(default=timezone.now, db_index=True) timestamp_read = models.DateTimeField(null=True, blank=True) -
Use Remote MySQL Database On Heroku With Django Server
Can I use mysql database from my personal web server instead of heroku's database? in django settings I have this for databses: DATABASES={ 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'x.x.x.x', 'PORT': '3306', } } what should be my settings.py databases part? or do I need anything more to do? -
Developer workflow: Does it matter which port is used during development?
Are there any differences between choosing this or that port? Are there any standards for picking a port? I'm just looking for the "why" a particular port was picked to be used. There doesn't appear to be a standard convention for picking a port number(at least in documentation). The examples in official docs use different port numbers. Create React App docs provide examples using localhost:3000/ Django docs provide examples using port 8000/ Ember docs provide examples using port 4200/ Express docs provide examples using port 3000/ Flask docs provide examples using port 5000/ Webpack docs provide examples using port 8080/ -
Why cant i access Django User "status"
I cant display my custom object "status". I can fill it and see it in my admin. But when i try to get it with HTML it dosnt display. But it does display username, lastname etc. . Here is my model.py (in accounts): from django.contrib.auth import models as authmodels class UserZ(authmodels.User,authmodels.PermissionsMixin): status = models.CharField(max_length=100, blank=True) avatar = models.ImageField(upload_to='images/avatar', null=True, blank=True,default='/static/img/Weramemesicon.png') def __str__(self): return self.username model.py (posts) User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts') # ... html code: note: {{post_user.username}} workes correct. {% block prepost %} <h1>{{post_user.username}}'s Memes</h1> {%if user.is_authenticated %} <a href="{%url 'settings'%}"><p>Einstellungen<p/></a> {% endif %} {{ post_user.status }} {% endblock %} it should display: PeterPan2's Memes Einstellungen Some Status -
Testing Django - Saving test DB
In my tests.py I have: from functions import function from .models import Student def setUp(self): self.student = Student.objects.create(status=False) def test_function(): function() # function changes student's status to True print(self.student.status) # I'm still getting False While running tests, my function doesn't change the attributes of objects created for tests so i can't test if function works properly. Is there a way to make sth like scenario below: Object for testing is created. I'm calling function which changes object's attribute. I can check if attributte was changed. Function I want to test doesn't return anything, it only changes attriubtes of objects. -
SAML authentication using django and mongodb
My project configuration is as- 1 Okta as a IDP 2 Django app as a service provider [django version 1.10] I am using django app web api. 3 MongoDB as a database [mongoengine 0.13.0] 4 For Saml authentication I am using [djangosaml2]: https://github.com/knaperek/djangosaml2 Till now I able to connect IDP and able to get SAML response [success] but I get error in assertion consumer service same code is working if I use sqllite database instead of mongodb Is there any way to get it working with mongodb database. or manage authentication using client side session Thanks in advance.