Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enable static for django-tinymce when using amazon-s3
The website on Django 1.10. Can't understand the work TinyMCE. The site statics are located on AWS S3. settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'orpro-assets' AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME) AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} REGION_NAME = 'us-east-1' AWS_LOCATION = 'static' AWS_MEDIA = 'media' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://{}/{}/".format(AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) AWS_PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = "https://{}/{}/".format(AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA) DEFAULT_FILE_STORAGE = 'app.storage_backends.MediaStorage' TINYMCE_DEFAULT_CONFIG = { 'theme': "lightgray", 'relative_urls': False} TINYMCE_JS_ROOT = STATIC_URL + 'tiny_mce' TINYMCE_JS_URL = STATIC_URL + 'tiny_mce/tiny_mce.js' TINYMCE_INCLUDE_JQUERY = False storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False When you load the home page, at the end of the load appears scripts that link to the folder static site. There are no such scripts in the templates. But the addition of the block is enabled: {% block additional_scripts %} {% endblock %} All other static files are loaded correctly with amazon-s3 -
How to get a duplicate instance on save in Django?
Supposing I already have a created instance of a Django's model. I want to get another instance that is a duplicate in the database. Is there a universal way to do it without finding out which unique index is responsible for this duplication: class MyModel(models.Model): ... instance = MyModel(...) print(instance.id) # None ... duplicate = get_duplicate(instance) print(duplicate.id) # Some ID in DB -
rendering 2 real time video to browser using flask
I tried with https://blog.miguelgrinberg.com/post/video-streaming-with-flask to render the webcam footage to the browser in real time. Similar to this, I need to render 2 different videos to the browser in real time (frame by frame). I tried editing the above-mentioned code to work for 2 different streams, but it didn't work. So please someone could help me in how to render 2/+ videos to a browser in real time using python flask or Django or any other library in python? Thanks in advance -
Error: 'Uncaught SyntaxError: Unexpected token <' (Django + React + Webpack)
I was following this tutorial to set up Django to serve templates with webpack-generated bundles. I have set it up just like in the tutorial. However the problem is when i go to localhost:8000 I get Uncaught SyntaxError: Unexpected token < exception when I open the console in chrome devtools. Other html I put in the template file gets rendered except the reactjs bundle. My folder structure is as follows: . ├── djangoapp │ ├── db.sqlite3 │ ├── djangoapp │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ ├── reactapp │ │ └── static │ │ ├── bundles │ │ │ └── main-fdf4c969af981093661f.js │ │ └── js │ │ └── index.jsx │ ├── requirements.txt │ ├── templates │ │ └── index.html │ └── webpack-stats.json ├── package.json ├── package-lock.json └── webpack.config.js settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates"), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } STATIC_URL = 'static/' webpack.config.js var path = require("path"); var webpack = … -
Logging in with e-mail as ldapUser in Django
I am currently working on my webapp. As of now, I can login with the username (sAMAccountName) but I want to login with the e-mail-adress. I looked up some backends, but none of them could help me. Here are my setting.py AUTH_LDAP_SERVER_URI = "ldap://192.168.4.123" AUTH_LDAP_BIND_DN = "username" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "dn": "distinguishedName", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=users,cn=users,DC=domain,DC=com", "is_staff": "CN=users,cn=users,DC=domain,DC=com", "is_superuser": "CN=users,cn=users,DC=domain,DC=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'stream_to_console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django_auth_ldap': { 'handlers': ['stream_to_console'], 'level': 'DEBUG', 'propagate': True, }, } } Maybe you have a good backend or I am missing something. I also tried: AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=sbvg,DC=ch", ldap.SCOPE_SUBTREE, "(mail=%(user)s)") but then it creates a user with the username user@domain.com, which is also wrong. If you have any advise, do not … -
Formsets validate_min is not working properlly
I have a formset with multiple forms: PodFormSet = forms.inlineformset_factory(parent_model=PodP, model=Prod, form=PofModelForm, min_num=1, max_num=4,validate_min=True, extra=3) The issues is that validate_min is not working properly: If the user complete another form than the first one, validate_min doesn't work, say is invalid, which is not, because at least a form is completed but not the first one. How can I override/fix this behavior ? -
How to serve user uploaded images with Django on Heroku in production
In my website an user can upload images. This works fine in development when DEBUG=True, but if I set it to False, the images give error "Not found". I understand that the images disappear after 30 minutes of inactivity, but for me they aren't working at all. I have Whitenoise installed on my settings.py middleware and on requirements.txt. On settings.py I also have these lines: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') And on urls.py I have this: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The user uploads the files to an ImageField. What do I have to change to make the user uploaded images also work on production? As the tile says, I'm deploying the project to Heroku. -
In django app received desktop apple device like a mobile device
I have an application in django, where I use http://detectmobilebrowsers.com/ to detect mobile devices or not. Unfortunately, the user agent gets to the Apple desktop: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Mobile Safari/537.36, where the words Android and Mobile are simultaneously and this redirects to mobile mode. My code in python: def local_detect_is_mobile(request): reg_b = re.compile( r"(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino", re.I | re.M) reg_v = re.compile( r"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-", re.I | re.M) user_agent = request.META.get('HTTP_USER_AGENT', '') b = reg_b.search(user_agent) v = reg_v.search(user_agent[0:4]) if b or v: return True else: return False There is some solution to broke this problem? -
Django: How to Iterate over an Object one by one in my View?
I am trying to write a Quiztool with Django. I have created an index where all surveys are listed. Clicking at one brings you in the detail view. Right now there are listed all questions with answers with a submit button going to nothing. What i am asking for is how to manage there will be only one question and when I submit the answer the next question will aply wihtout jumpin out of the detail view. If the answer is to easy i also would be happy for just getting a hint about what I have to read... Here is some Code from my views.py def detail(request, survey_id): #try: question = Survey.objects.get(pk=survey_id).question.all() question_dict = { 'question': question, } return render(request, 'survey/detail.html', question_dict) And here is my deatil.html {% if question %} <form method="post"> {% for x in question %} <fieldset style="width:10%;"> <legend>{{x.question_text}}</legend> {% for y in x.answer.all %} <p style="display: flex;justify-content: space-between;"> <label for="{{ y.answer_id }}">{{ y.answer_text }}</label> <input name="{{x.question_id}}" type="radio" value="{{y.answer_id}}" id="{{y.answer_id}}"/></p> {% endfor%} </fieldset> {% endfor %} <input type="button" value="Senden" onclick="var Sende=()=>{console.log('gesendet');}; Sende();"> </form> {% else %} <p>No questions are available.</p> {% endif %} Thank you in advance Flotzen -
missing default filters in django admin while applying bootstrap3
i had developed a project based on django-admin and when i have been changed the admin theme to django-bootstrap3 the default filters on admin panel are missing. these are the two screen shorts before bootstrap theme and after bootstrap this image is without bootstrap3 at the right side filters are visible this is the bootstrap image -
django InlineFormsets errors reporting with formset error list being empty
I have a strange error on creation using Django inline formsets. Django is reporting formset errors, so it doesn't finish the creation. Also I tested is_valid and it returns true. What is wrong ? but if I check them there is nothing in the dictionary of errors: 1. {{formset.errors}} [{}, {}, {}, {}, {}] 2. {% if formset.errors %} {% for error in formset.errors %} error {{ error }} {% endfor %} {% endif %} {} -
How to get userprofile in django 2.0
I read a few post already, but I couldn't find what I was looking for. I'm trying to figure out how to get the UserProfile of a user. I created a one to one field relationship when I create the User Profile. I thought I could just query the UserProfile as is, but I can't get it to work. def profile_edit(request): user = UserProfile.objects.get(user=request.user) return render(request, 'medium/profile_edit.html', {'user_profile_form': form, 'current_user': user}) Any thoughts? Here's my models.py and views models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) bio = models.TextField(blank=True) avatar = models.ImageField(upload_to='avatars', blank=True) views.py def register_user(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) user_profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and user_profile_form.is_valid(): new_user = user_form.save() new_user.set_password(new_user.password) new_user.save() new_user_profile = user_profile_form.save(commit=False) new_user_profile.user = new_user if 'avatar' in request.FILES: new_user_profile.avatar = request.FILES['avatar'] new_user_profile.save() registered = True else: print(user_form.errors, user_profile_form.errors) else: user_form = UserForm() user_profile_form = UserProfileForm() return render(request, 'medium/registration.html', { 'user_form': user_form, 'user_profile_form': user_profile_form, 'registered': registered }) -
Bug with default field django and postgresql
I have two models, Task and Order. Task has FK of Order, and Order has this field: foo = models.SmallIntegerField("Text", default=120, blank=True) When I save an Order from Task instance #Example t = new Task() #values of t t.order.save() Django throw me this error: null value in column "foo" violates not-null constraint In save method that i've implemented I have this (only for debug) t1 = self.foo ord = Order.objects.get(pk=self.pk) t2 = ord.foo Debugging I can check that t1 = None, and t2 = 120 -
How do you find the InlineModelAdmin from the admin context data?
I am trying to test that the correct form is used with an InlineModelAdmin I have set the custom form with: class RateInline(admin.TabularInline): model = Rate fk_name = 'project' extra = 1 form = RateForm However when I try to check that the RateForm is indeed being uses I get: a generated modelform: formsets = response.context['inline_admin_formsets'] ipdb> formsets[1].forms[0].__class__ <class 'django.forms.widgets.RateForm'> But I wanted the form used to be: <class 'billing.forms.RateForm'> Is this form only used during validation and the generated RateForm widget in the context data? -
Django where to place files other than images?
I have following defined in settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) and if there is an image in staticfiles/files/img.png , I can see that using http://localhost:8000/static/files/img.png but if there is another type of file for example: staticfiles/files/file.exe and I want to download it via http://localhost:8000/static/files/file.exe , then why it is showing the error Page not found (404) ? -
Heroku Server Error(500) : Error on checking user dashboard
On Registration and requesting user dashboard i get the following error : tux (master) CBT_therapy $ heroku logs 2018-03-06T09:16:49.883339+00:00 app[web.1]: - 10.79.228.240 - - [06/Mar/2018:09:16:49 +0000] "GET /static/admin/img/drwa.png HTTP/1.1" 200 - "https://nameless-island-79297.herokuapp.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0" 2018-03-06T09:16:49.885948+00:00 app[web.1]: - 10.45.77.75 - - [06/Mar/2018:09:16:49 +0000] "GET /static/admin/img/successstory.png HTTP/1.1" 200 - "https://nameless-island-79297.herokuapp.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0" 2018-03-06T09:16:50.643265+00:00 heroku[router]: - at=info method=GET path="/register/" host=nameless-island-79297.herokuapp.com request_id=34e1697c-e43b-4685-9cdb-9894705534bd fwd="14.139.246.27" dyno=web.1 connect=1ms service=72ms status=200 bytes=8700 protocol=https 2018-03-06T09:16:50.656447+00:00 heroku[router]: - at=info method=GET path="/favicon.ico" host=nameless-island-79297.herokuapp.com request_id=1efbb665-3b25-4bc9-979f-d2d73bba3367 fwd="14.139.246.27" dyno=web.1 connect=1ms service=5ms status=404 bytes=395 protocol=https 2018-03-06T09:16:50.642932+00:00 app[web.1]: - 10.33.225.156 - - [06/Mar/2018:09:16:50 +0000] "GET /register/ HTTP/1.1" 200 8205 "https://nameless-island-79297.herokuapp.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0" 2018-03-06T09:16:50.655146+00:00 app[web.1]: - 10.45.77.75 - - [06/Mar/2018:09:16:50 +0000] "GET /favicon.ico HTTP/1.1" 404 85 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0" 2018-03-06T09:17:17.135474+00:00 heroku[router]: - at=info method=POST path="/register/" host=nameless-island-79297.herokuapp.com request_id=020bc605-adf4-48e6-9a7a-aa528b40c0f9 fwd="14.139.246.27" dyno=web.1 connect=1ms service=82ms status=200 bytes=3884 protocol=https 2018-03-06T09:17:17.135129+00:00 app[web.1]: - 10.33.225.156 - - [06/Mar/2018:09:17:17 +0000] "POST /register/ HTTP/1.1" 200 3251 "https://nameless-island-79297.herokuapp.com/register/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0" 2018-03-06T09:17:21.350849+00:00 app[web.1]: - 10.33.225.156 - - [06/Mar/2018:09:17:21 +0000] "GET / HTTP/1.1" 200 11952 "https://nameless-island-79297.herokuapp.com/register/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0" 2018-03-06T09:17:21.351205+00:00 heroku[router]: - at=info method=GET … -
Able to add the same user multiple times to the another model
I have a model which adds(assigns) users to the academy (academy user), the issue is I am able to add the same user multiple times to the academy. What am I doing wrong here? class AcademyPlayer(models.Model): academy = models.ForeignKey(Academy, on_delete=models.CASCADE) player = models.ForeignKey('player.Player', on_delete=models.CASCADE) date_joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.player.user.name -
Form not showing in Django app
I picked up a very very simple django challenge, but am having a problem with inputing details and submitting it into Database. My forms are not even showing talkless of inputing details, and I don’t know what am doing wrong. models.py class Users(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=60, unique=True) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) views.py from django.shortcuts import render from django.http import HttpRequest from django.template import RequestContext from datetime import datetime from django.http import HttpResponseRedirect from .models import Users from .forms import UserForm def home(request): return render(request, 'pages/home.html', {}) def list(request): users = Users.objects.order_by('created_at').all() context = {'users': users} return render(request, 'pages/list.html', context) def add(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user = User(name=request.POST['name'], email=request.POST['email']) user.save() return HttpResponseRedirect('/list/') return render(request, 'pages/list.html', {'form': form}) forms.py from django import forms from django.core.validators import validate_email from .models import Users class UserForm(forms.Form): name = forms.CharField(label='Name', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(label='Email', max_length=60, widget=forms.TextInput(attrs={'class': 'form-control'})) def clean_email(self): email = self.cleaned_data['email'] if Users.objects.filter(email=email).exists(): raise forms.ValidationError('Email already exists') return email add.html (Template): {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>Add user</h1> {{ form.non_field_errors }} <form name='form' method="POST" action="/add/"> {% csrf_token %} {% for field in … -
Generate symfony 2.4 password from Python/Django
I'm working on a project where i have to insert user into a database from a Python/django application. Those users authenticate themselves in a symfony 2.4 application so i have to generate a password that will be decrypted properly. The symfony project use the sha256 algorythm (as i can see in the security.yml file) Do you have some informations about the way symfony 2 encode the password with this algorythm ? (I know i have to build a salt and a hash) Thanks -
Postgres,Django:How to approve every insert into postgres table?
I'm working on a django application with postgres. I have a html form which takes user inserted data. As of now the data entered in the form is directly getting inserted into postgres table.But I want to add a step in between where the DBA should check the data from the form and then approve it for insertion. How can I do it ? Thanks in advance. -
Have to print the result one by one in django template
I have a json response like {'resultset': [['Education', 324.0], ['Other', 61.17], ['Services', 175.17], ['Fees', 5454.8], ['Expenses', 181.0]], 'resultset1': [['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5'], ['09', '2016', '6196.14']], 'resultset2': [['11', '2015', '5418.0'], ['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5']]} {'resultset': [['Education', 324.0], ['Other', 61.17], ['Services', 175.17], ['Fees', 5454.8], ['Expenses', 181.0]], 'resultset1': [['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5'], ['09', '2016', '6196.14']], 'resultset2': [['11', '2015', '5418.0'], ['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5']]} {'resultset': [['Education', 324.0], ['Other', 61.17], ['Services', 175.17], ['Fees', 5454.8], ['Expenses', 181.0]], 'resultset1': [['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5'], ['09', '2016', '6196.14']], 'resultset2': [['11', '2015', '5418.0'], ['12', '2015', '240.0'], ['01', '2016', '6107.6'], ['02', '2016', '5066.2'], ['05', '2016', '180.0'], ['08', '2016', '178.5']]} I want to access this response one by one in django template -
if condition tag is not working properly
In demo.html <table class="table table-hover" style="width:80%;"> <tr> <th>Test Case</th> <th>File Name</th> <th>Coverage </th> </tr> {% for key, value in d.items %} <tr> <th>{{ key }} </th> </tr> {% for k,v in value.items%} {% if forloop.counter <= count1 %} <tr> <td> </td> <td>{{ k }}</td> <td>{{ v }}</td> </tr> {% endif %} {% endfor %} {% endfor %} </table> if condition works only when i declare as {% if forloop.counter <= 2 %} Instead if i use variable as above mentioned code it does not work.Please to help me out what is the error in above code. As if use {{ count1 }} the value is printing correctly. -
How do I pass user_id into a Django method
I need to pass user_id (or a User object that will resolve to user_id) into a function - from both templates and other backend functions. The purpose is to first check if a token exists for the user and if not, then to appropriately call an external API to generate a token. My question is, how do I pass the user_id into the method? Django doesn't appear to have a clear user_id method in the User object and using Django auth I can't set username as the ForeignKey. class Token(models.Model): user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) provider_id = models.ForeignKey(Providers, unique=False, on_delete=models.DO_NOTHING) access_token = models.TextField() refresh_token = models.TextField() r_lasttime = models.DateTimeField expires_in = models.IntegerField token_type = models.TextField() @classmethod #check if a user / provider combination exists def token_exists(cls, user_id, provider_id): return cls.objects.filter(user_id=user_id,provider_id=provider_id).exists() @classmethod def new_token(cls, provider_id, user_id, access_code): # use to acquire a new access token and update it in the database # requires the front end to have already been provided an authorisation token called access_code # determine if the user / provider combination already exist if Token.token_exists(user_id, provider_id) == True: status = {'code': 400, 'desc': 'User/provider combination already exist. Use refresh instead'} return (status) # the user / provider combination does … -
How to configure cloud public server in Django 1.11?
I am working on django 1.11 whenever i try to write an application it default takes development server as 127.0.0.1:8000 localhost. Instead of running localhost i want to run cloud server in that application. I have Microsoft Azure account also i just want to configure with my ip address which running on cloud. so can anybody help me on this. Thanks & Regards, Gunasekaran J -
Django form not saving inputs- refreshes upon submission
I am trying to create a website with two dropdown menus: Department and Course Number. The data for the dropdown menus comes from the "courses" table of my SQL database. Right now my website initializes properly and shows the correct options in the dropdown menus. However, when the user selects an option within the dropdown menus and submits their choices, the website reloads as a blank slate so their selections are not being saved or processed. The error lies somewhere in the CourseForm form because I have another form (Working_Form) that is created in a different way but works perfectly. What is wrong with CourseForm/its associated models? models.py from django.db import models class Dept(models.Model): dept = models.CharField(max_length=255, db_column = 'dept') class Meta: managed = False db_table = 'courses' def __str__(self): return self.dept class Course_num(models.Model): course_num = models.CharField(max_length=255, db_column = 'course_number') class Meta: managed = False db_table = 'courses' def __str__(self): return self.course_num forms.py from django import forms from django_select2.forms import ModelSelect2Widget from .models import Dept, Course_num class CourseForm(forms.Form): dept = forms.ModelChoiceField( queryset=Dept.objects.distinct().\ order_by('dept').exclude(dept__isnull=True), required=False, empty_label="No preference", label=u"Department") course_num = forms.ModelChoiceField( queryset=Course_num.objects.distinct().\ order_by('course_num').exclude(course_num__isnull=True), required=False, empty_label="No preference", label=u"Course Number") views.py from django.shortcuts import render from django import forms from .models import Dept, …