Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying fill a datatable from a json serialized by django
I am trying fill a datatable from a json serialized by django and for to do it I try as follows HTML <table id="table"> <thead> <tr> <th>Name</th> <th>Options</th> </tr> </thead> </table> JavaScript $(document).ready(function() { list(); }); var list = function() { var my_table = $('#table').DataTable({ "ajax": { "processing": true, "url": "/get_json/", "dataSrc": "" }, "columnDefs": [{ "targets": -1, "data": null, "defaultContent": "<button>View</button>" }] }); $('#table tbody').on('click', 'button', function(){ var data = my_table.row($(this).parents('tr')).data(); }); } I receive a json that was serialize in a view in Django with the next format: [ { "model": "application.model", "pk": 1, "fields": { "name": "Name", "path_icon": "/path/icon.png" } } ] Simply serialize a queryset: serializers.serialize('json',Model.objects.all()) I want show in the column Name the name received in the json and in column Options a button that redirect to another page using the pk of the model, but when I try to do this receive the next message error: DataTables warning: table id=tabla-model - Requested unknown parameter '0' for row 0, column 0. help in documentation -
How to make a set of forms in a div into a JSON dictionary and then pass it to a django view
So I have a jQuery function which will append a form to a div of forms. The code for this here: <div id = 'questions'> </div> <button id="newquestion">Add question</button> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript"> var question_form = '<div><form><label>Question: </label><input type="text"/><br><label>Numeric: </label><input type="checkbox"/></form></div>' //Builds the questions $(document).ready(function() { //Selector where you will add your questions var placeholder = $("#questions"); // Selector for the button var add_button = $("#newquestion"); $(placeholder).append(question_form); // Adding new fields when the user click the button $(add_button).click(function(e){ e.preventDefault(); $(placeholder).append(question_form); }); }); </script> The user is able to add as many or as little questions as they wish. I am passing this information to a django view. I want to do this by turning it into a json dictionary, and then pass it to my view. How do I do this? -
HTML/Django/Jinja/Python : How to post a fixed value back
This is a HTML template that displays all of the proposals in a database (passed through views.py as a list in the dictionary parameter). I then use a jinja for-loop to go through all the proposals in the database and display their attributes. How can I Post-request the {{ proposal.id }} back to my python code when the "Learn more" button is clicked? I need this to allow me to display the corresponding values in my other html template. Sorry if this is a basic question, i'm a high school student and extremely new to django! Thanks alot in advance! {% block body %} {% for proposal in proposals %} <div class="jumbotron"> <h2> Proposal : {{ proposal.title }} </h2> <h4> Status : {{ proposal.status }} </h4> <h4> Out of --- Votes: </h4> <div class="progress"> <div class="progress-bar progress-bar-success" style="width: {{ proposal.votes_for }}%"> <span class="sr-only">35% Complete (success)</span> {{ proposal.votes_for }}% For </div> <div class="progress-bar progress-bar-danger" style="width: {{ proposal.votes_against }}%"> <span class="sr-only">10% Complete (danger)</span> {{ proposal.votes_against }}% Against </div> </div> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p> </div> -
How to pass context variable from template to views.py in python django?
Suppose I have this my views.py def exampleclass1(request): #do other things examplevar = request.POST.getlist('id[]') data_dicts = [{'id': id} for id in examplevar] for data in data_dicts: master_data=ExampleModel.objects.get(id=data.get('id')) master_data.save() context={ 'sampleid':examplevar, } #do other things return render(request, 'examplepage.html',context) In my examplepage.html, I have this line: <a href="{% url 'exampleclass2' sampleid %}"></a> My exampleclass2 looks like this in my views.py : def exampleclass2(request,sampleid): examplevar = sampleid data_dicts = [{'id': id} for id in examplevar] for data in data_dicts: master_data=ExampleModel.objects.get(id=data.get('id')) master_data.save() What I am trying to do is pass 'sampleid' context variable from 'exampleclass1' to 'examplepage' template and then pass that 'sampleid' from 'examplepage' template to 'exampleclass2'. What will be my urlpattern in my urls.py ? How can I achieve this ? -
Get email address of user from twitter in django using allauth
I need to get email address from twitter. And i have added policy URL and Terms of Service URL in Twitter App settings. And enable checkbox of request for email address. And in django settings.py file: SOCIALACCOUNT_QUERY_EMAIL = True Anything else missing? and Sorry, But i am also not getting how to get in views.py. Thanks. -
whether it is necessary to add status_code and msg in response of rest framework APIs? If is , how to do with that?
How to add status_code and msg to a rest framework api? If we use the rest framework to write APIs, the Response will be like bellow JSON data: But, you know, in the Java APIs, we usually returns API data like bellow format: { "status_code":200, "msg":"success", "data":[the_data] } the_data is the data list like upper snapshot data. So, whether it is necessary to add status_code and msg in response of rest framework APIs? If is , how to do with that? -
Translate Chinese characters to english letter(pinyin) as slug
In Django, I want to convert Chinese characters to pinyin as slug. for instance: 旺顺阁鱼头泡饼 to 'wang-shun-ge-yu-tou-pao-bing'. Is there a shortcut to accomplish it using python? -
is there any way to display contents of .docx files as selected by a visitor on my django webapp?
i am creating a web application using django and i want to display the contents of docx files , edit those files and save it back to the local device. Is django capable of doing this. -
I wanna restrict length of letters in JSON value
I wrote in views.py like def index(request): id = request.POST.get('id', None) print(id) When i wrote index method's url in POSTMAN,and I wrote id in Key & 1000 in Value,so these data can be sent.I wanna restrict length of value's letters 1000 in max.I think widget is good for my ideal system but I did not use html so I cannot understand whether widget is good to my system or not. How should I restrict length of value's letters? -
django help login check
view.py username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('index') login success my view.py global_header.html {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} However, login verification is not possible globally there are two cases. return render(request, page_name, param) # if user.is_authenticated return True if another case. return HttpResponse(page.render(param)) # if user.is_authenticated return False So I can not use HttpResponse? -
Django: dynamic URL for user profiles
So I'm trying to make a pretty conventional dynamic URL profile pages for my users. So eg. www.website.com/profile/(username) I am getting an error of NoReverseMatch when I enter a valid username, and I do not know why. Here are snippets of my code urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^signup/$', accountsViews.signup, name="signup"), url(r'^logout/$', authViews.LogoutView.as_view(), name='logout'), url(r'^login/$', authViews.LoginView.as_view(template_name='login.html'), name="login"), url(r'^find/$', findViews.find, name="find"), # url(r'^profile/$', accountsViews.profile, name="profile"), url(r'profile/(?P<username>.+)/$', accountsViews.profile, name="profile"), url(r'^$', views.home, name="home"),] views.py def profile(request, username=None): if User.objects.get(username=username): user = User.objects.get(username=username) return render(request, "profile.html", { "user": user, }) else: return render("User not found") html file {% if user.is_authenticated %} {% url 'profile' as profile_url %} <li {% if request.get_full_path == profile_url %}class="active"{% endif %}><a href="{% url 'profile' %}"><span class="glyphicon glyphicon-user"></span> Profile </a></li> <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> Log Out</a></li> {% endif %} Also it if it helps, the error message is highlighting the "{% url 'profile' %}" part as the error, and claiming that it does not have a reverse match. However, in my urls.py, you can clearly see that I have done name="profile" Any help would be greatly appreciated. Thank you! -
Create customized DateTimeField
I am trying to implement a restaurants website to practice using Django. In models.py, I have a class called RestaurantLocation,with the following lines: class RestaurantLocation(models.Model): updated = models.DateTimeField(auto_now=True) I attempt to add a field visited to represent the first time I visited it. To accomplish it,I look through 'DateTimeField' DateField in django documentation. There are only two methonds of auto_now_add and auto_now without options to setup my own datetime. How to customize DateTimeField for my own datetime? -
How can I distinguish a user is AminUser or normal User in the custom User model?
I want to create a custom User by inherit the AbstractUser: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model But, there is a issue for me, when I use the permissions, there is a IsAdminUser permission. If I have two custom User models, such as User model, and AminUser model (all of them inherit form AbstractUser). How can I distinguish a user is AminUser or normal User in the custom User model? -
When develop a Django project, how to design the User model?
In Django project, there is a default User model, because in the database, there is auth_user table: So, when I create a the User model in models.py, whether I should inherit the django's User or inherit models.Model? Because I should use the permissions in my project. EDIT and, what's the Django's User model? if is the django.contrib.auth.models.AbstractUser? -
Django rest framework json web token logout function
First of all, i am still new to django rest framework jwt so pls excuse my stupidity if im wrong. Im wondering about how to create a logout function for jwt as when user want to logout and switch account, they will need this function. Based on the what i seen in many other logout post, - there is no need for logout function as the token isnt save on server side so closing and opening will result in having to login again. - jwt is using expire time for it so it will logout when the token has been expire , provided if the verify token is set to True But what i want is to have like a remember me function where user will stay login when they close and open again, as one of the suggestion is turn the verify token to false or set expire time to weeks. But then how does the user logout if the token expire time hasnt reach yet ? As i am using jwt and djoser, the logout function of djoser is for drf only and not for jwt. Since i am also using the api for mobile devices, so the … -
How to replace url paramater dynamically in html page with django?
Basically, I have a template which have a search form and a table to show the result. The result can be ordered if header column is clicked. I use get method in search form and sort the result's table by getting the last url. views.py if sort_by == "desc": order_by = order_by sort_by = "asc" else: sort_by = "desc" url = request.META.get('HTTP_REFERER') if (url != None): search_params = {} param = urlparse.urlparse(url) if (not 'search_button' in request.GET): get_request = re.split('&',param.query) for single_request in get_request: search_query = re.split('=',single_request) search_params[search_query[0]] = search_query[1] userlist = show_data(order_by,sort_by,search_params) else: userlist = show_data(order_by, sort_by, request.GET) def show_data(order_by, sort_by, get_data): //the function get the value from db return row template.py <table id="user-table"> <tr> <th><a href="?order_by=userId&sort={{sort}}">User id</a></th> <th><a href="?order_by=userName&sort={{sort}}">Name</a></th> <th><a href="order_by=userAddr&sort={{sort}}">Address</a></th> </tr> <tbody> {% for item in table_data %} <tr> <td>{{ item.userId|default_if_none:"" }}</td> <td>{{ item.userName|default_if_none:"" }}</td> <td>{{ item.userAddr|default_if_none:"" }}</td> </tr> The search form able to filter and table result can sort the data. Here is the sample url if the search button is clicked http://localhost:8080/userlist/?&userId=&userName=Jane&userAddr=&search_button=search url if the column header is clicked http://localhost:8080/userlist/?order_by=userAddr&sort=asc However, it cannot do sorting again since the the url changed and search_param did not get the userName=Jane Is it possible to replace url parameter … -
ImportError: No module named 'accounts' - Heroku
When trying to deploy to Heroku, I am receiving the following error: 22:06:03 web.1 | apps.populate(settings.INSTALLED_APPS) 22:06:03 web.1 | File "/Users/XXX/.envs/carla/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate 22:06:03 web.1 | app_config = AppConfig.create(entry) 22:06:03 web.1 | File "/Users/XXX/.envs/carla/lib/python3.5/site-packages/django/apps/config.py", line 94, in create 22:06:03 web.1 | module = import_module(entry) 22:06:03 web.1 | File "/Users/XXX/.envs/carla/lib/python3.5/importlib/__init__.py", line 126, in import_module 22:06:03 web.1 | return _bootstrap._gcd_import(name[level:], package, level) 22:06:03 web.1 | ImportError: No module named 'accounts' Installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_summernote', 'widget_tweaks', 'accounts', ... ] Project structure: - carla/ - carla/ - accounts/ - static/ - templates/ - config - settings/ - __init__.py - urls.py - wsgi.py - manage.py - Procfile - requirements.txt ... Would anyone know why Heroku isn't able to find my 'accounts' app? It works fine locally, and is obviously in my INSTALLED_APPS. Thank you in advance! -
Create an list/dictionary of form fields in Django
I want to create a list of unique radio select options for a game in Django that exponentially increases with each round. So in round 1, the player has 1 radio button to select from. Round 2, the player has 2 radio buttons to select from. Round 3, the player has 4 radio buttons to select from. Crucially, each of these forms needs to have a unique identifier so that the player can select all options for a particular round. For example, for round 3, my form contains the following code: <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision1 with label="" %}</p></td> </tr> <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision2 with label="" %}</p></td> </tr> <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision3 with label="" %}</p></td> </tr> <tr> <td class="tb" rowspan="2"><p {% formfield player.r3_decision4 with label="" %}</p></td> </tr> Player is then declared as a class in models.py, with player containing each of the form fields defined above as attributes. class Player(): r3_decision1 = models.CharField( choices=['A Option A','B Option B'], widget=widgets.RadioSelectHorizontal(), blank=False, initial='blank' ) r3_decision2 = models.CharField( choices=['A Option A','B Option B'], widget=widgets.RadioSelectHorizontal(), blank=False, initial='blank' ) r3_decision3 = models.CharField( choices=['A Option A','B Option B'], widget=widgets.RadioSelectHorizontal(), blank=False, initial='blank' ) r3_decision4 = models.CharField( choices=['A Option A','B … -
how can i fix this error ; resolver error in tests.py
enter image description here i got this error when run python manage.py test def test_update_status_using_index_func(self): found = resolve('/update-status/') self.assertEqual(found.func, index) -
how to redirect "print" command output to a file without changing the python code?
I want to redirect all the output of my django app to a file Firstly, I tried: python manage.py runserver 0.0.0.0:8000 >test.log 2>&1 But it doesn't redirect the output of print command. For example, in my code there is a statement: print ('query_content:') using command: python manage.py runserver 0.0.0.0:8000 I can see that 'query_content:' is printed out in the screen. But with : python manage.py runserver 0.0.0.0:8000 >test.log 2>&1 In the test.log, there are only something like this: [05/Nov/2017 20:38:20] "GET ... HTTP/1.1" 200 22404 [05/Nov/2017 20:38:26] "POST ... HTTP/1.1" 200 13 [05/Nov/2017 20:38:26] "GET .... HTTP/1.1" 200 16800 [05/Nov/2017 20:38:30] "GET ... 200 22430 ... One solution is: import sys sys.stdout = open('file', 'w') print 'test' But sometimes it is impossible to change the python code, is there any solution? -
Images not showing up with template tags in Django templates
I'm trying to display a user-uploaded image on my HTML template. I tried a bunch of template tags but none of them seem to be working. All the settings appear to be configured correctly. User-uploaded images are correctly uploaded to project_name/media/ settings.py MEDIA_URL = '/media/' MEDIA_ROOT = 'project_name' # Are the STATIC settings affecting the media settings? media is for user uploads so I don't think so? STATICFILES_DIRS = [ 'project_name/static/', ] STATIC_URL = '/static/' Things I tried in this HTML: # 'app.profileapp' is not the issue here. I can access other 'profileapp' attributes just fine (e.g. 'app.profileapp.agent_website' shows up just fine) <img src = "{{ app.profileapp.agent_picture }}" alt='My image' /> <img src = "{{MEDIA_URL}}{{ app.profileapp.agent_picture }}" alt='My image' /> <img src = "{{MEDIA_ROOT}}{{ app.profileapp.agent_picture }}" alt='My image' /> <img src = "{{ app.profileapp.agent_picture.url }}" alt='My image' /> <img src = "project_folder/{{ agent.agentpremiuminfo.agent_picture }}" alt='My image' /> <img src = "project_folder/media/{{ agent.agentpremiuminfo.agent_picture }}" alt='My image' /> -
Django DateTimeField Chunking, Averaging, and Reformatting
Here is the model I'm working with: class BTCPrice_kraken(models.Model): """ Defines BTC Price Model - Kraken """ id = models.AutoField(primary_key = True) date_time = models.DateTimeField(auto_now = True) code = models.CharField(max_length = 3) last_trade = models.FloatField() last_trade_volume = models.FloatField() ask = models.FloatField() ask_lot = models.FloatField() ask_whole = models.FloatField() bid = models.FloatField() bid_lot = models.FloatField() bid_whole = models.FloatField() open = models.FloatField() high = models.FloatField() high_24 = models.FloatField() low = models.FloatField() low_24 = models.FloatField() volume = models.FloatField() volume_24 = models.FloatField() I need a way to pull ranges from date_time, store all the keys in that range, average the data from keys in the range, and reformat the date_time response to look better than it does raw. For example: I want a 15 minute chunk of time from the DB (the objects are added in 1 minute increments). I want to average all the objects in this chunk and return the averages by column label. And list them by (%d, %m, %y, %h%h, %m%m). How would I go about building query's (preferably with list comprehension and django's built in db modelling) to do this? I'm using Postgres DB and stock Django. -
is there pywebview Alternatives that depend on chrome and not on safari
Is there's any similar or alternatives to Pywebview: https://github.com/r0x0r/pywebview While it depends on the version of installed Safari on OS X and QT. I am trying to make a desktop app out of Django project. but a lot of features (css & javascript) are not working well on Safari neither Pywebview, and works perfectly on chrome. After that it will be all encapsulated with py2app. Ps: Or, is there a way to make it depend on chrome. -
Django query - link 2 tables over 3rd
I have tables Company, City and linking table CompanyCity (this is just an example). class Company(Model): name = CharField() class City(Model): name = CharField() country = CharField() class CompanyCity(Model): company_id = ForeignKey(Company) city_id = ForeignKey(City) Can you please help to write an optimal query to get a list a companies with a distinct list of countries which their offices are placed in. For example we have such data: IBM - Washington, USA; Vancouver, Canada; Stockholm, Sweden; Microsoft - Washington, USA; Denver, USA; New York, USA; Toronto, Canada; I need to get: IBM - USA, Canada, Sweden Microsoft - USA, Canada -
django-admin: How to redirect to URL after one Object save?
I am using Django Signals to Trigger Code once the user is created i am saving additional data on another model class, it's getting triggered but it's not redirecting to additional data object page. Here is my models.py from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save class Customers(models.Model): user = models.OneToOneField(User) business_name = models.CharField(max_length=250) address = models.CharField(max_length=500) area = models.CharField(max_length=250) city = models.CharField(max_length=250) state = models.CharField(max_length=250) pincode = models.IntegerField(default='0') phone = models.IntegerField(default='0') mobile = models.IntegerField(default='0') def create_customer(sender, **kwargs): if kwargs['created']: customer_profile = Customers.objects.create(user=kwargs['instance']) post_save.connect(create_customer, sender=User) and here is my admin.py from django.contrib import admin from .models import Customers from django.shortcuts import redirect admin.site.register(Customers) class Customers(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): return redirect('/admin/app/customers/add/') def response_change(request, obj): return redirect('/admin/app/customers/add/') Tired looking for the answer but nothing works, please correct me here.