Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - CheckboxSelectMultiple shows object representation instead of object's name
So I am trying to have a list of checkboxes of cities, but instead of showing the cities' name, it shows this: How to make it shows the name instead of City object? -
Django: Database Model For Prize Structure
I'm trying to figure out the proper way to go about structuring a model for a contest's payout/prize structure, an example is below 1st: $50000 2nd: $10000 3rd-10th: $1000 10th-70th: $500 70th-150th: $25 150th-400th: $1 My first thought was to design it like this: class Prize(models.Model): place=models.IntegerField() prize=models.IntegerField() The issue for me is that once you get to the lower tier, you begin having multiple entries that are repetitive. So from 150th-400th I would have 250 of the same entries. I'm wondering if there is a smarter way to go about this. Thanks. -
When we submit a form, what happened?
Actually, I just want to get a very simple web application: a form in a webpage that I can upload a file within some parameters; submit the form when I choose a proper file; do some calculation using these parameters in uploaded file; redirect to a new webpage with the calculation result; display the result in this new webpage. I use Django 1.10, html. index.html with <form> like this: <form action="/index/result/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="> <div class="field"> <label for="id_file">Input File:</label> {{ form.file }} <!--from django model--> </div> <p><input type="submit" value="Submit"/></p> </form> result.html for display result like this: <div id="out"> <table id="result_display" border="1px" hidden> <thead> <tr> <th>No.</th> <th>Name</th> </tr> </thead> <tbody> <tr> <th>1</th> <!--here will display the value comes from result--> <th id="r_name"> {{ result }} </th> </tr> </tbody> </table> </div> my views.py like this: from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt from forms import UploadFileForm # Create your views here. @csrf_exempt def index_view(request): para = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data if cd['file']: para = cd.get('file').read().split('\r\n') else: return HttpResponse('Please Input a File!') else: return HttpResponse('Form is invalid!') if para: # do some calculation … -
Django: accessing variable value from TemplateView
Say I have the following url that maps to a TemplateView: url(r'^path/(?P<var1>\d+)/(?P<var2>\d+)/$', TemplateView.as_view('a_view.html')) I thought in the template view a_view.html I could access the values of var1 and var2 as they're being captured and extracted into named parameters: <!-- a_view.html --> <p>var1 value = {{ var1 }}</p> <p>var2 value = {{ var2 }}</p> However, these values are blank when visiting /path/10/89. Why? How can I access them then? Would I need an explicit view? -
several forms on the same page with django
i have a very simple model... something like this: class MachineTransTable(models.Model): ... file = models.ForeignKey('File', related_name='the_file') source = models.TextField() target = models.TextField() ... What I'd like to do is to have a page where the user has the source on the left (disable), the target on the right (editable) and a submit button to post the edited target text for EACH selected object in the MachineTransTable table. Here are some more information to better understand my request: A page refers to a single file and there are several (sometimes hundreds) of objects in the MachineTransTable table belonging to the same file Each time the user edit a single target and hit the submit button for that object, the object is saved/updated (depending on the initial value of the object) in the DB and the the user can continue to edit all the other objects... At the end of the page there is another submit button which is used to exit from the page at the end of the work (all the objects have been edited/updated). If an object has not been edited/updated, it keeps its original value. I tried to use a formset but I guess it's not the right … -
Django: AJAX and path params
I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django. Say we have an url with a path param that maps to a particular view: url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html')) And then the post.html includes a script that performs an AJAX request to fetch the post as JSON: post.html <script src="{{ STATIC_URL }}/js/post.js"></script> <div id="post-container"></div> This could be the js file. Let's say we do it this way because the post (as JSON) needs to be used in a js plugin to display it in a particular fancy manner. post.js $.ajax({ url: '/post/??post_id??', contentType: 'application/json' }) .done(function(post_data) { togglePlugin(post_data); }); My main concern is how to figure out what post_id is from the js file in order to make the appropriate call. How are these parts usually connected in Django? The parts I am talking about are urls, path params, views and ajax. -
NameError: global name 'UserProfile' is not defined
# getting error while i am running my register user code enter image description here from django.shortcuts import render from .forms import * from django.core.context_processors import csrf from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.template import RequestContext import hashlib, datetime, random from django.contrib import auth from django.core.mail import send_mail from django.contrib.auth import authenticate, login # Create your views here. def index(request): return render(request,'app/index.html') def register_user(request): args = {} args.update(csrf(request)) if request.method == 'POST': form = RegistrationForm(request.POST) args['form'] = form if form.is_valid(): form.save() # save user to database if form is valid username = form.cleaned_data['username'] email = form.cleaned_data['email'] salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt+email).hexdigest() key_expires = datetime.datetime.today() + datetime.timedelta(2) #Get user by username user=User.objects.get(username=username) # Create and save user profile new_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires) new_profile.save() # Send email with activation key email_subject = 'Account confirmation' email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \ 48hours http://127.0.0.1:8000/confirm/%s" % (username, activation_key) send_mail(email_subject, email_body, 'myemail@example.com', [email], fail_silently=False) return render(request,'app/success',{}) else: args['form'] = RegistrationForm() return render_to_response('app/register.html', args, context_instance=RequestContext(request)) -
Any Javascript UI library for Django?
I want to know if there is anything similar to jQuery EasyUI which can be more easily integrated with Django. Basically, I want to do CRUD & search operations on Django models. For e.g - Basic CRUD Application. The look and feel of those plugins should be better. Also, as I don't know Javascript, I am having a hard time integrating Javascript functions with that of Django. For instance, how to provide Django model instances to the data grid of the above application ( How to connect functions between them?). Please provide some steps/tutorials as to how can I achieve that. Can Angularjs + Django REST framework be more helpful. If that's so then also provide some good tutorials for that. Any other suggestions/alternatives are welcome. Thanks in advance -
Where is the Folder for shared library in a django project
I am working on a python/django project which calls a C++ shared library. I am using boost_python C++ library. It works fine: I can call C++ methods from python interpreter. I can also call this methods from my django project. But i am wondering something: Where is the best folder for my C++ shared library ? I actually put this binary shared library in django app folder (same folder as view.py). It works but i think this is ugly... Is there a specific folder for shared library in django directory structure ? Thanks -
Comprehensive Theming Failed - AttributeError: Namespace '__anon_0x7f3dc61e5950' has no member 'stanford_theme_enabled'
I am new to OpenEdx and I have setup my system using the Bitnami stack. But I cant seem to be able to setup custom comprehensive theming. LMS throws Internal Server Error. I have below my tailed server log Here's what I have done so far. Downloaded theme from - https://themex.io/ Set COMPREHENSIVE_THEME_DIR = "/path-to-theme" Ran SERVICE_VARIANT=lms ./bin/paver.edxapp update_assets lms --settings=aws and this finished successfully Launch LMS, 500 Internal Server Error What am I doing wrong? [Mon Sep 12 05:10:14.551555 2016] [:error] [pid 31981] [remote 127.0.0.1:512] runtime._include_file(context, (static.get_themed_template_path(relative_path='theme-header.html', default_path='navigation.html')), _template_uri) [Mon Sep 12 05:10:14.551570 2016] [:error] [pid 31981] [remote 127.0.0.1:512] File "/home/harrypalace/manjaro_vlp/apps/edx/edx-platform/venv/lib/python2.7/site-packages/mako/runtime.py", line 752, in _include_file [Mon Sep 12 05:10:14.551592 2016] [:error] [pid 31981] [remote 127.0.0.1:512] callable_(ctx, **_kwargs_for_include(callable_, context._data, **kwargs)) [Mon Sep 12 05:10:14.551607 2016] [:error] [pid 31981] [remote 127.0.0.1:512] File "/home/harrypalace/manjaro_vlp/.tmp/mako_lms/a2ab4a911ea1f0731584a3dbc36a191f/navigation.html.py", line 48, in render_body [Mon Sep 12 05:10:14.551630 2016] [:error] [pid 31981] [remote 127.0.0.1:512] _mako_get_namespace(context, '__anon_0x7f3dc61e5950')._populate(_import_ns, [u'login_query', u'stanford_theme_enabled']) [Mon Sep 12 05:10:14.551645 2016] [:error] [pid 31981] [remote 127.0.0.1:512] File "/home/harrypalace/manjaro_vlp/apps/edx/edx-platform/venv/lib/python2.7/site-packages/mako/runtime.py", line 525, in _populate [Mon Sep 12 05:10:14.551667 2016] [:error] [pid 31981] [remote 127.0.0.1:512] d[ident] = getattr(self, ident) [Mon Sep 12 05:10:14.551688 2016] [:error] [pid 31981] [remote 127.0.0.1:512] File "/home/harrypalace/manjaro_vlp/apps/edx/edx-platform/venv/lib/python2.7/site-packages/mako/runtime.py", line 625, in __getattr__ [Mon Sep 12 05:10:14.551711 … -
django + angular - serve static angular html with ManifestStaticFilesStorage
Having a project with django and angular, I only use django to serve angular files statically (and as a REST backend). The only view I use passes the js static file locations, i.e.: class AppView(LoginRequiredMixin, TemplateView): template_name = "myapp/app.html" def get_context_data(self, **kwargs): context = {} context['jsdir'] = "myapp/js" jsfiles = ["app.js", "services.js", "controller.js", "directives.js"] context['jsfiles'] = ["{}/{}".format(context['jsdir'], x) for x in jsfiles] return context And in the Template I access them as: ... {% for jsfile in jsfiles %} <script type="text/javascript" src="{% static jsfile %}"></script> {% endfor %} ... Using the STATIC_FILES_STORAGE = ManifestStaticFilesStorage then serves the right js files (so users don't need to empty the cache when I roll out a new version). Inside the django app I have html templates and I do not have the static tag there. Therefore, every time the html templates (for directives) get updated, the cached version is delivered. Question: How can I serve the static angular html files without disabling the cache (in nginx) and without bothering users clearing the cache on each change? -
How to write Django projects in Spyder (Python 3.4)?
I am currently using Spyder platform to run Python scripts. How to use Django framework for python on spyder ? -
Reverse Relationships in Django-Rest framework
I have two models . Now the Class Track Model has an Album foreignkey. I want to write a Track Serializer that has Album Name. How can i achieve that? class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ('album', 'order') ordering = ['order'] def __unicode__(self): return '%d: %s' % (self.order, self.title) I set depth parameter of Track to 1 but that retrieves album name as well as artist.I just want the album name in the Track Serializer -
HStoreField accepting null values
I am building a django project using the REST framework. Data is sent through from the front end as a JSON object. I allow for null values to be accepted, and in order to facilitate this I set blank=True, null=True in the relevant places in models.py. However, I have also used the HStoreField in order to allow arbitrary data to be stored. Now, if the value of an item inside the HStoreField is null, I get an error that: {"arbitrary_data":["This field may not be null."]} Is there a solution to this? From my research it looks like HStoreField has to follow a python dict structure, where the key and value are both strings. So perhaps this is the reason why I cannot set the value to null. Doing something like this: class Employee(models.Model): arbitrary_data = HStoreField(null=True, blank=True) does not help because all it allows is for the whole HStoreField to be null. -
Date + Time picker not working on new instance + giving me an error telling me to input correct date
So i have built a calendar using the Calendarium package. My add Event form and Update form are the same form but uses instances. When i create a event, everything works fine, the date picker, time picker and it does not give me an error when i click save. but! if i try to update that event none of the date pickers and time pickers work and if the date is in dd-mm-yyyy format i get an error but its being printed out to user in the format so why is it giving me an error? I have checked if the id's change on the input elements but they do not. Iv made sure 100% i'm using the correct forms. I don't really get what i should be doing to solve this problem, any advice would be much appreciated If you need me to show you any code or anything like that don't hesitate to ask please. -
Python login feature and push notification
I need to create an admin login(admin for the website) and after admin login we need to send some push notification to the apps developed in ionic framework. I am bit confused from where i should start. I got a tutorial like https://thinkster.io/django-angularjs-tutorial#learning-django-and-angularjs which says how can i create users. Python provide me different option for login when i check but i am not sure which is the best method and which should i follow. Please help me on this. THe database connection we need is a pstgresql and the web script should be written in angularjs. -
trouble finding the right django queryset for this
I have two models like this: class Foo(): name = CharField frequency = IntegerField class Bar(): thing = ForeignKey(Foo) content = TextField I want to get a queryset that will be Bar objects sorted by a range of Foo objects. It obviously doesn't work, but it illustrates what I need. Foo.objects.order_by('-frequency')[0:10].bar_set.all() -
How to update jsonView of an element?
I have Json objects which I want to pretty print using jsonView. But everytime I try to update the same element with new Json object it remembers the old objects as well and pretty prints the all the old ones as well as the new one. I am using the following command to pretty print. function commandPopup(){ $('.commandPopup').click(function() { $(".modal-title").html($(this).attr('box')+":"+$(this).attr('task')); $('#commandPopup').on('show', function () { $("#commandPopup").modal('show'); $.getJSON('get_taskinfo', { 'box' : $(this).attr('box'), 'task' : $(this).attr('task') }).done(function(data) { console.log(data); var config=data.config; **$("#config").jsonView(config);** }); }); } -
Your models have changes that are not yet reflected in a migration
In django1.9, tables have been in database already, i create init migration files python manage.py makemigrations my_app then, i run migrate: python manage.py migrate my_app It shows: psycopg2.ProgrammingError: relation "p_record_segment" already exists I want to fake it, first, i clean the django_migrations, then excute: python manage.py migrate my_app --fake 0001_initial It shows: Running migrations: Rendering model states... DONE Applying my_app.0001_initial... FAKED I think this will be fine, but when i run migrate again: Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I saw the history in django_migrations, and no changes in fact, but why django show me this. -
django how to show images from my user directory(
I am using linux and created a Django project. I have folder in my home directory /home/simha/siteimages In views.py def gallery(request): path="/home/simha/=siteimages" # insert the path to your directory img_list =os.listdir(path) return render(request,'blog/gallery.html', {'images': img_list}) gallery.html is <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for image in images %} <img src='/static/{{image}}' /> {% endfor %} </body> </html> Its not working. -
Top 7 most common tags Taggit
def most_common(self): return self.get_queryset().annotate( num_times=models.Count(self.through.tag_relname()) ).order_by('-num_times') How would I edit this to only view the top 7 tags. This is a function from taggit and I would only like to see only 7. thanks. -
ValueError: plural forms expression could be dangerous
I'm translating a third party package in this mommento but i get the next error: Environment: Request Method: GET Request URL: http://localhost:8080/ Django Version: 1.10.1 Python Version: 3.5.2 Traceback: File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/utils/deprecation.py" in __call__ 131. response = self.process_request(request) File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/middleware/locale.py" in process_request 29. translation.activate(language) File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/utils/translation/__init__.py" in activate 161. return _trans.activate(language) File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/utils/translation/trans_real.py" in activate 238. _active.value = translation(language) File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/utils/translation/trans_real.py" in translation 227. _translations[language] = DjangoTranslation(language) File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/utils/translation/trans_real.py" in __init__ 129. self._add_installed_apps_translations() File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/utils/translation/trans_real.py" in _add_installed_apps_translations 176. translation = self._new_gnu_trans(localedir) File "/home/salahaddin/Proyectos/uzman/lib/python3.5/site-packages/django/utils/translation/trans_real.py" in _new_gnu_trans 156. fallback=use_null_fallback) File "/usr/lib64/python3.5/gettext.py" in translation 426. t = _translations.setdefault(key, class_(fp)) File "/usr/lib64/python3.5/gettext.py" in __init__ 162. self._parse(fp) File "/usr/lib64/python3.5/gettext.py" in _parse 297. self.plural = c2py(plural) File "/usr/lib64/python3.5/gettext.py" in c2py 76. raise ValueError('plural forms expression could be dangerous') Exception Type: ValueError at / Exception Value: plural forms expression could be dangerous So, investiganting i found a answer and i search in the .po file, i found the line: #: templates/wagtail_embed_videos/chooser/results.html:6 #: templates/wagtail_embed_videos/embed_videos/results.html:6 #, python-format msgid "" "\n" " There is one match\n" " " msgid_plural "" "\n" " There are %(counter)s matches\n" " " msgstr[0] "" "\n" " Hay una coincidencia\n" " " msgstr[1] "" "\n" " Hay %(counter)s … -
flask working outside of request context
I use flask build a sit which provide function like leaderboard(kaggle).Now I have to use Ucenter(write by php)to make users can land main site and this site at the same time. In the directory of app , I create a directory called api. There are 4 document. app - inint.py - discuz.py - settings.py - views.py Here is the code of init.py: from flask import Blueprint api = Blueprint('api', __name__) from . import views setting.py is some parameter.like API_RETURN_SUCCEED=1 API_RETURN_FAILED=-1 API_RETURN_FORBIDDEN=-2 discuz.py consist some function.like: def discuzAuthcode(self,source,key,operation,expiry=0): if (not source) or (not key): return '' ckey_length=4 timestamp=self.unixTimestamp() key=self.MD5(key) keya=self.MD5(self.cutString(key,0,16)) keyb=self.MD5(self.cutString(key,16,16)) if ckey_length: if operation==Discuz.DECODE: keyc=self.cutString(source,0,ckey_length) else: keyc=self.randomString(ckey_length) cryptkey = keya + self.MD5(keya + keyc) if operation == Discuz.DECODE: try: temp = self.base64Decode(self.cutString(source, ckey_length)) except: try: temp = self.base64Decode(self.cutString(source + "=", ckey_length)) except: try: temp = self.base64Decode(self.cutString(source + "==", ckey_length)) except: return '' result = self.toString(self.RC4(temp, cryptkey)) if (self.cutString(result, 10, 16) == self.cutString(self.MD5(self.cutString(result, 26) + keyb), 0, 16)): return self.cutString(result, 26); else: return '' else: source = "0000000000" + self.cutString(self.MD5(source + keyb), 0, 16) + source; temp = self.RC4(source, cryptkey) return keyc + self.base64Encode(self.toString(temp)) views.py as follows: from flask import make_response, request from . import api from discuz import Discuz from … -
Set language preferences on view
I am working in a django project, and I have enabled the multi-language functionality. For change between languages, I added a simple get parameter to the home url and depending of the value of it, I set the language using the next code. def home(request): lang_to = request.GET.get('lang_to', '') if lang_to: translation.activate(lang_to) request.LANGUAGE_CODE = translation.get_language() return render(request, 'home.html', { 'active_home': True, }) On my settings.py MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True LANGUAGES = [ ('en', _('English')), ('es', _('Spanish')), ] And in the template, a link that redirects to home page and add the lang_to get parameter to the url. I want to use this parameter to set the selected user preference: <a href="{% if request.LANGUAGE_CODE == 'en' %}/?lang_to=es{% else %}/?lang_to=en{% endif %}">{% if request.LANGUAGE_CODE == 'en' %}Español{% else %}English{% endif %}</a> Ok, my problem is that when I try to change the default language (en) to Spanish sending the lang_to=es, My home change perfectly to Spanish, but when I click another link (without the lang_to=es parameter) the web page loads the default language again. ¿How can I set … -
AWS dumping postgres into SQL
My team has hosted a django project in AWS with a Postgres RDS instance. What is the proper way to get export the database into SQL or pg_dump?