Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render django page view for request methods
I have a view function, which is called for every page request however I want it to render pages with a certain dict value based on request(method). The below code will reach with if state and but doesn't render with name instead goes to else statement and renders without name. def index(request): ip = get_client_ip(request) csrf_token = get_token(request) if request.method == 'POST': return render(request, 'page.html', {'csrf_token':csrf_token, 'name': request.POST.get('the_post'),}) else: return render(request, 'page.html', {'csrf_token':csrf_token, 'name': 'Welcome, Anonymous',}) The post request is sent by an ajax call and on success url is replaced. Do I need to furnish more information. -
how to get the first in the list in django?
I have read through some threads which all talked about using something like x[o] for x in xs something that like would return first of each list but somehow I just couldn't make it though though...can someone give me a hand? this is my code for project in projects_obj: project_image_objs = ProjectImage.objects.filter(project=project) if project_image_objs: print(project_image_objs) this is what showed in console [<ProjectImage: M5>] [<ProjectImage: Image upload test>, <ProjectImage: Image upload test>] [<ProjectImage: Image upload test>, <ProjectImage: Image upload test>] [<ProjectImage: M8>] [<ProjectImage: M8>] I only need to return one one of each. so what I want to get in return should be something like [<ProjectImage: M5>] [<ProjectImage: Image upload test> [<ProjectImage: Image upload test> [<ProjectImage: M8>] so then I can call each property of the object then append it somehwere but I keep on getting error trying this. Thanks in advance for any help -
download generated html file with django
I have some html format text data in a database table(which is max. 10 rows). I have to create download links for each row using django. When user click the generated link, selected text in the table will be downloaded as an html file by user. How can I do it in django? In what way should I set up the view and http response of that view? When user click the link, page should not change or redirect. Only generated html file from database will be downloaded. -
How to connect a django project to a simple storage service
I want to connect my django project to a simple storage service (for example Amazon S3). How should I configure my settings.py? -
How to execute python code when POST request is sent to API end-point of DjangoRestFramework?
I am new to djangorestframework and developing a simple voting application. I have integrated this application for REST based user authentication: https://github.com/sunscrapers/djoser And this for voting: https://github.com/shanbay/django-vote This is what I want to execute every time an authenticated user makes a POST request to host/api/voteup endpoint with candidate_name: from django.contrib.auth.models import User from Elections.models import Election_party userpk = User.objects.get(username='username').pk candidate = Election_party.objects.get(candidate_name='candidatename') candidate.votes.up(userpk) #from applicatioin django-vote 'username' or 'token' will be accepted along with candidate_name through POST method, vote count will be increased and a HTTP200 response will be sent back to the user. How do I define an API for this functionality in views.py ? Thanks in advance. -
UnboundLocalError at /create_playlist/ local variable 'playlist' referenced before assignment
Here is my views.py : def create_playlist(request): form = PlaylistForm(request.POST or None) if form.is_valid(): playlist = form.save(commit=False) playlist.name = request.name context={ 'playlist':playlist, 'name':playlist_name, } return render(request, 'create_playlist.html', context) playlist.save() context = { "form": form, } return render(request, 'create_playlist.html', {'form': form,}) I have a model of Playlist and forms.py which contains all the fields of the Playlist model.I want users to be able to create their own playlist and for that I made this but when I compile it, it gives my this error: UnboundLocalError at /create_playlist/ local variable 'playlist' referenced before assignment Request Method: GET Request URL: http://localhost:8000/create_playlist/ Django Version: 1.9.6 Exception Type: UnboundLocalError Exception Value: local variable 'playlist' referenced before assignment Thankyou ;) -
pipeline-browserify TypeError: can only concatenate list (not "str") to list
I'm trying to set up django-pipeline with browserify. I started off working from a tutorial located here, but I had to dig through a few more sources to get where I am now. My issue is that when I run collectstatic, I get a typeerror from the browserify compiler. In this project, I have two stylesheets and one js file. The error occurs after the first stylesheet has been compiled and compressed correctly. Removing the second file from the project does not stop the error, and the first is still processed successfully. I have verified that all of my static files settings are correctly configured and working, that the program is able to access all the necessary binaries (browserify, uglify, etc.) through the path, and that all the brackets and commas are in the right place. I've also experimented with different compressors, noopcompressors, etc., but nothing gets me past this. Any advice would be greatly appreciated. Here's the full traceback: Post-processed 'css/stylesheet1.css' as 'css/stylesheet1.css' Post-processed 'css/stylesheet2.css' as 'css/stylesheet2.css' Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\env_project\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\env_project\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\env_project\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv … -
Django AttributeError: 'getfullargspec' object has no attribute 'default'
I teared down Django-oscar for practice and rebuild it not in capacity of a plugin app but as Django project. Now I am having this issue but couldn't figure out what it is related to exactly. Can someone help me to resolve this? Following is the error I am getting: When I run command "python manage.py shell" I get this error. (supermarket) C:\Users\shazia\supermarket\market>python manage.py shell Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\_ _init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\_ _init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\b ase.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\b ase.py", line 445, in execute output = self.handle(*args, **options) File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\c ommands\shell.py", line 69, in handle self.run_shell(shell=options['interface']) File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\c ommands\shell.py", line 58, in run_shell return getattr(self, shell)() File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\c ommands\shell.py", line 41, in ipython ip() File "C:\Users\shazia\supermarket\lib\site-packages\django\core\management\c ommands\shell.py", line 34, in _ipython from IPython import start_ipython File "C:\Users\shazia\supermarket\lib\site-packages\IPython\__init__.py", li ne 47, in <module> from .core.application import Application File "C:\Users\shazia\supermarket\lib\site-packages\IPython\core\application .py", line 22, in <module> from traitlets.config.application import Application, catch_config_error File "C:\Users\shazia\supermarket\lib\site-packages\traitlets\config\__init_ _.py", line 6, in <module> from .application import * File "C:\Users\shazia\supermarket\lib\site-packages\traitlets\config\applica tion.py", line 120, in <module> class Application(SingletonConfigurable): File "C:\Users\shazia\supermarket\lib\site-packages\traitlets\config\applica tion.py", line 291, in Application … -
In django channels how to access the consumed messages from consumers.py in views.py?
I am just getting started with django channels. I want to pull out a batch of messages from a specific channel and display it in a web page. After the page is reloaded, next batch should be pulled out from the channel and displayed. As far as I saw the documentation, the consumers should be inside the consumers.py script. How to access the messages from a consumer inside views.py so that I can render them and display the messages in a web page? -
Can I use rtsp in Django?
I would like to import an image from rtsp from an html document. I do not know what to do. I'm going to use opencv. I'm going to check on the video coming in from Python and apply it to Django. class Video(): def __init__*self): cap = cv2.VideoCapture("rtsp://400.mp4") def get_frame(self): success, frame = cap.read() ret, jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() http://www.chioka.in/python-live-video-streaming-example/ I created the above function by referring to the above site. I do not know how to apply this image to the template May I ask for your advice? Thank you -
Django Python How I can passing binary tree content specifically with level and data from View to Template?
this my code html to show data in template from View.py thanks before PLEASE HELP ME -
How to use gitlab for sso in Django rest?
I'm trying to use gitlab login with my Django rest application. But not able to get any starting point. So can anyone please help me out with this? -
A django-table in which table attributes must be with respect to their category and details must be in with respect to detail attributes
I am creating a institute details site where anyone can specify his/her own institute's details. The conditions I am in concussion with are that: 1)Every institute should have a category to group themselves in and their category must decide their details (in form of tabs). Example: Category: engineering, Tabs: terms and conditions:, departments:, blocks:, Category: Medical, Tabs: departments:, labs:, ). 2) Under each college detail page, tab name may contain the table of each college separately, (The table should be Like in College's branch tab, the table must be in form like: Tab: Branch, TR1: Branch1 name, Branch1 code, Branch1 facilities available, TR2: Branch2 name, Branch2 code, Branch2 facilities available, ). The problem I faced doing this was these details( branch name, Branch code) were not exactly aligned under their respective attributes and if details are more than 1, the look of the entire table was entirely different. So, their should be only 1 attribute name should be shown under each and must be arranged branch wise. 3) Similarly, their different tables should be aligned under the different tabs with respect to each college. -
retrieve multiple values from Dropdown menu in Django
i have a form well rendered in my template with a dropdown menu and a save button, when i choose an item from the dropdown menu and click save i pass to the views.py the url for that item, like this: <select name="listxblocks"> {% for scname, desc in scenarios %} <option value="{% url "workbench_show_scenario" scname %}">{{desc}}/{{scname}}</option> {% endfor %} </select> now, in the views.py file i can retrieve the selected item and it's value, if request.method == "POST": #checks if the request is a POST operation url = request.POST['listxblocks'] but i want also to retrieve the name scname and the description desc i tried with hidden field but it made my template messy, how can i do that -
Any suggestion for Django-FloppyFroms client side validation
Here are few links for Django FloppyForms. https://pypi.python.org/pypi/django-floppyforms I would like to use frontend/client side validation for my froms. I am using Django and semantic UI for my project. -
Django Static Files on Google Cloud Storage
I coppied google cloud sample django project for google appengine. Then, I modified settings.py for storing all static files on google storage. I added this settings DEFAULT_FILE_STORAGE = 'storages.backends.gs.GSBotoStorage' GS_ACCESS_KEY_ID = 'YourID' GS_SECRET_ACCESS_KEY = 'YourKEY' GS_BUCKET_NAME = 'YourBucket' STATICFILES_STORAGE = 'storages.backends.gs.GSBotoStorage' On local machine everything is perfetcly works but, when i deploy it to google appengine, static file problem appers.This is the error message: ImportError at /admin/login/ cannot import name SpooledTemporaryFile in app.yaml file settings about static files: handlers: - url: /static static_dir: static/ - url: .* script: mysite.wsgi.application I am new at google cloud and i can't figure it out where i am doing wrong. -
New users automatically following all users
So I'm building a fake social network for a project in django and I've implemented allowing users to 'follow' others they choose to follow(or technically none at all if they choose). But so far every time I create a user that user automatically 'follows' all the other users in the database and I do not fix this. Here is the model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') bio = models.CharField(max_length=200, blank=True) followers = models.ManyToManyField('Profile', related_name="followers_profile", blank=True, symmetrical=False) following = models.ManyToManyField('Profile', related_name="following_profile", blank=True, symmetrical=False) avatar_thumbnail = ProcessedImageField(upload_to='profile_images', processors=[ResizeToFill(320, 320)], format='JPEG', options={'quality': 40}, blank=True) feed_type = models.CharField(max_length=8, choices=GENDER_CHOICES, default='Both') # @receiver(post_save, sender=User) # def create_user_profile(sender, instance, created, **kwargs): # if created: # Profile.objects.create(user=instance) # # @receiver(post_save, sender=User) # def save_user_profile(sender, instance, **kwargs): # instance.profile.save() def get_number_of_followers(self): if self.followers.count(): return self.followers.count() else: return 0 def get_number_of_following(self): if self.following.count(): return self.following.count() else: return 0 def __str__(self): return self.user.username Here is the View that constructs User and Profiles and the form that process user creation data def signup(request): form = UserCreateForm() if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): form.save() user = User.objects.get(username=request.POST['username']) user_profile = Profile(user=user) user_profile.save() new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) login(request,new_user) return redirect('index') return render(request, 'userapp/signup.html', { 'form': form }) Here's the … -
Django 1.10 Count on Models ForeignKey
I guess this must be simple, but I've been trying for hours and can't find anything to help. I have 2 models. One for a Template Categories and another for a Template I'm listing the Template Categories on the Homepage and for each Category I want to show how many templates have that category as a Foreign Key. My code is as follows: Models.py class TemplateType(models.Model): type_title = models.CharField(max_length=60) type_description = models.TextField() file_count = models.ForeignKey('TemplateFile') def __str__(self): return self.type_title def get_absolute_url(self): return "/templates/%s/" %(self.id) class TemplateFile(models.Model): template_type = models.ForeignKey(TemplateType, on_delete=models.DO_NOTHING) template_file_title = models.CharField(max_length=120) template_file_description = models.TextField() def __str__(self): return self.template_file_title Views.py from django.shortcuts import HttpResponse from django.shortcuts import render, get_object_or_404 from django.db.models import Count from .models import TemplateType from .models import TemplateFile def home(request): queryset = TemplateType.objects.all().order_by('type_title').annotate(Count('file_count')) context = { "object_list": queryset, "title": "Home", } return render(request, "index.html", context) index.html <div class="row"> {% for obj in object_list %} <div class="template_type col-md-6"> <a href="{{ obj.get_absolute_url }}"> <h4>{{ obj.type_title }}</h4> </a> <p>{{ obj.type_short_description }}</p> <button class="btn btn-primary" type="button">Templates <span class="badge">{{ obj.file_count__count }}</span></button> </div> {% endfor %} </div> Can somebody help please? -
How to add gen.Task module in Tornado webserver running for django backend to allow multiple asynchronous requests
I am trying for the first time to deploy a django website on a microsoft webserver in service mode (without being logged in) using nssm. To do so, it seems I can't use the usual python manage.py runserver 0.0.0.0 So I have tried to add a new tornado.py file in my project and the nssm would point to it: from tornado.wsgi import WSGIContainer from tornado.ioloop import IOLoop from tornado.web import FallbackHandler, RequestHandler, Application, StaticFileHandler from wsgi import application from mySite.settings import * class MainHandler(RequestHandler): def get(self): self.write("Hi Tornado") tr = WSGIContainer(application) app = Application([ (r"/tornado", MainHandler), (r"/static/(.*)", StaticFileHandler, {'path': STATIC_ROOT}), (r"/media/(.*)", StaticFileHandler, {'path': MEDIA_ROOT}), (r".*", FallbackHandler, dict(tr)), ]) if __name__ == '__main__': app.listen(8000) IOLoop.instance().start() The nssm pointing to this file makes the deployment okay, but unfortunately, I have some long requests calling other APIs in the back-end django and when I call one of these long services, it is impossible to make an other request i.e I have to wait for the first request to be finished. From what I have seen on other questions related to the same issue on this website, I need to add the tornado decorator below someway: @gen I have tried a couple of options … -
Django 500 Error when DEBUG=FALSE, but only on some pages
I am stuck. When I set my DEBUG=False, I get a 500 error, but only when I click the tab going to another app on the navbar of my index.html. Here is my settings.py: """ Django settings for Tanta project. Generated by 'django-admin startproject' using Django 1.10.6. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_dir=os.path.join(BASE_DIR,"templates") STATIC_DIR=os.path.join(BASE_DIR,"static") MEDIA_DIR=os.path.join(BASE_DIR,'media') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' COMMUNITY_DIR=os.path.join(BASE_DIR,"community/templates/community") WALLET_DIR=os.path.join(BASE_DIR,"wallet/templates/wallet") WALLET_STATIC=os.path.join(BASE_DIR,"wallet/static") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '******************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # CSRF_COOKIE_SECURE=True # SESSION_COOKIE_SECURE=True # SECURE_HSTS_SECONDS=30 # SECURE_CONTENT_TYPE_NOSNIFF=True # SECURE_BROWSER_XSS_FILTER=True # X_FRAME_OPTIONS='DENY' ALLOWED_HOSTS = ["get-onyx.herokuapp.com",'localhost'] # CELERY STUFF CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home_page', 'dashboard', 'community', 'wallet', 'actstream', 'django_celery_results' ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ACTSTREAM_SETTINGS ={ 'MANAGER': … -
Create a special tuple with queryset and loop condition
I executed some commands in the Django's interactive shell. I got In [12]: Perception.objects.all() Out[12]: <QuerySet [<Perception: Perception #0000001>, <Perception: Perception #0000002>, <Perception: Perception #0000003>, <Perception: Perception #0000004>, <Perception: Perception #0000005>, <Perception: Perception #0000006>]> In [13]: perception1 = Perception.objects.get(pk=1) In [14]: perception1.loan.request.customer.user.last_name Out[14]: u'Kshlerin' In [15]: perception1.loan.request.customer.user.first_name Out[15]: u'Dwight' From this information, I would like to create a tuple. For instance, (('fullname1', _('Full name 1')), ..., ('fullnamen', _('Full name n'))) where fullname = Fullname = first_name + last_name and _ is just related to from django.utils.translation import ugettext_lazy as _ Could anyone have an idea how I could do such thing? Thanks! P.S. Please tell me if the question is unclear. In [19]: Perception.objects.values("loan__request__customer__user__first_name", ...: "loan__request__customer__user__last_name").distinct() Out[19]: <QuerySet [{'loan__request__customer__user__first_name': u'Jennyfer', 'loan__request__customer__user__last_name': u'Hauck'}, {'loan__request__customer__user__first_name': u'Dwight', 'loan__request__customer__user__last_name': u'Kshlerin'}, {'loan__request__customer__user__first_name': u'Keshaun', 'loan__request__customer__user__last_name': u'Boyer'}]> -
How to deploy a Django project using Digital Ocean
I followed the tutorial from Digital Ocean https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 on how to set up a virtual private server with Django with PostgresSQL, NGINX, and Gunicorn, and it worked perfectly. The IP address for my website gives me a thank you page for using Nginx. However, after I placed my actual Django project files on the server, I am unsure of how to actually serve the Django application. Can somebody point me in the right direction? -
Django-fsm - How can I get source state in transition?
How can I get the source state in transition method ? I want to validate transition IF source state is EXCLUDE for example @transition(field=status, source='*', target=ProjectStatus.ACTIVE.value) def activate(self): #get source transition for validations Thanks ! -
error in attempt to use tasks.py in django celery
I try to do something very basic with celery and django. Specifically in my app in tasks.py: from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery( broker='redis://localhost:6379/0') @app.task def add(x, y): return x + y and in views.py of this app: from .tasks import * def index(request): add.delay(4, 4) return HttpResponse("you are in index") when I start running celery and go to index the celery process raises the error. I run: celery -A tasks worker and the error is: [2017-04-14 00:53:12,404: ERROR/MainProcess] Received unregistered task of type 'rango.tasks.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports?' what do I do wrong? -
Django - Image doesn't load when using pdf view
I am using django-easy-pdf and I have the following view: class PrescriptionView(PDFTemplateView): template_name = 'meds/prescription.html' context_object_name = 'meds' model = Medicament def get_queryset(self): ids = map(int, self.kwargs['selected'].split(",")) return Medicament.objects.filter(id__in=ids) def get_context_data(self, **kwargs): context = super(PrescriptionView, self).get_context_data(pagesize="A5", title="Ordonnance", **kwargs) return context And I have the following html page: {% load staticfiles %} <html> <head> <meta charset="UTF-8"> <style> @page { size: A5; @frame headerLogo { top: 23mm; left: 20mm; width: 50mm; height: 24mm; -pdf-frame-content: headerLogo; } } </style> </head> <body> <div id="headerLogo"> <img src="{% static 'img/banner.png' %}"> </div> </body> But the banner.png image doesn't load and I keep getting the following error: missing explicit frame definition for content or just static frames getFile '/static/img/banner.png' None '/home/nids/cabin' '<div id="headerLogo"> <img src="/static/img/banner.png"/> </div>' Traceback (most recent call last): File "/home/nids/cabin/dentist/lib/python3.5/site-packages/xhtml2pdf/context.py", line 828, in _getFileDeprecated nv = self.pathCallback(name, relative) File "/home/nids/cabin/dentist/lib/python3.5/site-packages/easy_pdf/rendering.py", line 35, in fetch_resources path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, "")) File "/home/nids/cabin/dentist/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/home/nids/cabin/dentist/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'NoneType' Need a valid file name! '<img src="/static/img/banner.png"/>' line 0, msg: missing explicit frame definition for content or just static frames, fragment: line 0, msg: getFile %r …