Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: DateTimeField taking UTC format only, not others
The time that is being inserted in database is default UTC, not the timezone based time..I do not understand why is this happening, even though I am particularly specifying, in the query, the time that I want to be inserted. In my Model I have class leave(models.Model): date_created = models.DateTimeField(auto_now_add=True) In my settings I have TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True In my views i am setting timezone based on employee country if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND': tzone=pytz.timezone('Asia/Calcutta') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA': tzone=pytz.timezone('Asia/Manila') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS': tzone=pytz.timezone('CST6CDT') And then I am creating leave and updating timezone based on country new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des,date_created=datetime.now(tzone)) new_leave.save() Thanks in Advance. -
Django - runserver error- value error: source code string cannot contain null bytes
I just started learning django and I was trying out some tutorials online. Please help. This is just a small web app the accepts user input and displays it on the message board. I am using windows and django 1.11.7. I use sublime text editor for python. I am not sure whAt the error means. If somebody could help, it would be of great help. This is the error that I got: ` Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03BF8F18> Traceback (most recent call last): File "C:\dev\message_board\mb\lib\site-packages\django\utils\autoreload.py", l ine 228, in wrapper fn(*args, **kwargs) File "C:\dev\message_board\mb\lib\site-packages\django\core\management\command s\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\dev\message_board\mb\lib\site-packages\django\core\management\base.py ", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\dev\message_board\mb\lib\site-packages\django\core\management\base.py ", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\registry.py ", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\urls.py", l ine 16, in check_url_config return check_resolver(resolver) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\urls.py", l ine 26, in check_resolver return check_method() File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin e 254, in check for pattern in self.url_patterns: File "C:\dev\message_board\mb\lib\site-packages\django\utils\functional.py", l ine 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin e 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\dev\message_board\mb\lib\site-packages\django\utils\functional.py", l ine 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin … -
Unknown column 'userprofile.id' in 'field list
I ma getting this error while calling save method. the error is Unknown column 'userprofile.id' in 'field list class Userprofile(models.Model): user = models.OneToOneField(User) profile_id = models.IntegerField(db_column='profile_id') # Field namemade lowercase. f_name = models.CharField(max_length=45, blank=True, null=True) middle_name = models.CharField(max_length=45, blank=True, null=True) l_name = models.CharField(max_length=45, blank=True, null=True) dob = models.DateField(db_column='DOB', blank=True, null=True) # Field namemade lowercase. contact_number = models.IntegerField(blank=True, null=True) email = models.CharField(max_length=45, blank=True, null=True) joining_date = models.DateField(db_column='Joining_date', blank=True, null=True) # Field name made lowercase. temp_address = models.CharField(max_length=45, blank=True, null=True) permanant_add = models.CharField(db_column='Permanant_add', max_length=45, blank=True, null=True) # Field name made lowercase. user_image = models.CharField(max_length=45, blank=True, null=True) # group_idgroup = models.ForeignKey(AuthGroup, models.DO_NOTHING, db_column='group_idgroup') gender_idgender = models.ForeignKey(Gender, models.DO_NOTHING, db_column='gender_idgender') class Meta: managed = False db_table = 'userprofile' unique_together = (('profile_id', 'gender_idgender'),) This is my model -
How to display django project in web browser as website?
Someone gave me django project to make it with front-end, I can't open it to see the design. what can i do? -
What is the need for forms in Django?
I am a noob in Python/Django and want to know what additional benefits Django forms offer compared to html forms? From what I have seen in a few tutorials, Django forms are mostly used for front-end validation only, which can also be done by html/JavaScript, so why should I use Django forms? -
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?