Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to control template rendering based on if returned errors? Django
I want to show a loading GIF after the user submits the form but not if the user failed to fill a required field and received a form filling error. This is what I did: {% if not profile_form.errors %} <input type="submit" value="Submit" class="btn btn-primary btn-lg " onclick="loading();" /> {% else %} <input type="submit" value="Submit" class="btn btn-primary btn-lg" /> {% endif %} The onclick="loading(); loads the GIF. But it doesn't work. It whether shows the GIF on both cases or on neither. -
GoogleApp engine error accesing db "psql: FATAL: conversion between WIN1252 and UTF8 is not supported" (django flexible tutorial)
I am following the google app engine "Running Django in the App Engine Flexible" Environment(https://cloud.google.com/python/django/flexible-environment) and I am stuck in the point "Run the app on your local computer", when I try to run the migrations. When I run the command python manage.py makemigrations it shows the error FATAL: password authentication failed for user "postgres" After that, I try connect to the database manually with these instructions gcloud beta sql connect djangomodelspos --user=postgres and psql "host=127.0.0.1 sslmode=disable dbname=polls user=postgres" and they both prompt the same error: FATAL: conversion between WIN1252 and UTF8 is not supported I supposed that the first error( "password authentication failed for user "postgres") could be due the WIN1252 and UTF8 conversion problem of the password so I tried to fix the problem following these instructions PostgreSQL: encoding problems on Windows when using psql command line utility After that, I am able to connect with the db using psql "host=127.0.0.1 sslmode=disable dbname=polls user=postgres" but I am still not able to run makemigrations. I think that the password is not being converted, and therefore the same error. How could I fix this? -
Executing html function in Django template
I have one django template which has one button. All i want is that when i click this button it will include another template and show the contents. <button data-toggle="modal" id="myClickButton" href="#dbModal" type="button" class="btn btn-info pull-right custom" >Bookmark</button> The above is my button and it is linked with a modal. In the modal, I am saving a dictionary in a file using a Django template tag. So i am including the new html with arguments like below. {% include "app/return_info.html" with "dict" "String"} I tried several methods but Django runs this include command without waiting for button and when i click the button, nothing happened. Modal is displayed but no data is saved. -
Django Graphos Chart Not Loaded On Table Update Using Ajax
I have been using django graphos and it works fine till i realize that the chart is not drawn when i update my table through ajax instead of a page refresh. Let me describe the issue further. When my page is loaded for the first time, all the charts are loaded properly using {{chart.as_html}} . I am usng django by the way . This charts are displayed in a table. But when user selects different value from a dropdown and click reload, my code will only update the table through ajax instead of a whole page refresh. Unfortunately , when the table is updated, the chart with new data is not displayed. It just appears blank. I can see all the data from the developer tools but the chart just fail to appear. I have checked through various topics but I am unable to get it working. Any help is greatly appreciated. -
Django Rest fields grouping and customising
I have a Django models like so: class Floor(models.Model): name = models.CharField(max_lenght =100) class Point(models.Model): created_at = fields.UnixDateTimeField(auto_now_add=True) updated_at = fields.UnixDateTimeField(auto_now=True) floor = models.ForeignKey(Floor) device = models.CharField(max_lenght=100) creates_at and updated_at are just custom fields with timestamps. So, i need to send request like points/?start=x,end=y,timeslice=z and want to have JSON like so: { floor_id: floor_id slice: first timestamp of first slice count: count of devices in this slice }, { floor_id: floor_id slice: first timestamp of second slice count: count of devices in this slice }, ... Propably, i need to customise my serializers, using django-filters and write spetial view for this purpose, but i have no ideas how to put it together -
Django rest swagger nested serializer showing list of array in Example UI
Django Rest Swagger is not able to parse the Inner Serializer as an array of objects instead it shows only list of string My Serializers: class InfluencerSerializer(serializers.Serializer): prices = PriceSerializer(many=True) first_name = serializer.CharField(max_length=100) class PriceSerializer(serializers.Serializer): cost = serializers.IntegerField(default=0) On Swagger UI it appears as below json in Example { "first_name": "string", "prices": ["string"], } While I am expected Swagger UI to show { "first_name": "string", "prices": [ {"cost":0} ], } I am using Django==1.10.6 djangorestframework==3.6.1 django-rest-swagger==2.1.2 -
Django forms. How add, search data to form field from database
I have 2 models. class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Reservation(models.Model) person = ForeiginKey(Perrson, on_delete=models.PROTECT) from_date = models.DateField() to_date = models.DateField() I want make reservation. How make form in order that first field "person" can search person and add found data to form field, if person not exist add new person. -
Store trace of nested method-calls
Today I work on a legacy python application which imports mails. Some "magic guessing" does happen during that import: Mail header get examined and actions according to this examination happens. I have some, but not 100% understanding of the internals. To trace errors, I have the vague idea to store the lines and method calls executed by the python interpreter. import_mail(file_path) How to trace what happens during import_mail()? I would like to use JSON as data format. Which data schema can be used to store the trace? To avoid information bloat, I would skip everything which happens inside the python standard library and everything which happens inside django. If the "magic guessing" was wrong, I hope that this trace can help me to track down the problem. -
How to create Links that are independent from each other (Python Django)
i am currently working on a little Django Project where I display two different Albums and their Songs (on different URLs). Now I wanted to create a list of Links where you can listen to the different Songs. How can I create the links for example on localhost/music/1(album_id)/ so that they are not displayed on the website of Album 2. Code views.py: def albums(request): album_list = Album.objects.all() return render(request, 'music/index.html', {'album_list' : album_list}) def songs(request, album_id): album = get_object_or_404(Album, pk= album_id) return render(request, 'music/detail.html', {'album': album}) my index.html template: <ul> {% for album in album_list %} <li><a href = "/music/{{album.id}}/">{{album.artist}} - {{album.title}} </a></li> {%endfor%} detail.html: <ol> {% for song in album.song_set.all %} <li>{{song.song_title}} </li> {% endfor %} -
get current socially logged in account django
I am using multiple social authentications like google, likedin,github etc my django web app.How can i check which is the current logged in social account? is there any direct methods like request.user.get_currentsocialaccount() -
django-directmessages into my project
Am building a dating site so i need to add user to user messaging so i got this website https://pypi.python.org/pypi/django-directmessages. After I have successfully "install django-directmessages in my Project" ADD THE RIGHT CODE TO MY "HTML PAGE" ie dashboard.html has been a big issue. On the link above i cant find where the "HTML" was mention even in the "VIEWS.PY of the APP" only "from directmessages.apps import Inbox" was mention and i know there are more to be done to it the django-directmessages display on my html page ie dashboard.html -
save() doesn't work in Mongoengine
I'm trying to perform a simple insert operation using Mongoengine and Django. Regarding my project structure simply I have a project, AProject and an app, AnApp. I have a running mongo in a remote machine with an IP of X.X.X.X. I am able to insert document using Robomongo in it. I have removed the default Database configuration part of the settings.py located inside the AProject directory. The newly added lines are shown below: # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases import mongoengine # ----------- MongoDB stuff from mongoengine import register_connection register_connection(alias='default', name='AProject', host='X.X.X.X') # ---------- Now let me show the models.py and the views.py located inside AnApp. models.py from mongoengine import Document, StringField class Confession(Document): confession = StringField(required=True) views.py from django.http import HttpResponse from models import Confession from mongoengine import connect def index(request): connect('HacettepeItiraf', alias='default') confession = Confession() confession.confession = 'First confession from the API' print(confession.confession + ' Printable') # The output is --First confession from the API-- print(confession.save()) # The output is --Confession object-- return HttpResponse(request) The urls.py located inside AProject is simply as below: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^confessions/', include('confession.urls')), url(r'^admin/', admin.site.urls), ] When I enter http://127.0.0.1:10000/confessions/ I see a blank screen which … -
Django adding the values of reverse foreign key as field while returning
I have two models. One is Task model and other is reward model. class Task(models.Model): assigned_by = models.CharField(max_length=100) class Reward(models.Model): task = model.ForeignKey(Task) Now I want to return a queryset of Task along with the reward field in it. I tried this query. search_res = Task.objects.annotate(reward='reward'). I got this error: The annotation 'reward' conflicts with a field on the model. Please tell how to solve this. I want an field reward in each task object. -
where does Django store datatype to UI component mapping
I am trying to build a Django-like admin UI for a Spring-boot application. One of the parts is to create a mapping between datatypes and UI components. Could anybody share how and where does Django store the mapping between datatypes like number, string, boolean and UI components like textfield, datepicker, radio button, checkbox etc. Also, I believe we must have a tag django-internals on Stackoverflow. -
Ajax query not working in python django?
I want to change the status of data coming from table but it seems like like i have messed up some code in it. my ajax request:- function changeStatusDataById(object) { var baseURL = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : ''); var r = confirm("Are You sure we want to change status ?"); if (r == true) { var requestData = {}; var action = object.getAttribute("action"); var id = object.getAttribute("id"); requestData.action = action; requestData.id = id; $.ajax({ url: baseURL + 'promoted-user/list/changeStatus/', method: 'POST', dataType: "json", contentType: "application/json", data: JSON.stringify(requestData), beforeSend: function () { var text = 'changing status . please wait..'; ajaxLoaderStart(text); }, success: function (data) { ajaxLoaderStop(); location.reload(); }, error: function (jqXHR, ex) { ajaxLoaderStop(); } }); } return false; } my django url:- url(r'^promoted-user/list/changeStatus/$', delete.promoter_change_status, name='promoter-change-status') my views:- @login_required @csrf_exempt def promoter_change_status(request): response_data = dict() message = '' status = "ERROR" if request.method == "GET": message = "GET method is not allowed" if request.method == "DELETE": message = "Delete method is not allowed" if request.method == "POST": request_data = body_loader(request.body) print 'hello' try: action = request_data['action'] id = request_data['id'] if action is not None and id is not None and action != '' … -
pk__in raises EmptyResultSet exception in OSQA(Django). Any workarounds?
The following is the Exception Info: Traceback (most recent call last): File "lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "forum/views/readers.py", line 270, in search return question_search(request, keywords) File "forum/modules/decorators.py", line 95, in decorated return decoratable(*args, **kwargs) File "forum/modules/decorators.py", line 55, in __call__ res = self._callable(*args, **kwargs) File "forum/views/readers.py", line 306, in question_search feed_url=feed_url, feed_sort=rank_feed and (can_rank,) or '-added_at') File "forum/views/readers.py", line 240, in question_list 'questions_count' : questions.count(), File "forum/models/base.py", line 107, in count cache_key = self.model._generate_cache_key("CNT:%s" % self._get_query_hash()) File "forum/models/base.py", line 187, in _get_query_hash return md5(str(self.query)).hexdigest() File "lib/python2.7/site-packages/django/db/models/sql/query.py", line 175, in __str__ sql, params = self.sql_with_params() File "lib/python2.7/site-packages/django/db/models/sql/query.py", line 183, in sql_with_params return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() File "lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 93, in as_sql where, w_params = self.query.where.as_sql(qn=qn, connection=self.connection) File "lib/python2.7/site-packages/django/db/models/sql/where.py", line 132, in as_sql raise EmptyResultSet EmptyResultSet This is my query: self.filter(models.Q(id__in=qIDs)) where qIDs is a list of ids which may be empty. It may be irrelevant, but I am using elasticsearch in osqa revision 1285 and I've changed their code in /forum/modules/question.py. Also I've disabled mysqlfulltextsearch. I searched for this thing online and it says it's a bug in django. Since, the error doesn't produce an empty list on the webpage and displays a server error insted, it … -
deleting multiple rows using check boxes with jquery in django?
deleting multiple rows using check boxes with jquery in django??? def lead_delete(request, id): success_dict = {} task_del =Lead.objects.filter(id=id) if request.method== "GET": task_del.delete() success_dict['success_msg'] = "Successfully Deleted lead" return redirect('sales_manager_dashboard') url(r'^lead/delete/(?P<id>\d+)/$','lead_delete',name='lead_delete'), <div class="panel panel-default"> <div class="panel-heading"> {% if request.user|has_group:"sales rep" or request.user|has_group:"sales manager" %} <div class="col-md-11"> <h4>Leads/Enquiries</h4> </div> <!-- <button type="button" class="btn btn-primary" data-toggle="modal" data-url="{% url 'ImportWorkItem' %}" data-title="CSV Import" data-target=".bs-example-modal-lg" style="color: ">CSV</button> --> <button type="button" class="btn btn-primary" data-toggle="modal" data-url="{% url 'export_leads_form' %}" data-list-div-url="{% url 'export_leads_form' %}" data-title="Add Enquiry" data-target=".bs-example-modal-lg">Export</button> <button type="button" class="btn btn-primary" data-toggle="modal" data-url="{% url 'lead_add' %}" data-list-div-url="{% url 'leads_list' %}" data-title="Add Enquiry" data-target=".bs-example-modal-lg">New</button> {% else %} <div class="col-md-11"> <h4>Leads/Enquiries</h4> </div> <button type="button" class="btn btn-primary" data-toggle="modal" data-url="{% url 'export_leads_form' %}" data-list-div-url="{% url 'export_leads_form' %}" data-title="Add Enquiry" data-target=".bs-example-modal-lg">Export</button> {% endif %} </div> <div class="panel-body " style="overflow:scroll"> <form> <table id="lead_list_table" class="table table-bordered hover" data-url="{% url 'leads_list' %}" cellspacing="0" width="100%"> <thead> <tr class="headings"> <th><input type="checkbox" id="selectall"/></th> <th>Company</th> <th>Contact Person</th> <th>Email</th> <th>Phone</th> <th>Country</th> <th>Lead Date</th> <th>Next Followup</th> <th>Lead Status</th> <th class="no-link last"><span class="nobr"></span> </th> </tr> </thead> <tbody> {% for lead in leads %} <tr class=""> <td class=""><input type="checkbox" class="checkbxcolor" id="lead"></td> <td class=" "><a data-url="{% url 'leads_view' lead.id%}" id="lead" data-toggle="modal" data-title="View Enquiry" data-target=".bs-example-modal-lg">{{ lead.title }}</a></td> <td class=" ">{{ lead.contact_name }} </td> <td class=" ">{{ … -
Django LDAP Authentication Setting:Providing password,username securely
Hi I am developing a tool using the django.I have required the Django LDAP authentication so that each user of our organization can login to this tool using their windows user name and password. Now the problem starts here: This is the configuration we do in setting.py file in our django project. import ldap from django_auth_ldap.config import LDAPSearch, NestedActiveDirectoryGroupType # Binding and connection options AUTH_LDAP_SERVER_URI = "ldap://domain.example:389" AUTH_LDAP_BIND_DN = "CN=Bind_User,OU=Users,DC=domain,DC=example" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0, } # User and group search objects and types AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=Users,DC=domain,DC=example", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("OU=Groups,DC=domain,DC=example", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() # Cache settings AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 300 # What to do once the user is authenticated AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_staff": ["CN=Djano_Users,OU=Groups,DC=domain,DC=example", "CN=Django_AdminUsers,OU=Groups,DC=domain,DC=example"] } AUTH_LDAP_FIND_GROUP_PERMS = True # The backends needed to make this work. AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend') As you can see I require username and password to bind my application to the LDAP server. AUTH_LDAP_BIND_DN = "CN=Bind_User,OU=Users,DC=domain,DC=example" AUTH_LDAP_BIND_PASSWORD = "password" The LDAP server is handled by our IT department.They refuse to give me username and password of that LDAP server because it may happen … -
Reverse for 'detail.view' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
My urls.py looks like this urlpatterns= [ url(r'^$', views.detail, name= 'detail' ), url(r'^testapp/(?P<pk>[0-9]+)/$', views.image_detail, name='image_detail'), ] views.py looks like this from django.shortcuts import render from django.core.urlresolvers import reverse from .models import Album def detail(request): all_album = Album.objects.all() return render(request, 'testapp/detail.html', {'all_album' : all_album }) def image_detail(request, pk): album = get_object_or_404(Album, pk=pk) return render(request, 'testapp/image_detail.html', {'album' : album }) detail.html template is this: {% include "navbar.html" %} <div class="container"> <div class="row"> <div class="col-sm-4"> {% for image in all_album %} <a href="{% url 'testapp:image_detail' pk=album.pk %}"> <img src="{{ album.image.url }}" height="420"></a> {% endfor %} </div> </div> </div> I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated. -
calling class based view from different app in the same django project
I have a django project which has 2 app (call them app1, app2). app1 app1 has a view(DRF's model viewset) call it MyViewset(viewsets.ModelViewSet). this view has two actions (action1 which is GET and action2 which is POST). in urls.py I'm calling this view as urlpatterns = [ url(r'^$', MyViewset.as_view({'get': 'action1', 'post': 'action2'}), name="myviewset"), ] this is working fine, i mean i'm able to use these two apis directly. currently i'm calling GET api directly in my another view which is in app2. but to avoid http call i was trying to call above viewset directly as below view = MyViewset.as_view({'get': 'action1'})(request) resp = view.render().data but it returns method POST not allowed. if I pass both action view = MyViewset.as_view({'get': 'action1', 'post': 'action2'})(request) I get django.http.request.RawPostDataException: You cannot access body after reading from request's data stream. What is the best way to access only GET action? PS: I'm using Python3.5, Django==1.11.1 and djangorestframework==3.6.3 -
How do I get Amazon s3 private uploads/downloads working in my django views when they work in the admin?
I am trying to get uploads and downloads with amazon private s3 but am unable to get full circle with it. I have gotten pretty close but it had a but of a funny behavior as noted below. What works Upload from the admin. Download from admin. Download from my template using the my_team view What doesn't work Uploads from the views+templates I create won't change the database at all. Uploads, oddly, act as the form is valid, and even act like the upload occurred with no change when you look in the admin panel. ** Version ** Django version 1.9.7 My Relevant View def my_team(request, challenge): """A page showing details of a teams in a challenge.""" # Find the team that this user belongs to... team = Team.objects.filter(challenge=challenge, members__id=request.user.id).first() # Boot them out if they are not in any team. if not team: return redirect('challenges_list') special_form = SpecialForm(instance=team) upload_complete = False # POST if request.method == 'POST': special_form = SpecialForm(request.POST or None, request.FILES, instance=team) if special_form.is_valid(): special_form.save() upload_complete = True # this template us also used in team-details return render(request, 'challenges/team_details.html', { 'challenge': challenge, 'upload_form': special_form, 'team': team, 'special_form': special_form, 'upload_complete': upload_complete }) My Relevant Model special_storage = storages.backends.s3boto.S3BotoStorage( … -
Passing 2 variables to 2 different html pages on django
I have 2 variables a,b(say) and 2 html pages x.html and y.html. I have a function called getdetails(), Where I get the details of a,b from the db and I want to send the 'a' value to x.html and b value to y.html while redirecting to x.html in the return.render() of getdetails() .How can I do that? -
No encoding declared
I keep getting this error: SyntaxError: Non-ASCII character '\xe4' in file /var/www/mooimom_django/mooimom_tw/models.py on line 716, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details because of: subdistrict_destination_text = models.CharField(verbose_name=pgettext_lazy('taiwan-models Shopping_Cart', "Subdistrict Destination Text"), max_length=255, default='100 中正區') How to solve this problem? thanks -
Display Product(Object) info when user clicks on it
Right now I'm making an ecommerce store, but I can't wrap my head around displaying specific object info (in this case a Product instance) when a user clicks on it. So here's my views.py: def product_page(request): all_products = Product.objects.all() quantity_forms = QuantityForms(request.POST) quantity = request.POST.get('amount') grand_total = RevenueInfo.user_total current_user = request.user #buyer = User. if quantity > 0: #ExtendedProfile().amount_spent += (quantity * Product.price_CAD) #RevenueInfo().user_total += int(quantity) return HttpResponse(current_user.product_set.all()[0].description) return render(request,'tracker/product_page.html', {'all_products':all_products, 'quantity_forms':quantity_forms}) def product_details(request): product = Product.objects.all() return render(request, 'tracker/product_details.html', {'product':product}) models.py: class Product(models.Model): purchase = models.ManyToManyField(settings.AUTH_USER_MODEL, through="Purchases") category = models.CharField(max_length=100) name = models.CharField(max_length=100) description = models.TextField() #photo = models.ImageField() price_CAD = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.DecimalField(max_digits=2, decimal_places=0, null=True, editable=True) def get_absolute_url(self): return reverse("product_details") And my product_page.html: {% load staticfiles %} <!DOCTYPE html> <!DOCTYPE html> <html> {% for object in all_products %} <h3><a href="{{ object.get_absolute_url }}">{{ object.name }}</a></h3> <p>{{ object.description }}</p> <p>{{ object.price_CAD }}</p> {% endfor %} </html> Basically I'm not getting the logical flow of information, by get_absolute_url is running in my Product model when I click on one of the product links, which references my product_details view, but from there how do I refer to the individual product instance that was clicked on, then display it's unique attributes … -
Problems with ajax in django-el-pagination app
I am tring to use django-el-pagination app cause I need pagination with ajax. In my page I have several blocks with list of entry. I have very strange problem. 1) First of all it seems to me that ajax dont work. When I click to other page it update all page not currect block. 2) Second problem you can see in the picture below. When I go to other page I see this strange thing. How to fix it? home.html: {% block content %} <div class="card"> <div class="card-block endless_page_template"> {% include "home/currect_projects.html" %} </div> </div> <div class="card"> <div class="card-block endless_page_template"> {% include "home/archive_projects.html" %} </div> </div> {% endblock %} {% block script %} {{ block.super }} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{% static 'el-pagination/js/el-pagination.js' %}"></script> <script>$.endlessPaginate();</script> {% endblock %} views.py: @page_template('home/currect_projects.html', key='currect_projects') @page_template('home/archive_projects.html', key='archive_projects') def home(request, template='home.html', extra_context=None): context = { 'archive_projects': Project.objects.filter(status='close').order_by('-revision_date'), 'currect_projects': Project.objects.filter(status='open').order_by('-revision_date'), } if extra_context is not None: context.update(extra_context) return render(request, template, context) currect_projects.html: {% load el_pagination_tags %} {% paginate 1 currect_projects %} {% for currect_project in currect_projects %} {{ currect_project .name }} {{ currect_project .description|truncatewords:20 }} {% endfor %} {% show_pages %} NORMAL POSITION: GO TO 2 PAGE OF CURRECT PROJECTS BLOCK: