Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SQlite configuration
I just started learning of Django. My main "source" of knowledge about that framework is book named "Python Web Development with Django" wrote by Rudolph Snellius, Jeff Forcier and Wesley Chun. Can you explain me how to use SQlite in Django? The book is few years old thats why I have some problem with configuration of database. First step I have done correctly was create app by command ./manage.py startapp blog, then I added verse mojprojekt to tuple INSTALLED_APPS in setting.py file. Then I have to add verses DATABASE_ENGINE = 'sqlite3' and DATABASE_NAME = 'path to my project' to settings.py. The last step is run command ./manage.py syncdb. After all I am getting error : konrad@konrad-MS-7823:~/Documents/Django/mojprojekt$ ./manage.py syncdb Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/lib/python2.7/dist-packages/django/apps/config.py", line 119, in create import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named blog konrad@konrad-MS-7823:~/Documents/Django/mojprojekt$ Could u help me if u where I make mistake? -
How to pass values for password_reset() in Django 1.10?
I would like to pass the url value post_reset_redirect to Django. I have an url.py with appname = polls, so I want to pass it to avoid No reverse match error url(r'^password_reset/$', auth_views.password_reset(post_reset_redirect='polls:password_reset_done'), name='password_reset'), But I have the error: TypeError: _wrapped_view() takes at least 1 argument (0 given) How to pass values for password_reset() in Django 1.10? -
Django Filermedia and Calendarium giving template errors
Hello Stackoverflow community, I've been developing this python web application and I ran across this error 'filermedia' is not a valid tag library: Template library filermedia not found, tried django.templatetags.filermedia,bootstrapform.templatetags.filermedia,django_admin_bootstrapped.templatetags.filermedia,django.contrib.admin.templatetags.filermedia,django.contrib.staticfiles.templatetags.filermedia,easy_thumbnails.templatetags.filermedia,filer.templatetags.filermedia,mptt.templatetags.filermedia,calendarium.templatetags.filermedia In my settings.py file I have INSTALLED_APPS = ( 'bootstrapform', 'django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jobs', 's3direct', 'easy_thumbnails', 'filer', 'mptt', 'nested_inline', 'calendarium', ) for installed apps, its necessary that I have the filer application for my calendarium so I can load up my calendar however, when I add an image it will crash and give the error above. it will also crash when I click Folders under the Filer category below, strangely the show thumbnail options still works though. I can generate events in the calendarium that people can see, however it can only be used without images, the problem lies within the 'filer' but i cant remove it because my calendar only works with it in my settings.py, Im at my wits end, I dont know how to get django-filermedia my system says I have it installed and I dont know how to set my calendarium to use AWS to upload and store images -
Django two foreign keys on one model
I am desperately looking for a solution on a problem I won't find no answer to. My problem is matching columns via foreign key on another table: Code snippet from models.py: class components(models.Model) power = models.ForeignKey('SIPrefixxes', related_name='powers', default=1, on_delete=models.CASCADE) sign = models.ForeignKey('SIPrefixxes', related_name='signs', default=1, on_delete=models.CASCADE) class SIPrefixxes(models.Model): #Symbol sign = models.CharField(max_length=8, blank=True) #Potzenz power = models.IntegerField(blank=True, unique=True) #Name name = models.CharField(max_length=16, blank=True) def __str__(self): return self.name ´The SIPrefixxes Table is filled with several entries. What i am looking forward to do is getting those entries in my components posibilities. By now my only possibility in the django admin panel is the "name" entries. I am working with Django 1.10! Thanks in advance! -
How can I calculate a date in a Django model?
I spent most of the day yesterday trying to find an answer, but couldn't figure out how to add the decorator to the model. Goal: Calculate a date, based on the user entering the number of days. Use Case: User enters the "start date", and the number of days in a form. For example, the user enters a start date of 1/1/2017, and days = 5. The calc date should be 1/6/2017. I could not get the calculated field to pull through on my template. Code snippets below. #models.py from datetime import datetime, timedelta from django.db import models from django_extensions.db.models import TimeStampedModel from django.urls import reverse class Lease(TimeStampedModel): location_name = models.CharField(max_length=120) contingency_start_date = models.DateField(null=True, blank=True) contingency_period_in_days = models.IntegerField(default=0) ... def __str__(self): return self.location_name @property def get_contingency_end_date(self): return datetime.date(self.contingency_start_date) + timedelta(days=self.contingency_period_in_days) views.py class LeaseDetailView(generic.DetailView): model = Lease def get_context_data(self, **kwargs): context = super(LeaseDetailView, self).get_context_data(**kwargs) context['options_list'] = Option.objects.all() return context detail.html <li><strong>contingency start date:</strong> {{ lease.contingency_start_date }}</li> <li><strong>contingency_period_in_days </strong> {{ lease.contingency_period_in_days }}</li> #not working <li><strong>Contingency end date: </strong> {{ lease.get_contingency_end_date }}</li> -
form.is_valid() returns false
I have this piece of code from my view. I can't figure out why the is_valid() returns false and hence no httpresponse is returned. class PostTweet(View): """Tweet Post form available on page /user/ URL""" def post(self, request, username): if request.method == 'POST': form = TweetForm(request.POST) if form.is_valid(): user = User.objects.get(username=username) tweet = Tweet(text=form.cleaned_data['text'], user=user,country=form.cleaned_data['country']) tweet.save() words = form.cleaned_data['text'].split(" ") for word in words: if word[0] == "#": hashtag = HashTag.objects.get_or_create(name=word[1:]) hashtag.tweet.add(tweet) return HttpResponseRedirect('/user/'+user) -
Manually selecting a database for a QuerySet overrides database router methods in Django?
I'm using django 1.8, I want to define two databases, but I want to use one of them very rarely. So I defined two databases and a default router like this: DATABASES = { 'default': { 'ENGINE': '...', ... }, 'secondary': { 'ENGINE': '...', ... } } DATABASE_ROUTERS = ['DefaultRouter'] and then defined DefaultRouter like this so migrate wouldn't have any effects on it: DEFAULT = 'default' class DefaultRouter(object): def db_for_read(self, model, **hints): """Reads go to 'default' """ return DEFAULT def db_for_write(self, model, **hints): """Writes always go to 'default' """ return DEFAULT def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the 'default' pool. """ if obj1._state.db == DEFAULT and obj2._state.db == DEFAULT: return True return False def allow_migrate(self, db, app_label, model_name=None, **hints): if db == DEFAULT: return True else: return False Assume that I have a Model called Book which exists on both databases with different instances. I want to do a query on Book from my secondary database like this: books = Book.objects.using('secondary').filter(author="john") I have two questions now: 1- Does this query hits secondary database having that method in the Router to route all read/writes to the default? and more generally: … -
Django app does not load css files when run with supervsior
I am running a simple hello world django app using supervisor. I was looking at this package in GitHub - https://github.com/rfk/django-supervisor for reference as well. The app runs all okay, but when I load the index.html page, I see none of my CSS files being loaded and I just see plain-text. Do I need to add the css files as a specific program directory/file in the supervisord config? -
django- how can i save data in redis with django with custom key?
i want to delete some specific data after model.save() fired. i use "post_save()" signal. when I use cache_page() decorator in my views.py, data will save in redis with keys like this: "views.decorators.cache.cache_page..GET.8ce4de6051c3ba05396ff670741d3172.d41d8cd98f00b204e9800998ecf8427e.fa-ir.IRST'. I want to save data with custom key that i specify. how can i do it? or how can i delete stored data that are related to specific view ? @cache_page(60*15) def view_a(request): ... @cache_page(60*10) def view_b(request): ... how can i get data that are saved for view_a function? -
Django Rest Framework Login Token Authentication
I am making a appliation using the API framework. How to do token authetication for that? In which .py files I have to add code snippets and where? -
How to show spinner while typing in input field
I want to start spinner while typing. When I stop doing it, then it should match the username, if username exists, show tick icon otherwise show cross icon and also minimum letter should be 4 . I tried it with using two icons, tick & cross. I kept the minimum letter condition as 4 and it worked fine, when I remove the characters those tick or cross should disappear, but it does not. How to add spinner and also how to avoid this problem? HTML: <div class="input-group"> <input class="form-control" id="id_username" name="username" placeholder="Username" type="text" required /> <div class="input-group-addon" id="lola" style="display:none"></div> </div> JS: console.log($("#id_username")); $("#id_username").keyup(function () { $("#lola").show(); if(this.value.length<4) { return } var username = $(this).val(); console.log(username); $.ajax({ url: '/ajax/validate_username/', type: "POST", data: { 'username': username, csrfmiddlewaretoken: '{{ csrf_token }}', }, dataType: 'json', success: function (data) { console.log(data); if (data.is_taken) { $("#lola").html('<i class="glyphicon glyphicon-remove" aria-hidden="true"></i>'); $("#lola").css("background-color","red"); } else{ $("#lola").html('<i class="glyphicon glyphicon-ok" aria-hidden="true"></i>'); } } }); }); -
Can we use Django Hasher outside of Django project?
I am writing a python script that converts plain text to pbkdf2 encryption format. I am using Django Hasher to convert plain text to pbkdf2. Can I use Django Hasher outside in regular python script without creating Django project ? -
django endless-page replicates content that should not be replicated upon scroll
here's another tough one. I'm trying to implement twitter-style endless page in django 1.10. It works but content is being duplicated whenever I scroll to the bottom of the page. My view: class EntryListView(AjaxListView): context_object_name = 'entry_list' template_name = 'archlog.html' page_template = 'archlog_entries.html' def get(self, request, *args, **kwargs): if request.is_ajax(): self.template_name = self.page_template return super(EntryListView, self).get(request, *args, **kwargs) def get_queryset(self): return MyModel.objects.all() My main template: <b style="color:red">hello world!</b> <div class="endless_page_template"> {% include page_template %} {% block js %} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{{ STATIC_URL }}el-pagination/js/el-pagination.js"></script> <script type="text/javascript">$.endlessPaginate({paginateOnScroll: true});</script> {% endblock %} </div> My ajax template: {% load el_pagination_tags %} <div id="container"> {% paginate 100 log_entries %} {% for entry in log_entries %} <p style="line-height:8px;">key of job = {{entry.job_key}}</p> {% endfor %} {% show_more %} </div> The code works bug the content 'hello world!' gets repeated every time I scroll to the bottom of the page; it appears before the new payload of data. What am I doing wrong? -
Django BinaryField - Justification for statement in documentation
In the Django 1.10 documentation for the BinaryField field type, they give a warning about its use: Abusing BinaryField Although you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling. It does not continue with any justification for this claim. Are there any generalized indicators for what falls in the 99% "bad design" or 1% "not bad design" cases? Does this ring particularly true with Django because it has great static files support? -
Django manage.py --no-input . Yes or no?
I can't find this in the docs. When I run python manage.py collecstatic --no-input does it mean it will answer "yes" to any prompt that would pop up in the process? The same for python manage.py migrate --no-input. -
django channels: how to sync data
I am creating an application for sharing music on django + channels. There is one problem I can not solve. Each audio, added one of the participants to the playlist, should be played at the same time at all users, with the same timing, including those who visit during playback. The only solution that occurred to me - it's send request to admin of the room through a WebSocket at the entrance, get the timing from it and change timing. However, this option will result to playback delay, and therefore to the de-synchronization. Besides it for quite ugly to implement. Perhaps there is some simpler /more correct way to do what I need? -
Django tabular inline with translations (parler) missing 2 required positional arguments: model and admin_site
I'm having a main object that contain a dynamic numbers of images and descriptions. Thus, I'm using the Foreign Key / tabularinline combo! class InstructionsModel(TranslatableModel): instruction = models.ForeignKey(InstructionModel, related_name='instructions_plural_project') mainImage = FilerImageField(verbose_name=('Marker image'), blank=True, null=True, on_delete=models.SET_NULL) translations = TranslatedFields( title=models.CharField(_('Instruction title'), max_length=255), introduction=RichTextField(_('Instruction introduction or subtitle'), default='', blank=True), description=RichTextField(_('Instruction description'), default='', blank=True), ) _metadata = { 'title': 'get_title', } def get_title(self): title = self.safe_translation_getter('meta_title', any_language=True) if not title: title = self.safe_translation_getter('title', any_language=True) return title def __str__(self): title = self.safe_translation_getter('title', any_language=True) return title if title is not None else '(not translated)' def save(self, *args, **kwargs): super(InstructionsModel, self).save(*args, **kwargs) main_lang = self.get_current_language() for lang in self.get_available_languages(): self.set_current_language(lang) self.set_current_language(main_lang) self.save_translations() But the problem is that each of those descriptions has to be translatable. thus the admin looks like this: class InstructionsAdminInline(admin.TabularInline, TranslatableAdmin): model = InstructionsModel extra = 3 form = InstructionsMultiAdminForm list_display = [ '__str__', ] fieldsets = [ ('test', { 'fields': [('title', 'introduction'), 'description', 'mainImage'] }), ] with a very simple form (to show you that I'm running out of ideas on it): class InstructionsMultiAdminForm(TranslatableModelForm): class Meta(TranslatableModelForm): model = InstructionsModel exclude = () def __init__(self, *args, **kwargs): super(InstructionsMultiAdminForm, self).__init__(*args, **kwargs) But this error persist: File "/Users/JayCee/education-proj/homeroom/homeroom/django_instructions/admin.py", line 49, in <module> admin.site.register(InstructionModel, InstructionAdmin) … -
Javascript and django, "there is no locally stored liblary for the HTTP"
https://zapodaj.net/795d15df3c5af.png.html How can I solve it, I was searching in google, without result? -
the structure `request:`
I've seen the line : {% url "requests:applications" as applications_index_url %} I'm familiar with this structure, but not with requests:. Could anyone be able to explain to me what it means? -
How to set a custom field in a Django session model?
I have extended the session in Django per this. In short, I have added a field named account_id to hold the user id of the user which the session belongs to. Everything works fine, except the custom field account_id I have added is not being set on login. To do so: from django.contrib import auth from MyApp.models import CustomSession def login(request): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: try: auth.login(request, user) session_key = request.session.session_key # CODE HERE if session_key is not None: return HttpResponse(json.dumps({'status': 'Success'})) else: return HttpResponse(json.dumps({'status': 'Fail'})) I have tried putting the following to CODE HERE. However, none of them worked: request.session.model.account_id = user.id session = CustomSession.objects.get(pk=session_key) session.account_id = user.id session.modified = True request.session.account_id = user.id request.session[account_id] = user.id In each of these attempts, account_id is NULL in the data base. What am I missing here? -
MPTT Menu for Category and Products with Saleor E-Commerce
I am using Saleor E-Commerce for one of my sites and I cannot figure out the MPTT menu system. I have categories with products and I want to show a dropdown list in my sidebar of primary categories that expand to show the sub-categories that link to the page that shows a list of all the products assigned. So far the dropdown works fine of the primary categories but it is listing all the sub-categories beneath each dropdown; not just the sub-categories that are children of the primary. I hope this makes sense. Below is my sidebar menu code; hopefully someone with experience with Saleor and MPTT can lend a hand. Thank you. <div id="category-sidebar"> <div id="ss_menu"> {% recursetree categories %} <div class="ss_button">{{ node }}</div> <div class="ss_content"> {% if not node.is_leaf_node %} <ul> {% recursetree categories.get_descendants %} <li><a href="{{ node.get_absolute_url }}">{{ node }}</a></li> {% endrecursetree %} </ul> {% endif %} </div> {% endrecursetree %} </div> </div> -
Django: refresh table on the same page after search with new data
I am now writing a page in which I can perform searching in a django_table2's table in a Django (1.10) environment. I successfully use POST and JSON to bring the search criteria back to view for filtering. However, I seem unable to send the new filtered table to the same page for updating the table. Could anyone advise what to do so that I can refresh the django_table2's table on the same html (or same template) with the newly filtered table? Codes of the views.py are as below for reference. Many thanks. def admin_manageNews(request): queryset_ntag = db_tag.objects.filter(tag_type='NEWS') queryset_stag = db_tag.objects.filter(tag_type='SCHS') queryset = db_WiseNews.objects.all() table = wiseSimpleTable(queryset) RequestConfig(request).configure(table) frm_schtag = frm_SchTag if request.method == 'POST': #process if posting a searching if in_type == "search": if request.POST.get('s_stag'): s_stag = request.POST.get('s_stag') s_stag = json.loads(s_stag) else: s_stag = '' queryset = db_WiseNews.objects.filter(S_tag__contains = s_stag) table = wiseSimpleTable(queryset) #new table with the search results RequestConfig(request).configure(table) return render (request, 'admin_newsmanage.html', {'table' : table, 'form' : frm_schtag, 'tag_table' : queryset_ntag, 'sch_table' : queryset_stag}) else: #load the html as initialization return render(request, 'admin_newsmanage.html', {'table' : table, 'form' : frm_schtag, 'tag_table' : queryset_ntag, 'sch_table' : queryset_stag}) -
Django query: use F in range lookup
I have BigIntegerField "a" and DecimalField "b" in my app model and try to filter queryset. The following queries work fine ("Q" is used because queryset is filtered dynamically by several methods): qs.filter(Q(a__lte=F("b") + 1)) qs.filter(Q(a__gte=F("b"))) while the following raises "conversion from F to Decimal is not supported": qs.filter(Q(a__range=(F("b"), F("b") + 1))) Why it happens? How can I fix it? Thanks :) -
Do force-download responses need to be handled by angular to work?
Before adding AngularJS to my front-end I was able to download zip files from my Django server easily: downloadableZip = open('myZip.zip','r') response = HttpResponse(downloadableZip, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="myZip.zip"' return response Now Angular is the one making a call to this view, to request the download, and the file is no longer being downloaded by the browser. Does my angular $http.post() call need to handle the response sent from the view? Will this not work simply with: $http.post("myZipDownloadingView"); -
Django implementing rate for post
Currently I have these model: class Post(models.Model): user = models.ForeignKey('auth.User') post_title = models.CharField(max_length=300) post_content = models.TextField(null=True, blank=True) . . . def __str__(self): return self.post_title class Vote(models.Model): user = models.ForeignKey('auth.User') post = models.ForeignKey('Post') vote_type = models.SmallIntegerField() date_voted = models.DateTimeField( default=timezone.now) def __str__(self): return self.user I use this query to find all the posts: def index(request): posts = Post.objects.filter(created_date__lte=timezone.now()).order_by('-created_date') return render(request, 'homepage/index.html', {'posts': posts}) But this only returns the posts. I also want the Votes related to each post. Is there some way to join these two models with query?