Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
1.How to set lable to each widget in django_filters.DateFromToRangeFilter? 2.How can I change order in fields
How can I set lable 'Start date' to widget[0] and 'End Date' to widget[1] in DateFromToRangeFilter? class CasesFilter(django_filters.FilterSet): datelastupdate=DateTimeFromToRangeFilter() testtime=DateTimeFromToRangeFilter(widget=RangeWidget(attrs={'placeholder': 'DD.MM.YYYY HH:SS'})) class Meta: model = ListOfCases fields=['id_test' , 'datelastupdate', 'testtime', 'active_flag', 'version' ] 2.Variables in 'fields' are displayed in a different order on the page. How can I change the order of variables? Tamplate: <div > <form action="" method="get" class="form-inline"> {{filter.form|crispy }} <div style="display:block; clear:both; margin-top:10px"> <input type="submit" value="Search" /> </div> </form> -
django 1.10 with non-ascii cache names
The problem actually raised from mezzanine comment form which stores the author's name in the response cache (as summarized below): set_cookie(response, "mezzanine-comment-name", post_data.get("name")) Which calls the django set_cookie function: response.set_cookie(name, value, expires=expires, secure=secure) So if the author's name contain non-ascii characters, a well known problem is raised by the server (I've tested it with nginx and also django local server): UnicodeEncodeError: 'ascii' codec can't encode characters in position ...: ordinal not in range(128) I've also tried to modify mezzanine source code and put .encode() after post_data.get("name") but there is an weird line in the first line of the response.set_cookie which revokes the encoding! value = force_str(value) -
Adding "Save as Draft" and preview feature in Django admin
How to add "save_as_draft" and "preview" option to my django project. I want to allow admin interface to save the blog posts as draft. and a preview button to preview how my blog post will look after publishing. I also tried integrating mezzannine with my django project. But there are not enough documentations for doing. In the FAQ of mezzannine documentations. They just written that users can easily integrate mezzannine with their django project. Is there a way i can customize the django admin interface? -
no encoder installed for (u'json',) from kombu
I think I am missing a step somewhere but I've been looking around and cant find it. When I run my celery task, I get thrown this error message no encoder installed for (u'json',) when I call get_task.delay(args). Am i suppose to have my own custom serialization? settings.py CELERY_ACCEPT_CONTENT = ['pickle'] CELERY_TASK_SERIALIZER = 'json', CELERY_RESULT_SERIALIZER = 'json' I also tried get_task.apply_async((args), serializer='json'). This seems to hang. Nothing is running. I checked my workers, nothing shows up. -
Django lesson list with buttons
I want to display a list of lessons in django, that have a register or unregister button, depending on the users lesson-registrations. If a registration for the lesson exists, there is an unregister button. How can all the lessons be displayed with the right button? The models used are: class S_Lesson(models.Model): title = models.CharField(max_length=1000) description = models.CharField(max_length=4000) time_list = models.ManyToManyField(S_LessonTime) group_list = models.ManyToManyField(S_LessonGroup) def __str__(self): return self.title class S_LessonRegistration(models.Model): time = models.ForeignKey(S_LessonTime, on_delete=models.CASCADE, blank=True, null=True, default=1) group = models.ForeignKey(S_LessonGroup, on_delete=models.CASCADE, blank=True, null=True, default=1) lesson = models.ForeignKey(S_Lesson) def __str__(self): return str(self.lesson) + "(" + str(self.time) + "/" + str(self.group) + ")" class S_User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default="2") first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) lesson_registration_list = models.ManyToManyField(S_LessonRegistration, null=True) def __str__(self): return self.last_name + " " + self.first_name My views.py: @login_required(login_url='u:login') def LessonDetailsView(request, lesson_id): lesson_object = get_object_or_404(S_Lesson, pk=lesson_id) s_user = get_object_or_404(S_User, user=request.user.pk) return render(request, 'u/lesson-details.html', {'lesson_object': lesson_object, 's_user': s_user}) Template: <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> <th>Lessons</th> <th>&nbsp</th> </tr> </thead> <tbody> {% for lesson_item in class_object.lesson_list.all %} {% for lesson_registration in s_user.lesson_registration_list.all %} {% lesson_is_registered = False %} {% if lesson_registration.lesson.id == lesson_item.id %} {% lesson_is_registered = True %} {% if lesson_is_registered == True %} <tr> <td> <form id="unregister_{{ … -
Get data from model A to model B after filling the form of model B in django
I have following two models. What I want is Whenever I fill the data in model Book i.e its name (like name of Book says Java) It will automatically be saved also in Contributor model under field "name". Also I can manually be able to fill the "name" field in Contributor model in django Admin class Book(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Contributor(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name Data in model Book After Filling Data in model Book I want Data in model Contributor as this -
Render hyperlinks in django-wagtail template
I have a little problem, I created this model, and now I need a template for render the "related links section" in the bottom of a "post page" . class PostPageRelatedLink(Orderable): page = ParentalKey(PostPage, related_name='related_links') name = models.CharField(max_length=255) url = models.URLField() panels =[ FieldPanel('name'), FieldPanel('url'), ] I have no idea how to write html for that :) I wrote this, but obviously doesn't work <div class='related_links'> <h3>Related Links</h3> {% for item in page.related_links.all %} <a href='related_links'>{{ page.related_links.url }}</a> {% endfor %} </div> What is the right way to do this? Thanks for help! -
No exception raised when saving an empty field with null=False - Django
I have the following model: class User(models.Model): email = models.EmailField(max_length=254, null=False, unique=True) referral_code = models.CharField(max_length=10, null=False, unique=True) And used the Django shell to save a user instance with referral_code undefined: u = User(email="test@example.com") u.save() This did not raise an exception. My understanding was that null=False would require referral_code to be set - Is this not the case? How would I achieve that behaviour? -
auth.user not resolved error django
i added one field to my model and attached it to django user model through foreignkey. My model is, from django.db import models from django.contrib.auth.models import User # Create your models here. class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField() Username = models.ForeignKey(User,default=1) but while migration it is giving me error as 'valuerror: related model 'auth.user' cannot be resolved.' what does that mean and how to resolve that? I tried many things but did not work. Thanks in advance. -
Adding an image into a django template from the static folder - Django
I have a django template and I want to add an static image to the file from my static folder that I have within the applicaiton. I am trying to but nothing is appearing on the template. DOes anyone know where my error is coming from. Here is my code: {% extends "base.html" %} {% block content %} <div class="row"> <div class="col"> <img src="static/images/Artboard1.png" alt=""> <h2>{{ currentUser.username }}</h2> </div> <a href="{% url 'logout' %}">Logout</a> {% endblock %} Here is an image of my directory: -
Need Tips for Two dimensional array in Python
I am new in python. I have a two dimensional list in django. Now I want to check if given text is in list or not. But its not working. Here is my code: newmessage = 'Bye' stockWords = [ ['hello', 'hi', 'hey', 'greetings'], ['Bye', 'Goodbye'] ] for i in range(0, len(stockWords)): if newmessage.lower() in stockWords[i]: return HttpResponse('Found') else: return HttpResponse('Not Found') The problem is it works only for first element of list, the second one is not working. What am I doing wrong? Any suggestion? -
overlapping Navbar in bootstrap in a Django template
My navbar is overlapping my web, and I don't know how to change it. Now is : You can see the number of events and the blue button for create a new event, are cut in the middle by navbar. My templates are: navbar.html <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'events_app:panel' %}">Eventus</a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav pull-right"> <li><p class="navbar-text">Bienvenido, <a href="#" class="navbar-link">{{ user.username|capfirst }}</a></p></li> <li><a href="{% url 'users_app:logout' %}">Logout</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> panel.html {% block title %}Panel{% endblock title %} {% block content %} {% include "events/panel/navbar.html" %} <div class="container"> <div class="page-header "> <h4> <strong> Tienes <span class="label label-warning">0</span> Eventos disponibles </strong> <a class="btn btn-primary pull-right" href="{% url 'events_app:nuevo' %}"> <span class="glyphicon glyphicon-plus"></span> Crear un evento nuevo </a> </h4> </div><!-- page-header --> <div class="row"> <div class="col-md-12"> <table class="table table-striped table-hover"> <thead> <tr> <th colspan="2">Nombre del evento</th> <th>Categoría</th> <th>Inicio</th> <th>Fin</th> <th>Monto</th> <th class="text-center">Acciones</th> </tr> </thead> <tbody> <tr> <td> <img src="" alt="" width="60" class="img-rounded"> </td> <td>name</td> <td>category</td> <td>start</td> <td>finish</td> <td> <span class="label label-default">Gratuito</span> <span class="label label-info">S/. 0.00</span> </td> <td class="text-right"> <a href="#" class="btn btn-success"><span … -
Middleware logging limitation Django 1.11
Background: I have integration test which is working fine, but later on failed when I added the customized middleware def test_mobile_update_customer(self): user = User.objects.create(username='warhead') self.client.force_authenticate(user=user) mommy.make(Customer, family_name='IBM', created_user=self.soken_staff, updated_user=self.soken_staff) data = { "family_name": "C0D1UM" } customer = Customer.objects.first() res = self.client.patch(reverse('api:customer-detail', kwargs={'pk': customer.id}), data=data) self.assertEqual(200, res.status_code) customer.refresh_from_db() self.assertEqual('C0D1UM', customer.family_name) self.assertEqual('spearhead', customer.created_user.username) self.assertEqual('warhead', customer.updated_user.username) Problem: The middleware break it with Exception File "/Users/el/Code/norak-cutter/soken/soken-web/soken_web/middleware.py", line 47, in process_request data['PATCH'] = json.loads(request.body) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/django/http/request.py", line 264, in body raise RawPostDataException("You cannot access body after reading from request's data stream") django.http.request.RawPostDataException: You cannot access body after reading from request's data stream The problem is data has been read before the RESTful api do the job. Then the program raises an exception. def process_request(self, request): if request.path.startswith('/api/'): data = collections.OrderedDict() data["user"] = request.user.username data["path"] = request.path data["method"] = request.method data["content-type"] = request.content_type if request.method == 'GET': data['GET'] = request.GET elif request.method == 'POST': data['POST'] = request.POST # https://stackoverflow.com/questions/4994789/django-where-are-the-params-stored-on-a-put-delete-request # elif request.method == 'PUT': # data['PUT'] = json.loads(request.body) # test_mobile_update_customer # raise RawPostDataException("You cannot access body after reading from request's data stream") # django.http.request.RawPostDataException: You cannot access body after reading from request's data stream # elif request.method == 'PATCH': # data['PATCH'] = json.loads(request.body) elif request.method == … -
Assigning global variable in django
Here's the view, def notifications(request): new_data = Answer.objects.all() return render(request, 'base.html', {'new_data': new_data}) I've created a popup window for notifications just like stack-overflow has but I can't show the notifications since this view is linked to a URL. So, firstly I need to go to the URL only then click on notification button to make notifications appear. If i don't go to URL, it's just showing a blank window. I tried context_processors.py file in app & added TEMPLATE CONTEXT PROCESSOR in settings.py file but nothing is working. I'm not sure if it's the right way in django 1.11. How can I fix this? -
Django Calling Class Based Mixin from Another Class Based Mixin
My code is having two mixins, BasicAuthMixin and JWTAuthMixin as mentioned below. Just assume that self.authenticate method returns True and doesn't raise any exception: from django.http import JsonResponse from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import View class BasicAuthMixin(View): """ Add this mixin to the views where Basic Auth is required. """ @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): try: self.authenticate(request) except: return JsonResponse({'status': 403, 'message': 'Forbidden'}, status=403, content_type='application/json') return super(BasicAuthMixin, self).dispatch(request, *args, **kwargs) class JWTAuthMixin(View): """ Add this mixin to the views where JWT based authentication is required. """ @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): try: self.authenticate(request) except: return JsonResponse({'status': 403, 'message': 'Forbidden'}, status=403, content_type='application/json') return super(JWTAuthMixin, self).dispatch(request, *args, **kwargs) These mixins are being used in the views based upon the authentication needed. The actual problem begins from here: I'm trying to create another mixin AllAuthMixin which when included in any view will automatically determine which mixins need to be called based upon the Authentication Header provided: class AllAuthMixin(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): auth = request.META.get('HTTP_AUTHORIZATION') or '' if auth.startswith('Bearer'): return JWTAuthMixin.as_view()(request, *args, **kwargs) elif auth.startswith('Basic'): return BasicAuthMixin.as_view()(request, *args, **kwargs) raise Exception('Unauthorized Access to Saurav APIs', 403) Once I include AllAuthMixin in any of the … -
Providing download link to user in django
I am uploading files through form and displaying all uploaded file. And now i want to provide link to download any selected file for user, can someone guide me for this ? Thanks in advance -
Connect django with a mssql server using pymssql
I'm trying to connect an apllication on django (v1.11) using pymssql, and I don't know how to make it work. I have followed this steps: > apt-get install freetds-dev (v0.91) > pip install pymssql (v2.1.3) > pip install django-mssql (v1.8) > pip install django-pymssql (v1.7.1) And in settings.py I added: DATABASES = { 'default': { 'ENGINE': 'sqlserver_pymssql', 'HOST': '', 'PORT': '', 'NAME': '', 'USER': '', 'PASSWORD': '', }, } But I have a "TypeError: 'NoneType' object is not callable" error. Is there anything else I should do to configure it? I have tried adding these imports too: import sqlserver_pymssql import sqlserver_pymssql.base but nothing. Any idea? -
FieldError: Unknown field(s) (received_time) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin
I have the following model class Event(models.Model): product_type = models.CharField(max_length=250, null=False, blank=False) received_time = models.DateTimeField(editable=False) in admin: class EventAdmin(admin.ModelAdmin): fields = ['product_type', 'received_time'] I get the following error when trying to edit an event (clicking on an individual event in the admin): FieldError at /admin/events/event/20/ Unknown field(s) (received_time) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin. I do see that editable=False but I still want it to at least be visible, even it it isn't editable. Is there a way to fix this error and edit these items in admin? Thank you -
Assigning a Global Variable django
Here's my code, def notifications(request): new_data = Answer.objects.all() return render(request, 'base.html', {'new_data': new_data}) I have 2 apps in my project. I wants to use data stored in new_data variable in several templates. I can't extend the template. Is there any other way for doing so? -
imoprt error when I gave source toaster start in morty
I got below error when i run poky/build$ source toaster start. The system will start. Traceback (most recent call last): File "/home/siva/yocto/Morty/poky/bitbake/bin/../lib/toaster/manage.py", line 10, in <module> execute_from_command_line(sys.argv) ...... from .management import update_contenttypes ImportError: cannot import name 'update_contenttypes' I have seen the below link but I believe That is diiferent than this. importerror: cannot import name update _all_content -
Django class view: __init__
Im newcomer to python and django and I need some help with class views. I want to get < Model > value from url, and use it as init parameter in my class. urls.py url(r'^(?P<Model>\w+)/foo/$', views.foo.as_view(), name='foo_class'), views.py class foo(CreateView): def __init__(self, **kwargs): text = kwargs['Model'] #this is not working text = kwargs.get('Model') #nethier this Bar(text) ... Clearly, I'm missing something, or my understanding of Url <> class view is wrong. -
Django/template_block doesn't be operated
Thanks in advance. I have a code below "index.html" <!DOCTYPE html> <html> <head> </head> <body> {% block content %}{% endblock %} </body> </html> and I have another html code("maintab.html") for child of "index.html" {% extends "encyclopeida/index.html" %} {% block content %} <p>Hello world</p> {% endblock %} but it doesn't work.. my contact path is "browser -> "http://localhost/encyclopedia/"(by urls) -> function def("by view.py") -> index.html" and below is my folder structure. enter image description here -
Issue with url returned after login with facebook/google + in an django app
I am building an app using django 1.11 and providing users option to Login with Facebook and Login with Google. For this I am using social-auth-app-django 1.2.0. On successful login, I redirect it to a page – UserProfile.html – setting.py AUTH_PROFILE_MODULE = 'home.UserProfile' where home is an app. urls.py of project (say myProject) url(r'^myProject/',include('home.urls')), url('^complete/facebook/', include('home.urls')), url('^complete/google-oauth2/', include('home.urls')), urls.py in home app url(r'^ UserProfile.html',views. UserProfile,name=' UserProfile ') But the url generated after Login with Facebook is – http://localhost:8000/complete/facebook/UserProfile.html#= which should have been - http://localhost:8000/myProject/UserProfile.html Similar is the issue when user tries Login with Google. URL generated – localhost:8000/complete/google-oauth2/UserProfile.html# which should have been – localhost:8000/myProject/UserProfile.html Please assist and let me if I am missing something. -
Django + nginx + uwsgi how to use one domain to build multiple application?
My question is how can I use one domain (mydomain.com) to build multiple django server? This is my nginx.conf, upstream django_myproject { server unix:///home/frank/myproject/haunyu.sock; # for a file socket } server { listen 80; server_name mydomain.com; # This is my ow charset utf-8; client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/frank/myproject/media; } location /static { alias /home/frank/myproject/static; } location / { uwsgi_pass django_myproject; include /home/frank/myproject/uwsgi_params; # uwsgi_read_timeout 600; } } I try to let location "/" replace to location "/first_app" like this location /frist_app { uwsgi_pass django_myproject; include /home/frank/myproject/uwsgi_params; # uwsgi_read_timeout 600; } } Then I try to type domain/frist_app to browser, I got 404, My uwsgi also has no contact message. -
Why is Django connection.cursor query failing?
I am getting the following error message when trying to execute a cursor query against a SQLite3 database: My code is as follows: qry = ('select balancer_security.id, balancer_security.name, balancer_security.symbol, ' 'balancer_securityprice.at_dt, balancer_securityprice.price, balancer_securityprice.notes ' 'from balancer_security LEFT OUTER JOIN balancer_securityprice ' 'ON (balancer_security.id = balancer_securityprice.security_id ' 'AND balancer_securityprice.at_dt="?") ' # 'AND balancer_securityprice.at_dt="%s") ' 'ORDER BY balancer_security.name') from django.db import connection cursor = connection.cursor() cursor.execute(qry, [date]) solution = cursor.fetchall() The error occurs on the cursor.execute line. date is a string containing the value 2017-10-05 Also, is the parameter put into the query within django or is it passed to SQLite (i.e. should my parameter placeholder be %s or ?)? Thanks!