Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request with list of id's for many to many relationship in django rest framework
What is the correct way of implementing the following api with django and django-rest-framework. First the model Model def ChatModel(models.Model): users = models.ManyToManyField(User, through=ChatUser) Response The desired response when getting this model where the many to many relationship is presented with a nested serializer: [ { "id": 1, "title": "gossip", "users": [ { "id": 1, "name": "George" }, { "id": 2, "name": "Jerry" } ] } ] The request is the critical part: Have the api receive a list of primary keys and create the user -> chat relationship in the backend. Request { "title": "gossip", "users": [1,2] } So how do I allow for such a request to create an object with a many to many relationship. -
pip install mod_wsgi fails in virtualenv
I'm trying to install mod_wsgi using pip in python 2.7.10 on mac os 10.12 inside a virtual. I intend to use it in a a Django 1.10.3. When I run "pip install mod_wsgi" I get the following output: Collecting mod_wsgi Using cached mod_wsgi-4.5.7.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/sf/kdqqs98d06326180mss7hggh0000gn/T/pip-build-hgA7s1/mod-wsgi/setup.py", line 247, in <module> APR_INCLUDES = get_apr_includes().split() File "/private/var/folders/sf/kdqqs98d06326180mss7hggh0000gn/T/pip-build-hgA7s1/mod-wsgi/setup.py", line 219, in get_apr_includes stdout=subprocess.PIPE, stderr=subprocess.PIPE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/sf/kdqqs98d06326180mss7hggh0000gn/T/pip-build-hgA7s1/mod-wsgi/ I'm new to virtualenv so it might be that I'm just missing something with how to set that up. I've tried upgrading pip, reinstall setuptools and ez_setup via pip. -
Django - allow to access admin page superusers only
I'd like to restrict access admin page for everyone, except superuser. By access I mean opening the admin page. For now I've created user registration and user authentication, none of my users are staff members. So when user is logged in they still can go to admin url, where they have notice: "You don't have permission to edit anything.". Is there any way to redirect non superusers to other page (like home page or 404.html)? -
Django repeated block that isn't rendered in place
I use django-macros to insert repeated blocks into django template. It works fine, but I want to change the code so that repeated_block doesn't render anything. How can I accomplish that? -
Maintaining multiple databases in a Django App
My use-case is, I want to maintain multiple databases in a single instance. I will have n databases running for n apps in different server. I want to maintain some of the tables in those n databases in a single Master instance. The tables will be made un-editable in those n instances and they must be editable in the Master instance and when edited the change should reflect across those tables in the n instances. It is a kind of managing a couple of static table data in a Master instance, like the Master feeding the child database tables with the Updated data. The databases are running on Postgres. -
Using threadsafe queue.queue object in django
We have a requirement like this. A gift card transaction is to be performed through our vendor's webservice. The vendor has given us a token string that can be used only by one transaction at a time. The decision is to build a facade rest-layer and not to expose the token string. The approach was to have the token in a queue object and use it while hitting the target webservice and return it to the queue once done with it. I know that it is a blocking implementation. But we dont have a high volume of such transactions. So that should not be a problem. Here are my questions How do we maintain a single queue object in a webapp? We use django. Is there an alternate way to do it? In our case there is only one string. Can we do it with multiple strings too? -
Best frontend framework for django web application?
I am currently using JQuery with html and css for frontend of my application. I read about angular and react js but those two are built for node.js server-side application. Can you suggest any other frontend frameworks for django server-side application? -
django model automation possible?
I have a small problem with django, i'm beginner, and i would like to delete a file right before a new one is uploaded. I use this in my model.py class Object(models.Model): photo1 = models.ImageField('main image', upload_to='%Y/%m/%d', max_length=200) It works well for upload, but it keep the old image on hard drive. I can do a script to delete or move to a trash directory the file, but it's a bit problematic when using the django admin interface, because it won't update as i want. Is there a good way to delete the old photo1 variable object before storing the new one? Thanks for any help! (sorry for bad english) -
initial data in django model form
I use the following code to call the register_guest_order view but it doesn't prefill the guest data on the order form. Model/Form: class Order(models.Model): guest = models.ForeignKey('hotel.Guest', on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) amount = models.IntegerField() item = models.ForeignKey('hotel.Item', on_delete=models.CASCADE) price = models.IntegerField(default=1) is_paid = models.BooleanField(default=False) paid_date = models.DateField(blank=True, null=True) class OrderForm(forms.ModelForm): class Meta: model = Order fields = ('guest', 'item', 'amount') View: @login_required def register_guest_order(request, *args, **kwargs): if request.method == "POST": form = RegisterGuestForm(request.POST, initial={'guest': kwargs['go']}) if form.is_valid(): guest = form.save(commit=False) guest.save() #post.published_date = timezone.now() return redirect('guests') else: return redirect ('new_order') context = {'form': form} return redirect('guests') url: url(r'^guest/orders/(?P<go>\d+)$', views.register_guest_order, name='new_guest_order'), template: <a href="{% url 'new_guest_order' go=Guest.pk %}"> -
Apache or Nginx with gunicorn for flask, django apps. Development + Production servers
My project have next structure: 1) Website that serve on port 80 and using Django server side. 2) 2 Different flask rest api programs, every one surf on different port (5000,5001). I have two questions, 1) What is the best way to deploy it for production? Nginx with Gunicorn or Apache? Also, how can I start all this programs together from one place. 2) How to make on one server two projects? one for port 80 (production) and one 8000 for development that also will go to other api ports of development? In android there are way to compile project for debug / release and automatically the port variables will get the right values, there are something similar on pycharm? Thanks, Lior -
Python/ Django - Import Error : No module named apps
I got a stracktrace as simple as: /usr/bin/python2.7 /home/gridlockdev/Desktop/pycharm-projects/dlsu- gridlock-pycharm/manage.py runserver 8000 ImportError: No module named apps Process finished with exit code 1 after trying to Run the application. Below are my settings.py, manage.py, apps.py settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REPOSITORY_ROOT = os.path.dirname(BASE_DIR) DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mongodb_engine', 'djangotoolbox', 'djgeojson', 'leaflet', 'reversion', 'gridlock' ] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'comet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'comet.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default' : { 'ENGINE' : 'django_mongodb_engine', 'NAME': 'geodjango', 'USER' : 'geo', 'HOST' : 'localhost', 'PASSWORD' : '***' } #'default':{ # 'ENGINE' : 'django.contrib.gis.db.backends.postgis', # 'NAME' : 'geodjango', # 'USER' : 'geo', # 'HOST' : 'localhost', # 'PASSWORD' : '***' #} } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = … -
Admin page loads too slow when using inlines
I have an inline in my model admin class: class LogAdmin(admin.ModelAdmin): inlines = [LogExerciseInline] and here's what this inline class looks like: class LogExerciseInline(admin.TabularInline): model = LogExercise ordering = ['order'] extra = 0 It takes around 50 seconds to load admin change form on my machine for an object with only three related LogExercise's. And if I remove inlines field from LogAdmin class, it takes only 2 seconds to load the page. I tried to use Django Debug Toolbar to get some details about it, but it adds too much overhead, so it takes minutes to load just one page. -
how to do logging in Django 1.9
Software Django 1.9 Python 3.4 Postgres 9.x What happened I am using the below code in Django 1.9 from django.db import connection cursor = connection.cursor() cursor.execute('SELECT .... WHERE ... GROUP BY p.id') rows = cursor.fetchall() I wanted to see the rows in a log file What I did try I copied pasted from the documentation into my settings.py the following import logging.config LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(DJANGO_ROOT, 'WIT.log') }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } What's the problem? After that I am stuck as to how do I log that particular rows. Can help? -
How can I pass multiple arguements from Django Template to View via URL?
I am trying a simple thing User clicks a question displayed. The link when clicked would take in the question id and pass it as an argument to display the relevant Choices. The user is asked to chose a Choice and then the next page would display how many people has voted for that Choice(including the user's current decision). The Error I am getting is when I start the app using 127.0.0.1:8000/polls/ it displays the question. Then when I click the question the url becomes 127.0.0.1:8000/polls/3/ which is correct as 3 is the question id. So it is expected to show the Choices for the Question ID. But it is not showing. The Error is: NoReverseMatch at /polls/3/ Reverse for 'results' with arguments '()' and keyword arguments '{'q_id': 3, 'c_test': 'May Be'}' not found. 1 pattern(s) tried: ['polls/(?P<q_id>[0-9]+)/(?P<c_test>\\w+)/results/$'] Request Method: GET Request URL: http://127.0.0.1:8000/polls/3/ Django Version: 1.10.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'results' with arguments '()' and keyword arguments '{'q_id': 3, 'c_test': 'May Be'}' not found. 1 pattern(s) tried: ['polls/(?P<q_id>[0-9]+)/(?P<c_test>\\w+)/results/$'] Exception Location: /home/usr/.local/lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 392 Python Executable: /usr/bin/python3.5 Python Version: 3.5.2 My code is: views.py class IndexView(generic.ListView): template_name = "polls/index.html" context_object_name = "latest_question_list" model = Question … -
Can't migrate Django app - MySQL throws an OperationalError "Too big scale specified"
I am trying to connect my Django app to a MySQL database. I created the database, and tried migrating the app with python manage.py migrate. At this point I get the following error: django.db.utils.OperationalError: (1425, "Too big scale 100 specified for column 'score'. Maximum is 30.") I checked that object in models.py. It looks like this: class Para(models.Model): ... text = models.CharField(max_length=20000) score = models.DecimalField(max_digits=100, decimal_places=5) def __unicode__(self): return self.text[:20] So I changed the max_digits to 20, ran makemigrations and tried migrating again. But I keep getting the same error. I am new to MySQL, and not sure what I am doing wrong. Any help much appreciated. Thanks! -
Django : Cannot access outside smtp server for sending email
I'd like to send email from django application. I've written settings.py and account/views.py with sending email logic as following. I've checked EMAIL_HOST_UESR and EMAIL_HOST_PASSWORD at mailer service. However, it returned an error SMTPServerDisconnected at /account/signup. How should I solve the problem? settings.py # Email Settings EMAIL_HOST = 'smtp.lolipop.jp' EMAIL_PORT = '465' EMAIL_HOST_USER = 'my_account' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_USE_TLS = True # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = 'info@test.com' accounts/views.py # Send email template = get_template('emails/signup.html') content = template.render(Context({'onetime_code': user.onetime_code})) subject = 'test' from_email = 'info@test.com' email = EmailMultiAlternatives( subject, content, from_email, [user.email] ) email.attach_alternative(content, "text/html") email.send() return redirect('/invoice') -
Cannot POST correctly when submitting form in Django
I am trying to upload files (specifically images) to a database. When I try to POST my form in profile_photo.html (attached below), it gives me an error saying: MultiValueDictKeyError at /user_profile/login/upload_profile_photo/ profile_photo.html: <body> <div id="blue_background_with_fibers"> <form class="pull-center white form-signin" role="form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="aqua button2" type="submit" value="OK">Upload</button> </form> </div> detail.html that uses profile_photo.html: <div class="modal fade" id="profile" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Upload Profile Picture</h4> </div> <div class="modal-body"> <form> <!--Insert form here--> <iframe src="upload_profile_photo/" allowTransparency="true" scrolling="yes" frameborder="0" width="560px" height="175px"></iframe> </form> </div> <div class="modal-footer"> <span>Ekho © 2016</span> </div> </div> </div> </div> I believe that I am messing up in my views.py (specifically under the EditProfileView class). Below is my views.py: class EditProfileView(View): form_class = EditProfileForm def get(self, request): form = self.form_class(None); return render(request, 'ekho/profile_photo.html', {'form': form}) def post(self, request): if not request.user.is_authenticated(): return render(request, 'ekho/login.html') else: form = EditProfileForm(request.POST or None, request.FILES or None) if form.is_valid(): user = form.save(commit=False) user.user = request.user user.profile_photo = request.FILES['profile_photo'] file_type = user.profile_photo.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'user': user, 'form': form, 'error_message': 'Image file must be PNG, JPG, or JPEG', } return render(request, 'ekho/detail.html', context) … -
Django print in prod' server
I've gotten use to using print in my python code to show contents of variable and checking the shell output. But i have now migrated all my work onto a online server. Pythonanywhere I don't have the foggiest idea how to do the same now? Can someone point me in the right direction? Print to web console? To a file? Or even to the shell session? Thanks -
Python - Inner Functions
In this block of code I'm trying to figure out how the scoping works. def sort_by_last_letter(strings): def last_letter(s): return s[-1] return sorted(strings, key=last_letter) In my python console I test this like this - >>> from sort import sort_by_last_letter >>> sort_by_last_letter(['hello','a','var']) ['a', 'hello', 'var'] Everything looks good. But I would like to debug this in Pycharm IDE to figure out the working of inner functions so I called the function within the code like this - def sort_by_last_letter(strings): def last_letter(s): return s[-1] return sorted(strings, key=last_letter) res = [] res = sort_by_last_letter(['hello','a','var']) print res This is not invoking the inner function last_letter. I'm not sure why this is happening. Can somebody explain this please/guide me. Thanks -
how to set admin.site.urls as home page in django
some question about django 1.10: I am going to make a website and the home page should be a login page created by django,when i tried to make the admin login page as my site's home page,it failed,can anybody help me ? my urls.py: urlpatterns = [ url(r'^$', include(admin.site.urls)), ] or urlpatterns = [ url(r'^$', admin.site.urls), ] both works wrong. thx -
Do I add Google Analytics tracking script in both parent and child Django templates or just the parent templates on a Django website?
I have a question - I'm launching my first ever website, and am including the Google analytics tracking ID in it. The site is built in Python Django. Does this mean I have to include the tracking script in ALL html template files? What if I have extended a parent template to create a child template or included a child template into a parent template - then, do I have to add the tracking script in all parents and child, or adding it in the parent is sufficient? Further, is there any harm in adding the script in both parent and child - like it is going to doubly show in my Google Analytics Dashboard, cluttering the analysis? Thanks, -
How do I pass two model objects to a get_queryset view?
So what I'm trying to do is pass another model object (Question) to my view.The view currently returns a get_queryset of another model (Post). So this is the context I want to pass through so I can render it in my polls.html: question = get_object_or_404(Question, id=1) context = {'question': question}) urls.py BV = BoxesView.as_view() urlpatterns = [ url(r'^$', BV, name='news') ] view.py class BoxesView(ListView): template_name = 'polls.html' def get_queryset(self): queryset_list = Post.objects.all().filter(category=1).order_by('-date') return queryset_list polls.html {% extends 'parent.html' %} {% block polls %} <p>question goes here</p> #this shows up {{ question.question_text }} #this doesn't show up {% endblock %} parent.html {% extends 'base.html' %} {% block content %} {% for post in post_list %} {% block polls %} {% endblock %} {% endfor %} {% endblock %} models.py class Post(models.Model): title = models.TextField(max_length=70) class Question(models.Model): question_text = models.CharField(max_length=70) -
Iterating Through Many to Many Model
I have a model like so: `class task(models.Model): name = models.CharField(max_length=100) notes = models.TextField() created = models.DateTimeField() created_by = models.ForeignKey(User) subtask = models.ManyToManyField('self') ` I'm having trouble writing out the view for it, essentially <li>task #1</li> <li>subtask#1.1</li> <li>subtask#1.2</li> <li>task #2</li> <li>subtask#2.1</li> <li>subtask#2.2</li> . . . . I tried creating a for loop to iterate through them using but it doesn't show up nested like how I would want it {% for task in items %} <li>{{ task.name }}</li> {% for subtask in task %} <li>{{ subtask.name }}</li> {% endfor %} {% endfor %} -
Python Django Unsuscribe system
Hello guys I'm trying to make a unsubscribe email system, what I'm trying to do it's just tu send a link to unsubscribe a user in the data base perhaps if I have a row called active, it could be 0 or 1 which means if the user don't like to receive emails anymore the row should be changed to 0. The issue here is that if I send a user a link for example domain.com/unsuscribe/1 or domain.com/unsuscribe/1787, the user could unsubscribe all the list set the number in the url. I wonder if there is a system in django to avoid this or a way to make it possible. Thank you ! -
django admin popups properties arent shown
When i want to change plugin or edit existing one( no metter which one i open). Properties in popup arent show or if they are, they arent on right positions. When pop up shows to edit plugin i cant click save. I must scroll out page(ctr and -) to see save button. Its not only save button, most of properties arent show properly How can i fix this? base.html {% load cms_tags sekizai_tags %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <title>{% page_attribute "page_title" %}</title> {% render_block "css" %} </head> <body> {% cms_toolbar %} {% block base_content %}{% endblock %} {% render_block "js" %} <footer> {% static_placeholder 'footer' %} </footer> </body> </html> template_two.html {% extends "base.html" %} {% load cms_tags %} <html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> {% block base_content %} <body id="myPage" data-spy="scroll" data-target=".navbar" data-offset="60"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#myPage">Logo</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li><a href="#about">ABOUT</a></li> <li><a href="#services">SERVICES</a></li> <li><a href="#portfolio">PORTFOLIO</a></li> <li><a href="#pricing">PRICING</a></li> <li><a href="#contact">CONTACT</a></li> {% if …