Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multi node usage of python-don
I want to use pythone-don for monitoring openstack networking.But during data collecting it gives error. horizon log shows it: 2017-06-03 08:49:12,738 13396 ERROR django.request Internal Server Error: /dashboard/don/view/ Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/site-packages/horizon/decorators.py", line 36, in dec return view_func(request, *args, **kwargs) File "/usr/lib/python2.7/site-packages/horizon/decorators.py", line 52, in dec return view_func(request, *args, **kwargs) File "/usr/lib/python2.7/site-packages/horizon/decorators.py", line 36, in dec return view_func(request, *args, **kwargs) File "/usr/share/openstack-dashboard/openstack_dashboard/wsgi/../../openstack_dashboard/don/ovs/views.py", line 77, in view plotter.plot_compute_node() File "/usr/share/openstack-dashboard/openstack_dashboard/wsgi/../../openstack_dashboard/don/ovs/plot.py", line 790, in plot_compute_node self.__plot_vms() File "/usr/share/openstack-dashboard/openstack_dashboard/wsgi/../../openstack_dashboard/don/ovs/plot.py", line 348, in __plot_vms if self.info['floating_ips'].get(self.info['vms'][vm]['uuid']): KeyError: 'floating_ips' -
How to determine the first URL segment in a CMSPlugin Model and use as Filter
Good Morning I'm building a CMS/SPA based Website with Django CMS and the Site is splitted into three Departmenets. The Base URLs for those are as following: /en/private /en/business /en/education Then i wrote a CMSPlugin Model with the possibility to put a Latest Blog Post Widget on any Placeholder: The Blog Model: from category.models import Category from department.models import Department class Post(models.Model): STATUS = ( ('published', 'Published'), ('draft', 'Draft'), ('closed', 'Closed'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) meta_title = models.CharField(max_length=250) meta_description = models.CharField(max_length=160) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(default=datetime.now) archive_date = models.DateTimeField(blank=True, null=True) head_image = models.ImageField(upload_to='media/', null=True, blank=True) body = HTMLField(blank=True) status = models.CharField(max_length=20, choices=STATUS, default=STATUS[1][0]) author = models.ForeignKey(User) categories = models.ManyToManyField(Category) departement = models.ManyToManyField(Department) def __str__(self): return self.title The Plugin Model: class PostLatestPluginModel(CMSPlugin): latest_posts_limit = models.IntegerField(default=5) def get_posts(self, request): posts = Post.objects.order_by('-publish_date').filter(status='published', publish_date__lte=datetime.now()) return posts[:self.latest_posts_limit] def __str__(self): return ugettext(' - Limit: %(latest_posts_limit)s') % { 'latest_posts_limit': self.latest_posts_limit, } The Form: from __future__ import unicode_literals from django import forms from . import models class PostLatestPluginForm(forms.ModelForm): class Meta: model = models.PostLatestPluginModel fields = [ 'latest_posts_limit', ] As you can see there is a Field in the Blog Model where i can define the Department (private, business, education), … -
Django - Dynamic search result
I have a list of video games in my database. The user is suposed to choose their favorite games by selecting the checkbox of the wanted game. So I have a form with the entiere list of these games. For now I use a For condition to display all the entries from my database/table. But now I have a huge list of game that the user can choose, so I can't display everything. Do you think It could be a good solution if I replace my system by placing a search bar which could dynamicly search and add a game. Is there a right way to do this with Django ? If not, could you give me the simpliest solution to solve my problem ? Thank you. -
Redirect to external URL with some parameters
I was trying to redirect the user to an external URL and that URL contains a login form. I would like to fill in the username and password column for the user. As if there's auto-complete function. I can't figure it out by using redirect or HttpResponseRedirect. Could someone enlight me or give me some directions? -
I dont want MODEL layer of any web development framework(Django)
I dont want the MODEL (MVT) concept so how can i avoid this and I want to run my own db query directly. I dont want ORM concept. Especially in DJANGO framework with mysql. Simply want VIEW and TEMPLATE. Please share some tutorial about this. -
Django: class based view logout user if not staff
i'm new to Django and i'm trying to use the PermissionRequiredMixin to verify if the authenticated user is staff before access to page, if he isn't authenticated the view redirect the user to the login page, on this page is loaded a form from django.contrib.auth.views.login, ok. But if the user is authenticated and he isn't staff, he will not have any form on the login page when redirected. What should I do? Logout the user if he is not staff when he try to access the staff only page? If yes, how do I could do that using the CBV with TemplateView? View from django.contrib.auth.mixins import PermissionRequiredMixin ... class AdminView(PermissionRequiredMixin, TemplateView): permission_required = 'is_staff' template_name = 'checkout/admin.html' login URL from django.contrib.auth.views import login ... url(r'^entrar/$', login, {'template_name': 'accounts/login.html'}, name='login') -
Force CharField's Choices
I have few models.CharField objects in my Model, with the choices attribute. This is working great as far as the GUI is concerned, But I want to block values other than these specified in the choices attribute in the code itself (to protect myself from bugs). Is there a way to raise an exception (I believe it'll be a ValueError) when trying to save a string which is not in the choices list? -
how to compare values in unequal zip list in django?
I have two unequal lists and I have zipped it and passed it as a context from my view.In my template, I have a multi select drop down where I want to compare the values and show selected there on the dropdown.But i am unable to achive that. here is my code:- first list:- university_all_list = Universities.objects.using('cms').all() second list:- university_ids_list = [] school_university_mapping = SchoolAdminUniversityMappings.objects.filter(userId=cms_user) for university_ids in school_university_mapping: university_ids_list.append(university_ids.universityId) print university_ids_list combing the two list:- zip_list = zip(university_all_list, cycle(university_ids_list)) if len(university_all_list) > len( university_ids_list) else zip(cycle(university_all_list), university_ids_list) now,using that zip_list in template:- <div class="col-sm-8 multiselect_container"> <select class="mutisel" id="first_select" multiple="multiple" value="university_all_list.id" name="universityId" id="userName" required> {% for university,id in zip_list %} {% if id == university.id %} <option value="{{ university.id }}" selected>{{ university.name }}</option> {% else %} <option value="{{ university.id }}" >{{ university.name }}</option> {% endif %} {% endfor %} </select> <script> $("select.mutisel").multipleSelect({ filter: true, placeholder: "Select", }); </script> </div> but there isnt any dropdown selected in multiselect. -
Django watchtower logging handler is not work from AWS ECS container
First, I use the server environment: sever: django + nginx + uwsgi cloud: docker + AWS ECS logging: AWS CloudWatch log service + watchtower third party app I would like to use the cloudwtch log service used by watchtower third party. Docker build and run command docker run -v $ HOME / .aws: /root/.aws --rm -it -p 8080:80 image_name locally, the cloudwatch log service will work normally. However, if you run Task by loading docker image in AWS ECS Cluster, it will still return 500 error. However, if I delete the following logging setting and run the task in ecs again, the server will work normally. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'watchtower': { 'level': 'DEBUG', 'class': 'watchtower.CloudWatchLogHandler', 'formatter': 'verbose', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['watchtower', 'console'], 'level': 'INFO', 'propagate': True, }, 'django.user': { 'handlers': ['watchtower'], 'level': DJANGO_LOG_LEVEL, 'propagate': False, }, 'django.partner': { 'handlers': ['watchtower'], 'level': DJANGO_LOG_LEVEL, 'propagate': False, }, } } Enable logging again and upload the docker image to ecs. I'm setting aws credentials as well. Refer … -
Django: Startapp Generated files into existing project folder
I want to place django app files into generated Django project folder . MyProject/ MyProject/ settings.py urls.py here i want to insert my Django app files like, views.py, admin.py, models.py etc into same MyProject folder itself. we can do the same by copy paste after app was created. but i want to know is their any magic we can achieve the same while executing this command? django-admin startapp MyApp <directory> I dont want to create Myapp folder instead Myapp/* should be move onto Myproject/ itself. without doing copy paste thing. so finally i want my Project folder should be like this, MyProject/ MyProject/ admin.py models.py settings.py urls.py views.py -
Error in picking the latest event
I have table in the DB say MyHistory table. Based on event history , I have to pick latest event in my events say LOGIN and SUPPORT. I have to pick whatever the event performed latest. Note : Event does not have priority that particulate event has to perform order. While running the below code , I got the error like ERROR: error - too many values to unpack What is the wrong in the below code? def my_welcome_msg(self): msg_created_date = MyHistory.objects.select_related().filter( cluster=self.cluster).filter( event_type=MyHistory.SUPPORT).filter(MyHistory.LOGIN).order_by('created_date')[0].created_date return msg_created_date I have records related to single user_id in a table as shown below. | id |created_date|modified_date| description |user_id | event_type | cluster_id 1 2017-05-31 01:00:58 SUPPORT 2 2017-05-30 23:00:38 LOGIN -
'Error 65537 while instatiating the CBC mode' in python pycrypto
I want to connect to a payment system that force me to use AES to cennect them. with these requirements: AES algoritme block size and keysize =256 padding: PKCS7 Encoding : UTF-8 and given key and IV after many search and questions I reach this code but I have 'Error 65537 while instatiating the CBC mode' error Code: def pad(request,s): bs = 32 return s + (bs - len(s) % bs) * chr(bs - len(s) % bs) def pardakht(request): paymentString="1,negin1234567,T6u123459I,1234,1001,20170601 092231,abcd,example.com/test,0" config={ 'zarin_key':b'7o7NLbbBpLb2vF8qYLVmeCYCmZtJupKb2TFOVdafDZQ=', 'zarin_iv':b'4TdLAqzuihq+SU4C+58tCjMbO14KyZ40qn3yIPX4klM=', 'username':'negin1234567', 'merchant_id':'1350655' } key = base64.b64decode(config['zarin_key']) iv = base64.b64decode(config['zarin_iv']) paymentString = pad(requests,paymentString) cipher = AES.new(key,AES.MODE_CBC,iv) res=base64.b64encode(cipher.encrypt(paymentString)) return HttpResponse(res) -
Python/Django and React.js server-side rendering: ReactRenderingError
I'm trying to use React.js alongside with Django framework and I'm intending to do some server-side rendering through a view over React components but it's not possible due to I'm getting the error: ReactRenderingError. What it shows is a "self is not defined" message on the exact line where rendering should happen. rendered = render_component('file.js', props={...}) I've used both python-react and react-render libraries to achieve it, but none of them work. I must say webpack is used too for generating the js bundles. Posts on other sites like GitHub say that's due to browser objects not being pre-loaded at the render time, but anything has worked for me. Hope you can help me, thanks! -
TemplateDoesNotExist at /account/
I experimented with making my URLs more dynamic, and ended up breaking something. I can figure it out for the life of me! Any help would be greatly appreciated. The only URLs working are my login and logout templates. I get why those are working, but what am I doing wrong for the rest of my URLs? Here's the traceback I'm receiving: Traceback (most recent call last): File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/xxxxx/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/xxxxx/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/m.zayas/Desktop/env1/diversely/accounts/views.py", line 20, in home return render(request, 'accounts:home') File "/xxxxx/env1/lib/python2.7/site-packages/django/shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "/xxxxx/env1/lib/python2.7/site-packages/django/template/loader.py", line 67, in render_to_string template = get_template(template_name, using=using) File "/xxxxx/env1/lib/python2.7/site-packages/django/template/loader.py", line 25, in get_template raise TemplateDoesNotExist(template_name, chain=chain) TemplateDoesNotExist: accounts:home [03/Jun/2017 03:15:17] "GET /account/ HTTP/1.1" 500 78337 Here are my views: from django.shortcuts import render, redirect from django.urls import reverse from accounts.forms import ( RegistrationForm, EditProfileForm ) from django.contrib.auth.models import User from django.contrib.auth.forms import ( UserChangeForm, PasswordChangeForm ) from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required # Create your views here. def home(request): name = 'Matthew Zayas' args = {'myName': name} … -
I want to integrate email in my verification in my CMS in django
I'm developing a CMS website in django.Till now the users logins successfully with username and password and can use my website without any hindrance. But the missing thing is user verification. I want some way for the user authentication for security. I want the user to provide his/her email id while login and redirects to his/her email id for the verification purposes.Security is my main concern, so i want to integrate email in my verification in my CMS.Is this possible to achieve with any library for the same? -
Restart Django server at regular interval
Am thinking of how restart at periodic interval Django server on Linux. It means : 1) Exit, Kill the current python process 2) Launch start of manage.py from command line. 3) Put the command in python and setup som CRON. Is there any straightforward to do it in Django or in python script ? -
Make Join in Django queryset to filter it
I have two querysets and I'd like to make a join, but I'm not sure how to proceed. Queryset in steps # Example: # Main queryset q = Recipe.objects.all() ingredients = ['salt','oil','flour','tomato'] # This result in all the ingredients necessary q1 = q.annotate(total=Count('steps__ingredients', distinct=True)) # This result in the available ingredients. # First I filtered the ingredients I have, them I counted them q2 = q.filter(steps__ingredients__ingredient__name__in=ingredients) .annotate(available=Count('steps__ingredients', distinct=True) ) I'd like to join both results and filter by .filter(total=F('sum')) at the end. I know I have available the | operator. I'd have to do something in this line: result = q1 | q2 But whenever I do this, one of the annotations disappear (the last one, in this case q2 annotation which is available). Any ideas? I don't want to iterate over them if the DB can do that. Strangely enough, there were times that when I put everything in one line, it would give me the expected results often times. I have the impression this can be a bug. I think it cached somehow the result... This is what I did and it resulted correctly a few times: queryset = Recipe.objects.all() .annotate(total=Count('steps__ingredients', distinct=True)) .filter(steps__ingredients__ingredient__name__in=ingredients) .annotate(sum=Count('steps__ingredients', distinct=True)) .filter(total=F('sum')) I'm using … -
django: how to consume incoming POST data as a file-like obj for streaming processing
I'm using python + Django to handle incoming web requests that can post a large amount of JSON attached as one of the POST data fields (e.g. var1=abc&json_var=lots_of_data&other_var=xxx). I'd like to process the JSON in a streaming fashion with my own streaming json parser which takes a file-like handle as its input argument. It appears from https://docs.djangoproject.com/en/1.11/ref/request-response/ that this is feasible, using HttpRequest.iter(), but I can't find any examples of how to achieve this with my own code (i.e. not just importing a library like xml.etree.ElementTree). Basically, I'd like to do the following: POST request w/ big JSON => Django/python => create file-like handle to read POST => streaming url decoder => streaming JSON processor I can use ijson for the streaming JSON processor. How do I fill in the two gaps for creating a file-like handle to the POST data and passing it to a streaming url decoder? Would prefer not to roll my own of either but I suppose if necessary I could. -
How to do SELECT COUNT(*) GROUP BY DJANGO?
I want to do this MySQL query in django SELECT Descripcion,count(*) FROM votaciones.Tarjeton where Voto_idVoto=1 group by Descripcion; Result consult Mysql '', '1' 'Camilo Gomez Ortega', '3' 'JUan Jose Marquez', '3' 'Pedro Pablo de la Mar', '15' 'Sandra Mejia Gutierez', '4' my model is: class Tarjeton(models.Model): idtarjeton = models.AutoField(db_column='idTarjeton', primary_key=True) # Field name made lowercase. descripcion = models.CharField(db_column='Descripcion', max_length=45) # Field name made lowercase. cadidatos_idcadidatos = models.ForeignKey(Cadidatos, models.DO_NOTHING, db_column='Cadidatos_idCadidatos') # Field name made lowercase. voto_candidato = models.ForeignKey('Voto', models.DO_NOTHING, db_column='Voto_idVoto') # Field name made lowercase. class Meta: managed = False db_table = 'Tarjeton' -
In Django 1.8, how can I render login form?
I have started learning Django, I want to create login form. Here is snippet code in myproject/urls.py in tutorial. login_helper = FormHelper() login_helper.form_action = reverse_lazy("my_login_page") login_helper.form_method = "POST" login_helper.form_class = "form-signin" login_helper.html5_required = True login_helper.layout = layout.Layout(layout.HTML(string_concat("""<h2 class="form-signinheading">""",_("Please Sign In"), """</h2>""")), layout.Field("username", placeholder=_("username")), layout.Field("password", placeholder=_("password")), layout.HTML("""<input type="hidden" name="next" value="{{ next }}" />"""), layout.Submit("submit", _("Login"), css_class="btn-lg"), ) urlpatterns = [ url(r'login/$', "django.contrib.auth.views.login", {"extra_context": {"login_helper": login_helper}}, name="my_login_page"), ] I can't understand what the {"extra_context": {"login_helper": login_helper}} means and Why I use FormHelper. When I go to http://localhost:8000/login/, the exception has occurred as follows. TemplateDoesNotExist at /login/ registration/login.html Request Method: GET Request URL: http://localhost:8000/login/ Django Version: 1.8 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: /home/k/python/myproject_env/local/lib/python2.7/site-packages/django/template/loader.py in get_template, line 46 Python Executable: /home/k/python/myproject_env/bin/python Python Version: 2.7.12 Here is snippet code in myproject/templates/registration/login.html file as follows. {% extends "base.html" %} {% load crispy_forms_tags %} {% block stylesheet %} {{ block.super }} <link rel="stylesheet" href="{{ STATIC_URL }}site/css/login.css"> {% endblock %} {% block content %} <div class="container"> {% crispy form login_helper %} </div> {% endblock %} login.html file extends to myproject/templates/base.html file. But login form doesn't be rendered. What shall I do? -
Assigning Django model field within one model to point to one of a choice of other, related models
I am designing an inspection app in Django for a service company and have an esoteric question about my models. This is the scenario I'm struggling with: Site(models.Model): name = CharField() Generator(models.Model): number = CharField() site = ForeignKey(Site) Pump(models.Model): number = CharField() site = ForeignKey(Site) Jobs(models.Model): asset = ? site = ForeignKey(Site) What I would like to do is assign either a Generator OR a Pump object to the asset field in Jobs. Rather than just generating a list of both generator and pump numbers I would like the field to point to the actual model itself, that way I can backwards reference each job without scanning both tables. Any ideas? Would it help to have an asset property in the job model? I am overthinking this? Using Django 1.11.1 and Python 3.6 -
How to disable authorization in Django for registration?
I'm using to authentication this: from rest_framework.authtoken import views as rest_auth_views url(r'^login/', rest_auth_views.obtain_auth_token) Everything works fine but in order to create new account I have to send token in header what is wrong. I'm creating new account using such view: elif request.method == 'POST': serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How can I disable authentication for user registration? Maybe my method or line of thought is wrong? -
How to link optional arguments with positional arg?
I have one positional arg all and 2 optional args one & 'two`. when I run script.py all --one script.py all --two then it works fine. but I want to that when I run script.py all then automatically one and two will run? Here is the code:- from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): # Positional arguments parser.add_argument('all', nargs='+', type=str) # Optional arguments parser.add_argument( '--one', action='store_true', dest='one', default=False, ) parser.add_argument( '--two', action='store_true', dest='two', default=False, ) def handle(self, *args, **options): if options['one']: one_issues() self.stdout.write(self.style.SUCCESS('Successfull')) if options['two']: two_issues() self.stdout.write(self.style.SUCCESS('Successfull')) -
Django Rest Framework. Custom permission with JSONWebTokenAuthentication
I have a need to write a custom permission (deriving from BasePermission) for one of my endpoints where: If the method is POST, it's open for everyone (e.g. returns true).. however, if the method if PUT or GET it should be authenticated with JSONWebTokenAuthentication to figure out if to clear or reject the request. Typically, I know how to add this into my APIView class authentication_classes = ([JSONWebTokenAuthentication]) But how do I check whether the user is already authenticated with JSONWebTokenAuthentication in case the HTTP method is PUT or GET in my Custom Permission class? Is there something like IsJSONWebTokenAuthenticated somewhere? -
Alter form of formset data before redisplay
We have forms cleaned_data and forms instances, I dont know what django uses if I prefer to redisplay the form and dont know how to update suggested attributes. Planning to do some business logic after validation and redisplay it. if formset.is_valid(): #do something with forms in formset and redisplay it. #maybe, alter forms data return render(.....)