Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django editable database table
My background is more in PHP and mySQL and offline applications. Therefore, I'm not sure what the best way to implement the following. I'm looking for the best/or a good way to add an editable table into my django app. The idea I'm looking for is similar to an Access database where the user can either add new lines to a table or update the existing fields. I found already some post on the topic. however, I'm not sure if these ideas from 5 years ago are still up to date (django dynamic formset, ...) The website is currently used by maybe 100 people at the same time in peaks with a rather low number of entries to process (1000). Also regarding the database, I'm not sure. Should I already move to postgresql or is sqllite enough. Thanks in davance -
How do I print items in a dictionary from highest value to lowest value using Django?
I want to do something like the following but do not know how to make it compatible with the HTML that I've written for my program. {% for u in sorted(dictionary, key=dictionary.get, reverse=True) %} {{ u|safe }}<br> Priority level <b>{{ dictionary[u] }}</b><br> ---<br> {% endfor %} I'm not opposed to doing it in the views.py file either. Ideally I'd like to only show the top 20 or so results as well. -
Django URLConf Not Resolving Properly
I'm following the Django introductory tutorial, and I'm running into a weird error. Or at least I think it's a weird error. I'm on part 3, which is writing more views. I have, to the best I can tell, followed the tutorial to the letter. My /polls/urls.py file looks like this: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] if __name__ == "__main__": pass And polls/views.py looks like this: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, question_id): return HttpResponse("You're looking at question {question}.".format(question=question_id)) def results(request, question_id): response = "You're looking at the results of question {question}.".format(question=question_id) return HttpResponse(response) def vote(request, question_id): return HttpResponse("You're voting on question {question}.".format(question=question_id)) if __name__ == "__main__": pass And I've registered the urls in my_project/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^polls', include("polls.urls")) ] If I go to http://127.0.0.1:8000/polls I see the "hello world" message that I expect to see, but it I try looking up one of the questions, i.e. I go to http://127.0.0.1:8000/polls/1/ I see the following error message: Using the … -
Django and Postgresql
I need a clear step by step method to hook up Django to postgresql. Any takers? As we know it comes natively with sql lite and online methods fall shy of an unbreakable solution. -
Sporadic social-auth-app-django errors with on Google & Twitter
On my website, I'm occasionally getting errors like the one below from other users, but I can't reproduce it myself. I'm using django-social-auth for for OAuth authentication with Google, Twitter, Facebook, and GitHub. They work most of the time, but every 50 users or so that try to log in, I get errors like these. This seems to be a bug in the library. But, since I can't reproduce it myself, it's hard to troubleshoot. Most problematic is that when it tries to recover from the error, new exceptions occur, so I don't think the user even gets a friendly error message asking them to try another login option. It seems that it's trying to do a reverse-url lookup on the value None. I can't quite tell from the stack trace what is calling reverse. Is there some default URL that I'm not setting in settings.py maybe? TypeError at /oauth/complete/google-oauth2/ argument of type 'NoneType' is not iterable ...snip... File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/social_core/backends/oauth.py" in validate_state 87. raise AuthMissingParameter(self, 'state') During handling of the above exception (Missing needed parameter state), another exception occurred: File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/shortcuts.py" in resolve_url 147. return reverse(to, args=args, kwargs=kwargs) File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/urls/base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/opt/virtualenv/readkorean.org/lib/python3.5/site-packages/django/urls/resolvers.py" … -
django blocktrans doesn't work
I read the answewr, but it doesn't work properly. My settings and codes are as follows: settings.py LANGUAGE_CODE = 'ko-kr' LANGUAGES = [ ('en', _('English')), ('ko', _('Korean')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) USE_I18N = True USE_L10N = True Template {% for date in date_list %} <li style="display: inline;"> <a href="{% url 'blog:post_year_archive' date|date:'Y' %}"> {% blocktrans with year=date|date:'Y' %}Year - {{ year }}{% endblocktrans %} </a> </li> {% endfor %} English django.po msgid "Year - %(year)s" msgstr "Year-%(year)s" Korean django.po msgid "Year - %(year)s" msgstr "%(year)s년" I expected the output "2017년" because of LANGUAGE_CODE = 'ko-kr', but it prints "Year-2017". Other translations are correctly printed in Korean. What's wrong with me? -
Best way to create test data for all django apps unittest
I want to setup django test data for all app unit tests, like create a user before all tests running, and then the test in each app test could use that user. -
how to make Django search hyperlink in PDF?
I want to ask some questions about Django Now I have a simple search engine built by Django Besides, I can get the search results based on the search query However, I want to add the hyperlink function. I want to the search results on the result page can be clickable and link to the original publisher. so, my question is how to make Django search the hyperlink in the PDF and display on the new web page? -
Why won't my link work whenever it's clicked?
Whenever I click Red, for example, it takes me to that error. It's saying one of my lines are messed up but I just don't see how. Here's my detail.html file (the one that's throwing the error) <img src="{{ album.album_logo }}"> <h1>{{ album.album_title }}</h1> <h3>{{ album.artist }}</h3> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.pk %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}" /> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="http://findicons.com/files/icons/1620/crystal_project/22/knewstuff.png"> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> -
Django- TypeError using URL with multiple args
I'm having trouble with the Django URL-View system. I've been trying out a view: #views.py... def IsolatedForm(request, lat, lng, slug): if not request.user.is_authenticated(): return redirect('login') chosen_form = Form.objects.filter(slug=slug) return render(request, 'polls/isolatedform.html', {'chosen_form':chosen_form, 'lng': lng, 'lat': lat}) I've associated it with a URL pattern that takes a couple of floats (coordinate values) and a slug: #urls.py... url(r'^testing/(-?\d+\.\d+),(-?\d+\.\d+)/(?P<slug>.*)/$', views.IsolatedForm, name='isolatedform'), When I try this URL pattern with, for example (with the App name being polls): polls/testing/1.0,-1.0/postchaos/ (where "postchaos" is an example slug that corresponds to an existing Form) I get: TypeError at /polls/testing/1.0,-1.0/postchaos/ IsolatedForm() takes exactly 4 arguments (2 given) I'm not being able to realize what the actual issue is, as the URL I've tried contains the expected numbers and the expected slug. Any help would be appreciated. -
How to use iframe in Django for Production?
I have been using WordPress since 2005 now in the process of switching all my websites to Django Projects. This is my first Django Project which will have multiple web apps. I am using Visual Studio Preview 2017 to create my Django Project. In my project I setup a main web app that holds the projects urls.py, view.py, model.py and templates folder that holds the main html pages. This main web app will connect to the other web apps within the project. I know the objective of web app development is to keep a person on the web app. With that said I need to add blogs and affiliate pages to my project. The only way I know how to do this is iframe. I found one option on this site but it did not make any sense except for adding | safe to the url. [1]: generate iframe from django tag I looked at the above link and the question I have if I need to use serializer in my code for my project web app? My code is : Affi web app web_host_python.html <html> <head><title>Web Host Python Hosting</title></head> <body> {{ whpaff.html | safe }} </body> </html> whpaff.html <!DOCTYPE … -
Error on process url on static files
I have a website on django mezzanine. Everything works fine, but the uploaded files are not processed correctly Here the settings on production: In [2]: settings.STATIC_ROOT Out[2]: '/home/user/webapps/static_app/' In [3]: settings.STATIC_URL Out[3]: '/static/' In [4]: settings.MEDIA_ROOT Out[4]: '/home/user/webapps/static_app/media/' In [5]: settings.MEDIA_URL Out[5]: '/static/media/' If I upload a file using django-filebrowser the file is loaded and stored in the STATIC_ROOT, but somehow the thumbnail is not generated and in the django-filebrowser panel the src of the thumbnail is /static/media/. If I load the image file in a post, I see the image correctly in the WYSIWYG editor, the html generated in there point correctly to the image url. The problem is the published post where the image is broken because the src is, like in the filebrowser panel, /static/media/ The error is in the url process of the static file, but I don't know where to look. I already checked: The permissions on the server are ok. The Pillow installation works. The images in static/ are available and I can load them from the browser. Any suggestion where to look? -
Is there a simple django example of sqlite3 db working in memory?
I’m trying to make Django app that runs on sqlite3 db in memory (in production). The steps seems simple Get an in-memory database running Attach the disk database (file) Recreate tables / indexes and copy over contents Detach the disk database (file) but his is all new to me and I have problems with implementing them. So far I’ve written: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } app.py from django.apps import AppConfig import sqlite3 import os from StringIO import StringIO from django.conf import settings class EnquirerConfig(AppConfig): name = 'enquirer' def ready(self): con = sqlite3.connect(os.path.join(settings.BASE_DIR, 'db.sqlite3')) tempfile = StringIO() for line in con.iterdump(): tempfile.write('%s\n' % line) con.close() tempfile.seek(0) sqlite = sqlite3.connect(":memory:") sqlite.cursor().executescript(tempfile.read()) sqlite.commit() sqlite.row_factory = sqlite3.Row This is all based on the following: How to load existing db file to memory in Python sqlite3? Django - in memory sqlite in production I've also tried if settings.DATABASES['default']['NAME'] == ':memory:': call_command('migrate', interactive=True) However, this does not seem to work - I still have unapplied migrations and ‘no such table’ exception. -
Django QuerySet returns duplicate instance using "filed__in" on list
I have a model like this: class Post(models.Model): STATUS_CHOICE = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICE, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() This model use tags provide by taggit. So I want to find the similar blogs according to the number of the shared tags the have(actually it is the example on 《django by example》). I use this: post_tag_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tag_ids) \ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')) \ .order_by('-same_tags', '-publish')[:4] I know the what the first line means.But if the first line return the blog's id list [1,2,3,4,5] and the second line filter all posts.when a post have a id list like this [1,2,6,7] it will return 2 similar_blogs because they have 2 shared id.so I do not know what's going on?(I know annotate meas and I know aggregation means) And also why this three lines of code can find the similar blogs according to the tags they shared! -
How add in django admin a filter field from a custom join?
I need to add a filter for a field that exist in a VIEW that is part of a calculation. It can be add to the table as a JOIN: In SQL: SELECT d.*, r.saldo, r.estado FROM recaudo_deuda d JOIN reporte_base r ON d.id=r.deuda_id r.estado is the field for the filter. I need a way to add the join + fields or swap the model/queryset on the LIST view and use the normal one in the edit views. -
Setting up Apache2 to use Django with mod_wsgi, No module named 'django' error
I am trying to set up Apache2 to use mod_wsgi to connect to Django. I have a local development server set up running apache2 to serve the majority of the files for the website. However, I wish to serve the contact page using Django as I have a Django app that is a contact form. I am also using virtualenv as the python path. I have followed the instructions on the Django project documentation. My folder structure is: -mysite.com -myproject -contactApp -myproject -env mysite.com.conf <Directory /home/user/Documents/webdev/mysite.com/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.com python-home=/home/user/Documents/webdev/mysite.com/myproject/env python-path=/home/user/Documents/webdev/mysite.com/myproject/env/lib/python3.5/site-packages WSGIProcessGroup mysite.com WSGIScriptAlias /contact /home/user/Documents/webdev/mysite.com/myproject/myproject/wsgi.py process-group=mysite.com The problem that I am having is a 500 Internal Server error when I try to reach mysite.com/contact The apache error.log gives the following errors: [Mon Jun 12 23:03:09.649249 2017] [wsgi:error] [pid 25755:tid 139706287081216['/home/user/Documents/webdev/mysite.com/myproject/env/lib/python35.zip', '/home/user/Documents/webdev/mysite.com/myproject/env/lib/python3.5', '/home/user/Documents/webdev/mysite.com/myproject/env/lib/python3.5/plat-x86_64-linux-gnu', '/home/user/Documents/webdev/mysite.com/myproject/env/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/user/Documents/webdev/mysite.com/myproject/env/lib/python3.5/site-packages'] [Mon Jun 12 23:03:09.649846 2017] [wsgi:error] [pid 25755:tid 139706287081216] [remote 127.0.0.1:39990] mod_wsgi (pid=25755): Target WSGI script '/home/user/Documents/webdev/mysite.com/myproject/myproject/wsgi.py' cannot be loaded as Python module. [Mon Jun 12 23:03:09.649925 2017] [wsgi:error] [pid 25755:tid 139706287081216] [remote 127.0.0.1:39990] mod_wsgi (pid=25755): Exception occurred processing WSGI script '/home/user/Documents/webdev/mysite.com/myproject/myproject/wsgi.py'. [Mon Jun 12 23:03:09.650380 2017] [wsgi:error] [pid 25755:tid 139706287081216] [remote 127.0.0.1:39990] Traceback (most recent call … -
Nested Regroups - Django
I have a model with the following fields: "Date", "Employee", and "Planned Hours". Each employee has various planned hours for various dates. I'm attempting to structure my template where employees are listed in rows and their planned hours are listed in columns under the correct corresponding date. Something like this My template looks like this so far: {% regroup emp3 by employee_name as emp9 %} {% for employee_name in emp9 %} <!--Job--> <div class="table-row table-job-column employee-row"{{employee_name.grouper}}</div> {% for x in employee_name.list %} <div class="table-row table-fr-column">{{x.planned_hours}}</div> {% endfor %} {% endfor %} My issue with the current structure is it places the first "planned hour" next to the employee. I need to be able to insert a blank column if there are no planned hours for that date. I realize I haven't included a nested regroup, but everything I've tried hasn't worked. Note: I'm pulling my column dates in outside the regroup. -
How do I allow the editing of my extended UserProfile with UserChangeForm Django?
Fist of all this is my first actual post here, so please be gentle. I have been working with Django for a few weeks now and have overcome most troubles by searching here and on Google, however I seem to be stuck when trying to allow a user to edit their profile. Specifically allowing a user to edit the field that I extended to the normal Django User. I am able to allow the user to view and update all of the info contained in the regular Django User, however when the form displays the "company_name" field, it does not auto-populate with the current value and it does not save if the user types a different company in. Forms.py class EditUserProfileForm(UserChangeForm): class Meta: model = UserProfile fields= ('company_name','password',) class EditUserForm(UserChangeForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') Views.py def edit_profile(request): content = {} profile = request.user.get_username() if request.method == 'POST': form = EditUserProfileForm (request.POST, instance=request.user) form2 = EditUserForm (request.POST, instance=request.user) content['form'] = form content['form2'] = form2 if form.is_valid() and form2.is_valid(): new_user = form.save() new_user2 = form2.save() return render(request, 'website/view_profile.html', content) else: content['form.errors'] = form.errors content['form2.errors'] = form2.errors else: form = EditUserProfileForm(instance=request.user) form2 = EditUserForm(instance=request.user) content['form']= form … -
multiprocessing.Process.start() blocks on Linux when called from Django
I have a little Django view which does some heavy lifting (represented here by time.sleep) in a thread: from multiprocessing import Process from time import sleep class FooView(View): template_name = 'foo.html' def get(request): c = Process(target=sleep, args=(50,)) c.start() return render(request, self.template_name) You would expect that this view would return a response almost immediately, and indeed it does, on my Mac. On my Linux VM, the page spins for 50 seconds and then returns, so c.start() actually blocks, without any call to c.join(). In addition, the call to c.start() only blocks within the context of the Django view, for instance, I can verify that it does not block using the command prompt: $ python3 Python 3.6.1 (default, Jun 12 2017, 19:31:58) [GCC 6.2.0 20161005] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from time import sleep >>> from multiprocessing import Process >>> c = Process(target=sleep, args=(50, )) >>> c.start() >>> # prompt returns immediately, so no problem. I've also tried using Python 3.6.0, but the same problem arises there. Django version is 1.11. My mac, where it works unconditionally uses Python 3.6.0 and Django 1.11. How can I start to debug this problem? -
Django form not saving to DB
I tired using the formset to create a form but the form is not saving. The form is imported from my model and four forms has foreign key to the main form. My terminal looks like this: [12/Jun/2017 22:26:20] "POST /model_form/ HTTP/1.1" 200 25267 My view: def careerForm(request): if request.method == 'POST': form1 = ModelForm(request.POST or None, request.FILES or None) formset1 = ModelFormSet(request.POST or None, request.FILES or None) formset2 = ModelFormSet(request.POST or None, request.FILES or None) formset3 = ModelFormSet(request.POST or None, request.FILES or None) formset4 = ModelFormSet(request.POST or None, request.FILES or None) if form1.is_valid() and formset1.is_valid() and formset2.is_valid() and formset3.is_valid() and formset4.is_valid(): message = "Thank you" career.vacancy = get_object_or_404(Vacancy, pk = request.POST.get('vacancy')) form1.save() formset1.save() formset2.save() formset3.save() formset4.save() return HttpResponseRedirect('successful') else: message = "Something went wrong" context = { 'message': message } return render(request, 'library/careerForm.html', context) else: form1 = ModelForm() formset1 = ModelFormSet() formset2 = ModelFormSet() formset3 = ModelFormSet() formset4 = ModelFormSet() context = { 'form1': form1, 'formset1': formset1, 'formset2': formset2, 'formset3': formset3, 'formset4': formset4 } return render(request, 'library/careerForm.html', context) -
How to use Django's PasswordChangeView with a custom user?
I want to use the default PasswordChangeView to change passwords for users in a project. The problem is that by default it works for the current user. Is it possible to use the view with a custom user, i.e. provided in the URL? # this doesn't work by default url(r'users/(?P<user_id>\d+)/change_password/$', PasswordChangeView.as_view() name="password-change") -
Django static files not serving in DetailView
Trying to create a Profile View in the app I just started. I can't seem to figure out this simple issue I'm having though. When I load my index page or any other page that doesn't have a pk, everything loads correctly. However, whenever I attempt to load a page that has something like /profile/1/ in the url, the staticfiles won't load. I keep getting a 404. Please help! My code is rather long already, but I'll break it down. I'll add my settings, urls, and views, and profile page. I can't think of anything else that would be needed at this time. Settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'dispatch/templates') STATIC_DIR = os.path.join(BASE_DIR, 'dispatch/static') MEDIA_DIR = os.path.join(BASE_DIR, 'dispatch/media') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR] MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' URLS.py at Project level from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'', include('dispatch.urls', namespace='dispatch')), url(r'^admin/', admin.site.urls), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) URLS.py at App Level: # SET THE NAMESPACE! app_name = 'dispatch' # Be careful setting the name to just /login use userlogin instead! urlpatterns=[ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^profile/(?P<pk>\d+)/$', views.ProfileDetailView.as_view(), name='profile_detail'), ] Views.py class ProfileDetailView(DetailView): context_object_name = 'profile_detail' … -
How to use sleep effectively in python 2.7 without increasing the active threads
I need to recursively call API request if an error occurs after making it sleep for few seconds. But I cannot allow to sleep because only limited number of active threads are allowed in Apache. So there comes situation like all active threads are in the sleep state. How can I handle this situation currently, I am using like from time import sleep def api_request(flag=0): time_delay = 2**flag flag = flag + 1 result = apicall() if result['status']="succes": return(result) else: if flag < 5: sleep(time_delay) api_request(flag) else: print "api request failed" I am looking alternative solution that won't sleep the thread but it calls the function after few seconds -
Keep data after deleting object in ManyToMany relationship
I have a model that has a M2M with another model. Like this: class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): author = models.ManyToManyField("Author") I want to keep the data in the intermediate table even if I delete an object from Author which was added to a Book object. Much like the Foreign Key field has the on_delete=models.DO_NOTHING. I don't think Django has this 'feature'. Every time I execute Author.objects.all().delete(), the field author from Books becomes empty. I don't want them to be empty. I want to keep the data prior to delete(). The reason I want to do this is because I receive a feed and I do a summary on this feed. I delete the objects from author because they might be updated and I don't want to keep checking the data. It's easier to delete and the data is not supposed to change the PK's. -
Python localhost server
Whenever I use py manage.py runserver on windows powershell it causes python to crash, Python has stopped working window pops up. Any idea why? I've tried rebooting which causes a different type of Error """python.exe: can't open file '.\maanage.py': [Errno 2] No such file or directory""". So I created another project and tried runserver and it again caused the first error.All Installation commands ran smoothly but why this error?