Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django send_mass_mail over 300 mail errors
I have a Django project with Gunicorn and Nginx. I have to send over 300 mail. First, I solved Connection Timed Out 504Nginx with proxy_.._timeouts. After that, I got Bad Getaway 502. I try some solutions, but I couldn't send mails because Bad Getaway 502 arisen. How to configure nginx to send over 300 mails at once? -
customizing django admin ChangeForm template / adding custom callable fields
I'm able to insert (lame) static text onto the change form admin page, but I'd really like it to use the context of the current object being edited! For instance, I want to format on the MyObject change form a URL to include the ID from a ForeignKey connected object (obj) as a link. My admin objects: class MyObjectChangeForm(forms.ModelForm): class Meta: model = MyObject fields = ('field1', 'obj',) class MyObjectAdmin(admin.ModelAdmin): form = MyObjectChangeForm list_display = ('field1', 'obj') def render_change_form(self, request, context, *args, **kwargs): self.change_form_template = 'admin/my_change_form.html' extra = {'lame_static_text': "something static",} context.update(extra) return super(MyObjectAdmin, self).render_change_form(request, context, *args, **kwargs) My template templates/admin/my_change_form.html: {% extends "admin/change_form.html" %} {% block form_top %} {{ lame_static_text }} <a href="http://example.com/abc/{{ adminform.data.obj.id }}?"/>View Website</a> {% endblock %} How do I insert dynamic context from the current object into the admin change form? -
Registering Different types of Users in Django
I wont be needing to write codes much,I just need an idea.I am trying to make users in two different categories.That is a User can either have a Profile or Shop both not both. class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,editable=True) class Shop(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,editable=True) I want all users to either have one of both,They will register with the same form without being able to switch from one to another once they have registered for it.As at now what I'm doing is If i dont want a shop-owned User to have the previlege of a profile i do def post_product(request): try: if bool(request.user.profile)==False: ..... except: pass But I have to do this for all views that require previledges. I want something site-wide that i can put in settings or put at the view like @login_required .Please how can I go about this.Thanks -
Center map on GeoJSON feature
I am loading a geojson file from my server and displaying it on the map. This works. But I am not sure how to actually center the map on the map data created by the geojson. Its a polygone. I want to center on the polygone and fit it as best I can in the window. function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(0, 0), }); map.data.loadGeoJson("{{ pa.geojson_file.url }}"); } -
Django says OverflowError at /admin/ while trying to access /admin/
I noticed this error while trying to access /admin/. Whenever /admin/model_name or /admin/ or /admin/* is accessed django says OverflowError at /admin/ and regular expression code size limit exceeded. I did a little digging and came across this SO post. I have checked urls.py of app since regex are mostly used in urls. But all I have is a typical admin url, nothing complex. from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), .... ] Stack trace Environment: Request Method: GET Request URL: http://domain/admin/ Django Version: 1.9.8 Python Version: 2.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'haystack', 'myapp.apps.core', 'myapp.apps.home', 'myapp.apps.accounts', 'myapp.apps.dashboard', 'myapp.apps.app1', 'myapp.apps.app3', 'myapp.apps.app5', 'myapp.apps.app6', 'myapp.apps.app7', 'myapp.apps.app8', 'myapp.apps.app9'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in wrapper 265. return self.admin_view(view, cacheable)(*args, **kwargs) File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner 244. return view(request, *args, **kwargs)> File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs)> File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in index 505. app_list = self.get_app_list(request)> File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in β¦ -
Make Django Project Secret Keys accessible from Google Cloud
I have a Django App running on Google Compute Engine VM instance. I am trying to store all the secret keys of settings.py file securely in the Google Cloud and then fetch those values in settings.py file. I can store all the keys in either the VM's Metadata or Google Cloud Bucket. But I am not able to fetch these values in settings.py file. For Example: Let's say Settings.py is: SECRET_KEY = "123-456-789" CLIENT_SECRET_PATH = BASE_DIR + '/../client_secrets.p12' Now, I can store SECRET_KEY variable in either Google VM's Metadata, or Google Datastore and the client_secrets.p12 file in Google Cloud Storage bucket. But I am not able to figure out how to fetch these values back in settings.py. Can someone please suggest a good & efficient way to do this ? Thanks, -
How to store Form Data (a Django form) to browser's local storage, using javascript and not Django sessions?
I want to take the data from the user through a form (a Django form) and store it in the browser's local storage, using javascript and without using Django sessions. My code looks like: ./forms.py : class digitize(forms.Form): medicinename = forms.CharField(label='Medicinename', max_length=100) quantity = forms.CharField(label='Quantity', max_length=100) ./e_commerce.html : <form id="digitizer_form" role="form" action="/MediciansDigitizer/Presc/" method="post" enctype="multipart/form-data"> {% csrf_token %} <h3 class="prod_title">Add Detail</h3> {{iform.as_table}}{{ dform.as_p }} <div class=""> <button type="Submit" class="btn btn-default btn-lg">Digitize</button> </div> </form> <script> window.onload = function() { // Check for LocalStorage support. if (localStorage) { // Add an event listener for form submissions document.getElementById('digitizer_form').addEventListener('submit', function() { // Get the value of the MedicineName field : Now, this is where I need help. Here I want to give in the 'MedicineName' field of the form defined above, So that I can get the MedicineName entered by the user from the form and store it in the browser storage. The logic should look something like this: // get the value of the MedicineName so that I can store it in a variable like this: var Medicine = document.getElementById('MedicineName').value; //but because I am using a django form, and linking it in the e_commerce.html template through {%csrf_token%} , {{iform.as_table}} and {{ dform.as_p }} and β¦ -
In Django, how do I order_by() when reaching across tables?
I'm trying to filter my Friendships objects and then order_by user.first_name, but it's not working. Can anyone tell me what I'm doing wrong? Here's my models: class Friendships(models.Model): user = models.ForeignKey('Users', models.DO_NOTHING, related_name="usersfriend") friend = models.ForeignKey('Users', models.DO_NOTHING, related_name ="friendsfriend") created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'friendships' class Users(models.Model): first_name = models.CharField(max_length=45, blank=True, null=True) last_name = models.CharField(max_length=45, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'users' My query is as follows, which returns my needed Friendships, but the order is not correct. I've tried a number of different combinations and examples but just am not sure what I'm not correctly understanding: My query in my controller: ordered_friends = Friendships.objects.filter(user__id=1).order_by('user__first_name') for ordered_friend in ordered_friends: print ordered_friend.friend.first_name, ordered_friend.friend.last_name Note, I've tried a number of combinations in place of user__first_name and I know this is where I'm failing. -
Django - Splitting admin.py
from django.contrib import admin from hisapp.models import * @admin.register(ModelA) class ModelAAdmin(admin.ModelAdmin): class Meta: model = ModelA But the model is not showing in my admin site. What's wrong with the steps above or I missed anything? -
Schema - Ability to change email address (primary user id) in Django
Currently my user table looks like this - (all fields are not null) display_name = CharField # string email_address = EmailField (primary key) # string password = CharField # string However, I have decided to add additional functionality and to allow users to change their email addresses. The flow goes like this Does anyone have any ideas on how to do this? Currently I am thinking of something like display_name = CharField # string email_address = EmailField (primary key) # string password = CharField # string pending_email = EmailField (unique) # string And simply hold the new email address in pending_email before replacing the old email address in email_address But obviously this is far from perfect (e.g. pending_email unique constraint does not cover email_address) Ive thought about just leaving it like this and performing more selects against the database with AJAX queries to check if the desired new email address already lives in email_address before allowing it to be entered into pending_email but this seems still vulnerable to race conditions and poor user experiences on top of being not very database friendly. -
selecting date in date ranges wrong result
Following if statement occasionally gives wrong result. any idea why? if self.start_date <= datetime.datetime.now().date() <= self.end_date: self._is_current = True else: self._is_current = False return self._is_current -
python/django: deployment to heroku fails
I am trying to deploy an app to heroku. It's a python/django app, and it runs fine on my local machine. When deploying, heroku downloads the packages defined in requirements.txt, but then stops complaining about qpython not being able to be built, because it can't find numpy. But from the log output it's visible that numpy is being downloaded, and installed BEFORE qpython. The only thing I could think of is that the logs actually say "Collecting" and "Downloading", but not explicitly "Installing"...Could it be that the way heroku handles this causes qpython to be built before numpy is being installed? It's a weird assumption but the only one I could think of. In any case, I don't and would not know what to do. I defined python to be python 2.7.12 in runtime.txt. $ git push heroku-dev django6_12:master Counting objects: 21, done. Delta compression using up to 4 threads. Compressing objects: 100% (20/20), done. Writing objects: 100% (21/21), 1.99 KiB | 0 bytes/s, done. Total 21 (delta 16), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: /*...more output omitted for brevity */ remote: -----> Python app detected remote: -----> Installing python-2.7.12 remote: -----> Noticed cffi. β¦ -
How to make 2 columns unique (1 value can only appear in 1 row 1 column)
How do I do this in mySQL, (particularly django) Currently I have a user table that has the following schema username = ... password = ... email = ... verified = ... pending = ... (an unverified email change request) The pending field is usually empty, but when a user requests a change of email addresses, it becomes filled with the "new address" - that is until the verification link sent to their email is clicked - which will then replace email with pending and set pending to empty once more However, since my system has the constraint that any email address, pending or official, must be unique - I need the unique constraint to be applied simultaneously to both columns username = ... password = ... email = ... UNIQUE verified = ... pending = ... UNIQUE Not the combination, but as an extension. Is this possible? -
javascript dajngo html tags
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true); var articles = [ {% for article in article_list %} {% if not forloop.first %},{% endif %} { title: "{{ article.title }}", slug: "{{ article.slug }}", content: "{{ article.content }}", authors: [ {% for author in article.authors.all %} {% if not forloop.first %},{% endif %} { first_name: "{{ author.first_name }}", last_name: "{{ author.last_name }}", } {% endfor %} ] } {% endfor %} ] ] This is code located in calendar-conf-events.js(fullcalendar), and cause error I passing objects to index.html ( which use calendar-conf-events.js ) And, In JS I use objects and template tags, but error -
How can I use "for loops" in Jquery without this mistake?
Here's the problem: I have a simple unordered list of posts. Each post is truncated (250 chars), but should expand when clicked (Using .replaceWith). What I'm trying to do is replace the truncated Post.content with the "untruncated" Post.content. When I try this, the click returns the content of all the Posts in my list. I only want the content of the Post that I am clicking. Here's the relevant code: <ul> {% for post in object_list %}<tr class="{% cycle 'row1' 'row2' %}"></tr> <div class="panel panel-default col-sm-offset-1 col-sm-8"> <p><h4><B><a class="title" href="/posts/{{ post.id }}/">{{post.title }}</a></B></h4></p> <p style="color:gray">Author: <a style="color:darkgray" href="{% url 'accounts:profile' %}"> <span class="link">{{ user.first_name }} {{ user.last_name }}</span></a></p> <hr style=""> <div class="post" > <h5 style="color: rgba(101, 106, 106, 1)">{{post.content|truncatechars:250 }}</h5> </div> <div class="expandContent"> <button class="btn btn-primary btn-sm">Read</button> </div> <br> <br> <br> <div class="content"> <p>{{ post.content }}</p> </div> </div> <br> {% endfor %} </ul> Above is my basic list. Here is the JS that should expand the Post.content: <script src="{% static 'posts/jquery-3.1.1.js' %}"></script> <script type="text/javascript"> $(".expandContent").click(function(){$(".post").replaceWith($('.content')); }); </script> If any more information or code would be helpful, please let me know. If it's at all relevant, this project is on Django 1.10. Thank you! -
Proper way to populate model with one-to-one relationship with User model - Django
I am using Djangos basic User model. There are some fields that I wanted to add to the User model for my own needs. I created a new model named Profile and made it have a one-to-one relationship with the User model. I can now create a user and then populate the Profile model that is associated with that user. However, the current implementation of populating the Profile model seems sloppy. For a couple reasons. I first create a user and then populate the Profile table. If the user didn't supply certain data then the Profile model wont be updated. How can I make sure the user wont be created before the Profile? I want to know if there is a way to make a constructor for the Profile model. The current way I am populating the Profile model is very sloppy, here is my implementation: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = User.objects.create_user( username=validated_data['email'], email=validated_data['email'], ) user.set_password(validated_data['password']) user.profile.account_email = validated_data['email'] user.profile.middle_name = validated_data['middle_name'] user.profile.initial_name = validated_data['initial_name'] user.profile.bio = validated_data['bio'] user.student.additional = validated_data['additional'] user.save() return user class Meta: model = User Also any suggestions on the best way to approach having an extra model to keep track β¦ -
How to have a Custom User model for my app while keeping the admins working as default in Django?
Here is what I am trying to accomplish: - Have admins login to the admin page using the default way (username and password). - Have users register/login to my web app using a custom User Model which uses email instead of password. They can also have other data associated that I don't need for my admins. - Separate the admin accounts and user accounts into different tables. I checked how to create a Custom User class by extending AbstracBaseUser, but the result I got is that my admins also became the new user type. So can I have the Custom User model be used for my app users while keeping the default admin system untouched? Or what is a good alternative to my design? -
how to add django_google_charts to installed apps
I am new to Django and I'm trying to integrate Google charts. I followed instructions from 'https://danpalmer.me/projects/django-google-charts' and created appropriate files. However when I run ther server I get an error which reads "Import error: No module named django_google_charts". The pip install was successful and I see a 'googlecharts' folder in my 'site-packages' folder. In my project's settings.py file under INSTALLED_APPS I have added 'googlecharts'. What am I missing? P.S.: There were also an error like "No module named qsstats" that I fixed by installing qsstats again. -
Django - Simple search form
Using Django 1.9 with Python 3.5, I would like to make a simple search form: views.py from django.views import generic from django.shortcuts import render from .models import Movie, Genre class IndexView(generic.ListView): template_name = 'movies/index.html' page_template = 'movies/all_movies.html' context_object_name = 'all_movies' model = Movie def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update({ 'all_genres': Genre.objects.all(), 'page_title': 'Latest' }) return context def get_queryset(self): query = request.GET.get('q') if query: return Movie.objects.filter(title__icontains=query) else: return Movie.objects.all() form <form method="GET" action="" id="searchform"> <input class="searchfield" id="searchbox" name="q" type="text" value="{{ request.GET.q }}" placeholder="Search..."/> </form> For some reason I keep getting the error: name 'request' is not defined I'm not quite sure what I'm doing wrong, any help would be appreciated. -
How to view backup Postgresql database in Postgresql Studio
I have just backup Postgresql database , I would like to view it with Postgresql studio? I have searched on Internet but found no tutorial. Please give me some keywords or a link so I could read more about how to view it. Thank you! -
cannot import name multiarray Django Apache2
I am currently running a django app on an ec2 with apache. The app works fine when I run it using djangos runserver command. However I receive a 'cannot import name multiarray' when I run it using apache. I have tried reinstalling numpy and various packages many times and have still not had any luck. Below is my .conf file for apache. I am using python3.4 and have recently updated pip within my venv. I can provide more information if necessary. Include conf-available/serve-cgi-bin.conf WSGISCRIPTALIAS /site /home/ubuntu/site/initSite/wsgi.py WSGIDaemonProcess site_group threads=15 display-name=%{GROUP} python-path='/home/ubuntu/site:/home/ubuntu/site/envsite/lib/python3.4/site-packages' <Directory /home/ubuntu/site> <files wsgi.py> Require all granted </Files> </Directory> <Location /site> WSGIProcessGroup site_group </Location> Alias /site1/ /home/ubuntu/site/fullSite/static/css <Directory /home/ubuntu/site/fullSite/static/css> Require all granted AllowOverride All </Directory> -
Understanding population script and os imports in Django
I would like to create a population script for the application I'm building. I've done a few tutorials and am using them as crutches as I work on my project. This is the tree for the application. . βββ db.sqlite3 βββ functional_tests βββ geckodriver.log βββ manage.py βββ marketplace β βββ db.sqlite3 β βββ __init__.py β βββ __init__.pyc β βββ models.py β βββ __pycache__ β β βββ __init__.cpython-35.pyc β β βββ models.cpython-35.pyc β β βββ settings.cpython-35.pyc β β βββ test.cpython-35.pyc β β βββ urls.cpython-35.pyc β β βββ views.cpython-35.pyc β β βββ wsgi.cpython-35.pyc β βββ settings β β βββ base.py β β βββ development.py β β βββ __init__.py β β βββ __init__.pyc β β βββ production.py β β βββ __pycache__ β β β βββ base.cpython-35.pyc β β β βββ development.cpython-35.pyc β β β βββ __init__.cpython-35.pyc β β β βββ testing.cpython-35.pyc β β βββ staging.py β β βββ testing.py β βββ settings.pyc β βββ static β βββ templates β βββ test.py β βββ urls.py β βββ urls.pyc β βββ views.py β βββ wsgi.py β βββ wsgi.pyc βββ Marketplace.sublime-project βββ Marketplace.sublime-workspace βββ populate_marketplace.py βββ requirements βββ base.txt In order to create a population script I need to import os and and some django files β¦ -
Django PermissionRequiredMixin not working when user doesn't have the permission required
Okay i have this view and im using django PermissionRequiredMixin, when the user has the change_item permission i specify there all works fine from django.contrib.auth.mixins import PermissionRequiredMixin class MyView(PermissionRequiredMixin,View): template = 'myapp/item_detail.html' permission_required = 'myapp.change_item' def get(self, request, *args, **kwargs): #Query here return render(request, self.template) But,when user doesn't have it, i got a 404 error page saying that myapp/login it's not valid: **Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/myapp/login?next=/myapp/item/35/** The current URL, myapp/login, didn't match any of these. That login it's set in settings LOGIN_URL and works perfectly with everything else...but not with this, and i also see that a login string it's in the middle of the url from the error...am i missing something about mixins ?, what am i doing wrong ?? Thanks in advance !! -
django 1.10 render template html class
After a user fills out a form on my site, I user render(request, html, context). I'd like to return the user to the same part of the page after they register. I am not using any front end frameworks (like angular - thats my next project). How would I go about doing this? views.py: def homepage(request): countries = Country.objects.count() cities = City.objects.count() start_trip_date = date(xxxx, x, x) today = date.today() total_days = today - start_trip_date queryset_list = Post.objects.active()[:6] query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(title__icontains=query) | Q(content__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) ).distinct() contact_form = EmailUpdatesForm(request.POST or None) if contact_form.is_valid(): contact = contact_form.save(commit=False) contact.email = request.POST['email'] contact.first_name = request.POST['first_name'] contact.save() profile_data = { 'email': contact.email, 'first_name': contact.first_name, } plaintext = get_template('email/frontpage_registered_email/email_text.txt') htmly = get_template('email/frontpage_registered_email/email_template.html') text_content = plaintext.render(profile_data) html_content = htmly.render(profile_data) subject = "{0}, thank you for registering with xx!".format(contact.first_name) from_email = 'xx@gmail.com' to_email = contact.email msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, "text/html") msg.send() return render(request, "homepage/homepage.html", {}) else: print contact_form.errors, context = { 'object_list': queryset_list, 'countries': countries, 'cities': cities, 'days_traveling': total_days.days, 'contact_form': contact_form, } return render(request, "homepage/homepage.html", context) and a made up html to show what I mean: <body> <div class="first">content</div> <div class="second"> <form id="contact_form" method="POST" action="." enctype="multipart/form-data" β¦ -
Add a 'Save as new' action to django admin change list
Goal I am trying to add an action that opens the change_form of the selected object and has only two buttons on the submit-row, 'Cancel' and 'Save As New'. I have so far tried this: def save_as_action_admin(modeladmin, request, queryset): rows = len(queryset) if rows > 1: messages.warning(request, "This action can't be executed with %s objects selected. \ You should select only one." % rows) else: selected_item = get_object_or_404(queryset) form = ItemForm(instance=selected_item) return render(request, "admin/save_as_action.html", {'test_action': form, 'opts': modeladmin.model._meta}) save_as_action_admin.short_description = "Save As New" minimalist template: {% extends "admin/change_form.html" %} {% block content%} {{test_action}} {% endblock content%} but it comes with some problems like: this is hard-coded to a specific model as you can spot ItemForm, indeed I have a few and I want to apply this action to all of them. I already have fieldsets and inlinesand I want the 'save_as' page to look like the 'change_form' page except the submit-row. Help What I really need are the steps I should follow and a bit of explanation about the blocks of change_form template necessary for this, because it looks like a bunch of tags to me. I am really new in django and in web programming as well. Thanks in β¦