Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you return result after entering text in form in django?
As an exercise I'd like to write a web app that returns keyword prediction after user enters content in the form. So, if a user enters some "text" in form, then below the form in, the keyword should appear. I'm thinking that one approach could be using redirect to another view function that produces the prediction model function in view then the returned result would be a revised template. But, I'm not too sure about the following: Could multiple functions be placed in the view under the same url patterns? Is there an if condition that can be applied on the same template holding the form such that if the user submits, then the template shows results? View: def content_to_predict(request): if request.method == "POST": form = InputForm(request.POST) if form.is_valid(): return redirect('show_prediction_result') else: form = InputForm() return render(request, 'prediction/content_input.html', {'form': form}) Template: <h1> Input Content: </h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> -
Should default Debian time zone: 'Etc/UTC be changed?
Should the default Debian time zone: 'Etc/UTC be changed fo all practical purposes including administration or development using Django or other frameworks? -
Django, how do it in template?
{% if request.user??? %} <h2><a href="/games/{{game.id}}/{{game.slug}}/add_rate">Add rate</a></h2> {% else %} <h2><a href="/games/{{game.id}}/{{game.slug}}/add_rate/edit/{{rate.id}}/">Edit rate</a></h2> {% endif %} I want to this : if user have rate for this game display "Edit rate" else " Add rate" How do this? -
py2neo connection refused while docker-compose up
I am trying to run a Django app which connects to neo4j database using py2neo library. Its running fine on my my local machine. But when I am trying to get it docerized using docker-compose I am getting bellow error again and again. This is my docker-compose.yml file version: '2' services: db: image: postgres neo4j: image: neo4j ports: - "7474:7474" - "7687:7687" volumes: - ./db/dbms:/data/dbms web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db - neo4j links: - neo4j Dockerfile: FROM python:3 FROM neo4j:3.1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ ADD startneo.sh /startneo.sh CMD ["/start.sh"] views.py import os import json # Create your views here. from py2neo import Graph, authenticate from bottle import get,run,request,response,static_file graph = Graph(password='neo4j') @get("/") def get_index(): return static_file("index.html", root="static") @get("/graph") def get_graph(self): print("i was here" ) print("graph start") results = graph.run( "MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) " "RETURN m.title as movie, collect(a.name) as cast " "LIMIT {limit}", {"limit": 10}) print("graph run the run") nodes = [] rels = [] i = 0 for movie, cast in results: #print("i am here") nodes.append({"title": movie, "label": "movie"}) target = i i … -
What are the possible ways of extracting text from a news article?
I'm developing a Web app for my school project by implementing Django and NewsAPI so far. The NewsAPI returns me JSON response including the heading, the source URL and a few lines of description for the news while I need full text of article as next step for my detailed view page. So, after a research I found ArticleAPI very useful where I can extract full text of article by just giving the source URL I got from NewsAPI. Yet, since ArticleAPI is neither open-source nor free-to-use, I need another solution. Do you have any suggestions? Thanks in advance. -
django heroku makemigrations ignoring changes in models
I deleted two models from models.py, and when I run makemigrations and migrate locally, everything is fine. When I run makemigrations on Heroku, I get the following message, where Building and BuildingInstance are the models I deleted: Migrations for 'hello': 0002_building_buildinginstance.py: - Create model Building - Create model BuildingInstance When I run migrate, I get: Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I followed the steps here and also tried squashing the migrations locally and on Heroku as suggested here. How can I fix this problem? -
What is the pythonic way of building full urls for links?
I'm looking for a way to build urls in python3 without having to do string concatenation. I get that I can import requests url_endpoint = 'https://www.duckduckgo.com' mydict = {'q': 'whee! Stanford!!!', 'something': 'else'} resp = requests.get(url_endpoint, params=mydict) print(resp.url) # THIS IS EXACTLY WHAT I WANT or from requests import Request, Session s = Session() req = Request('GET', url, params={'q': 'blah'}) print(req.url) # I didn't get this to work, but from the docs # it should build the url without making the call or url = baseurl + "?" + urllib.urlencode(params) I like that the request library intelligently decides to drop ? if it isn't needed, but that code actually makes a full GET request so instead of just building a full text url (which I plan to dump to an html tag). I am using django, but I didn't see anything to help with that in the core library. -
Django deployment best practices
Safaribooksonline.com has a video [1] from Jacob Kaplan-Moss about how to deploy a Django app. This video is from 2010. It refers to a site [2] that has a list of many relevant aspects. Now the workshop mentions things like virtual machines, vagrant (as deployment environments) or Fabric and other tools for deployment automation. I was wondering how much has changed since then. I can think of Docker replacing Vagrant. Or Heroku or AWS instead of renting a dedicated physical server for deployment (or virtual machines). Or using Ansible or Chef / Puppet instead of Capistrano or Fabric. But what else has changed? What is still relevant? What is done differently? What is the state of the art in 2017 for deploying a production ready Django app. Can anybody point me to good blogs / books / tutorials? [1] "Django deployment workshop", https://www.safaribooksonline.com/library/view/django-deployment-workshop/9781449396442/ [2] "infrastructure of modern websites", https://randomfoo.net/2009/01/28/infrastructure-for-modern-web-sites -
How do you nest url mapping in webapp2.WSGIApplication
I'm writing a webapp2 application and am trying to figure out out to nest url mappings. The application is broken up into several packages, and I'd like each package to be able to specify it's own url mappings similar to the way Django does with it's include() directive. Copying from the Django documentation this would look like: urlpatterns = [ # ... snip ... url(r'^community/', include('django_website.aggregator.urls')), url(r'^contact/', include('django_website.contact.urls')), # ... snip ... ] Would this need to be specified in app.yaml, or is there a way to specify the inclusion in webapp2.WSGIApplication([]) -
ValueError: Empty module name when running Python Django Project Locally
I took over this Django project and am trying to get it to run locally. Problem is that whenever I run it locally (python manage.py runserver), I get this error: ValueError: Empty module name Here is the full traceback: /Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/environ/environ.py:579: UserWarning: not reading /Users/pauljurczyk/BandyApp/BandyBack/Bandy-django-new-master/.env - it doesn't exist. warnings.warn("not reading %s - it doesn't exist." % env_file) /Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/environ/environ.py:579: UserWarning: not reading /Users/pauljurczyk/BandyApp/BandyBack/Bandy-django-new-master/.env - it doesn't exist. warnings.warn("not reading %s - it doesn't exist." % env_file) Unhandled exception in thread started by Traceback (most recent call last): File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "bandy/apps/taskapp/init.py", line 1, in from .celery import app as celery_app File "bandy/apps/taskapp/celery.py", line 15, in app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/celery/app/base.py", line 322, in autodiscover_tasks return self._autodiscover_tasks(packages, related_name) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/celery/app/base.py", line 330, in _autodiscover_tasks self.loader.autodiscover_tasks(packages, related_name) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/celery/loaders/base.py", line 252, in autodiscover_tasks related_name) if mod) File "/Users/pauljurczyk/BandyApp/BandyBack/eb-virt/lib/python2.7/site-packages/celery/loaders/base.py", line 273, in autodiscover_tasks return … -
Django Multiple Model Form with Part Radio Buttons
So I have a django app in which I track users and the language(s) they know. Each user can know 0 or more languages. I've managed to create a simple web-app that has CRUD on the table for 'users'. However, when I created my field for users (in views.py): class PeopleForm(ModelForm): class Meta: model = People fields = ['uid', 'utype', 'firstname', 'lastname'] That way in my function based view, I can generate a form with the fields above. However, I also have the other table for language, which has a field for 'uid' and 'Language'. I created a form for that as follows: class LangForm(ModelForm): class Meta: model = Language fields = ['uid', 'lang_speciality'] Now in my current view for creating a new user, I have the following code: def people_create(request, template_name='people/people_form.html'): form = PeopleForm(request.POST or None) if form.is_valid(): form.save() return redirect('people:home') return render(request, template_name, {'form':form}) As you can see, when I create a new person, I just get info about their uid, utype, firstname, and lastname. I also want to be able to include the languages they know in the same view. What is the best way to go about this? One approach I was thinking of implementing would … -
how to get django to return both an HttpResponse AND render a different template
i have a method in views.py that can download a file i've constructed via an HttpResponse['Content-Disposition'] attachment: response = HttpResponse(content_type='text/json') response['Content-Disposition'] = 'attachment; filename="%s"' % (dgjf) response.write(dgjson) this works fine if my the method returns response but, after the download i want to redirect to a confirmation page that i render like this: confirmMsg = render(request,'confirmation.html',context) which i would normally return from the same method. but how can i get the response to do download AND also redirect to the confirmation? -
How to copy django admin change_list functionality to an app?
I want to copy out the object list functionality from the django admin site into my app. Specifically, I have a page that I want to copy the change_list.html or change_list_results.html templates and into my app. I don't want to customize the admin site, I want to use that functionality in my app. For example, how do I create the c1.formset variable that is used these templates in my view, so that I can use the templates in my app? Also, where is that admin code for this? I can't seem to find it. Thanks! T -
Creating Django File from local PNG raises UnicodeDecodeError
I'm working on a Django web app that allows users to upload presentations. The presentation needs to be converted to images, one for each slide, and the images need to be saved to an ImageField as part of a model. However, when I try to save the local image to the model, Django throws a UnicodeDecodeError on the header of the image file. UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I did a little reading, and found that this is part of the valid header for a PNG image file. It seems that for whatever reason, Django is attempting to decode the binary file as unicode. Here's the model I'm attempting to save the image to: class PresentationSlide(models.Model): ... image = models.ImageField(upload_to=upload_to) The upload_to function saves uploaded files with a base64 encoded UUID. In a view, I validate the form, get the presentation file, and use a custom library to convert it to individual images in a temporary directory. The idea then is to create a PresentationSlide instance for each of these images. Below is how I attempt to create the model instances and save the images. presentation = Presentation.objects.create( description=form.cleaned_data['description']) slides = [PresentationSlide.objects.create( … -
Query Django Wagtail Document Model
I have a client that has hundreds of documents that are tagged that we need to query and list on a page. I want to write a TemplateTag so its more reusable, but I have no idea how to query the builtin Wagtail image and document models. The below code is what I am starting with Document.objects.all() added for placement only. Any help would be appreciated. @register.inclusion_tag( 'tags/_document_snippets.html', takes_context=True ) def document_snippets(context): documents = Documents.objects.all() return { 'documents': documents, 'request': context['request'], } -
Django - show result (error) with javascript
I have form, that accepts number between 1-6 and a file. You can see code in my other question: Django-Javascript Modal form validation I have to validate form, without having to reload it as it is modal form and it closes on refresh (or is should open it on refresh, but i don't really like the idea of reloading). So i want the modal to show error, if there is any (wrong file type, model already exists...) How would i achieve this? Somebody suggested me to post form asynchronously and show error with javascript. How would i send javascript message from views in django, without the page having to reload? Could it be done with Json? How? Thank you in advance! -
Django autocomplete light not working for my widget
Hey I'm trying to implement django-autocomplete-light in my django project, but unable to get it to work. I think its a problem with the urls.py file in my app. urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^(?P<playlist_id>[0-9]+)/$', views.detail, name='detail'), url(r'^create_playlist/$', views.create_playlist, name='create_playlist'), url(r'^(?P<playlist_id>[0-9]+)/create_song/$', views.create_song, name='create_song'), url(r'^song-autocomplete/$', SongAutocomplete.as_view(), name='song-autocomplete'), url(r'^(?P<playlist_id>[0-9]+)/delete_song/(?P<song_id>[0-9]+)/$', views.delete_song, name='delete_song'), url(r'^(?P<playlist_id>[0-9]+)/delete_album/$', views.delete_playlist, name='delete_playlist'), url(r'^(?P<playlist_id>[0-9]+)/add_preferences/$', views.add_preferences, name='add_preferences'), ] This is my form. class SongForm(forms.ModelForm): song_title = forms.ModelChoiceField( queryset=Sngs.objects.all(), widget=autocomplete.ModelSelect2(url="login:song-autocomplete") ) class Meta: model = Song fields = ['song_title'] This is the class based view class SongAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Sngs.objects.none() qs = Sngs.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs the widget does not suggest any content and I'm unable to type into it. but when I go to the url of the view it shows me data. also when i change the url like: url(r'^(?P<playlist_id>[0-9]+)/create_song/song-autocomplete/$', SongAutocomplete.as_view(), name='song-autocomplete'), It gives me an error: Reverse for 'song-autocomplete' with no arguments not found. 1 pattern(s) tried: ['login/(?P<playlist_id>[0-9]+)/create_song/song-autocomplete/$'] I'm new to Django and still learning so help would be highly appreciated. Thank you. -
What kind of widget to use?
I am new in Django and want to know how create next thing: 1) As you can see from the picture I have form with 3 field. 2) First field must be select widget but in the same time all fields must be editable as normal CharField. 3) When user select lets say 'Manager' in first field I want to load other information to fields. TABLE: (What kind of array I need to use?) "Manager" - "M" - 'Manager is the person...' "Developer" - "DEV" - 'Developer is the person...' "ADMIN" - "AD" - 'ADMIN is the person...' "Analist" - "AN" - 'Analist is the person...' modals.py: class Characteristic(models.Model): class = models.CharField(_('Class'), max_length=250) symbol = models.CharField(_('Symbol'), max_length=250) description = models.TextField(_('Description')) -
csrftoken tag not working after upgrade to Django 1.11
I have inherited a Django app that I initially got working on Django 1.9. Recently I have migrated it to Django 1.11 and Python 3.4 (from 2.7). Since then, some admin view that I have has started failing with a 403 Forbidden error, CSRF verification failed. I looked at the documentation, and checked the following things: I'm still using MIDDLEWARE_CLASSES, but django.middleware.csrf.CsrfViewMiddleware is included in my configuration (it's second, after SessionMiddleware and CommonMiddleware). The template used includes the {% csrf_token %} stuff. The view uses render_to_response(), and passes RequestContext(request) as the third argument to it. (None of these changed during or after the Django/Python upgrades, as far as I know.) I'm not that experienced with Django, although I have quite a bit of Python web programming experience. What am I missing/how could I debug further? -
Handling many request simultaneously in Python/Django
I have been asked this question many time but may be i didn't get the exact answer of this. SO let say we have one file, which has got the (read,write) access to all the user. when one user try to access this file and doing some modification in it , same time another user will try to access it and will delete some of the details from it. So how we can handle this that both the user should be allow to access or make the changes simultaneously in the file and changes from both the user should be present there. Multi threading is one concept but as i am aware python is not with multi threading . Then how we can write to resolve such issue ?? Thanks in advance Anendra -
'HttpResponseForbidden' object has no attribute
I'm trying to create an api for our users. I've decided to use Django-rest-framework. Users need only GET requests. Each GET request has to have 'token' attribute to determine which data should we return. So I've created a function which tries to get user object from request object. def get_user(request): token = request.GET.get('token') if not token: return HttpResponseForbidden() user = get_object_or_404(User,auth_token=token) return user I want to use this function in my view: @api_view(['GET']) def products(request): user = get_user(request) products = user.products.all() serializer = ProductSerializer(products, many=True) return JsonResponse(serializer.data, safe=False) The problem is that when I doesn't provide token attribute, it raises: AttributeError at /api/products/ Exception Value: 'HttpResponseForbidden' object has no attribute 'products' Instead of proper response. I can do: @api_view(['GET']) def products(request): user_or_response = get_user(request) if user_or_response.__class__ != User: return _or_response products = _or_response.products.all() serializer = ProductSerializer(products, many=True) return JsonResponse(serializer.data, safe=False) As you can see, it doesn't automatically return forbidden response, instead, it returns it as user. I can return it in products view but maybe there is a better way to do this with Django-rest-framework. What should I do? Do you have a better approach or any advice? -
Getting { "detail": "Method \"POST\" not allowed." } from ModelViewSet in DRF
Hi I'm trying to send POST request to create_mole() method, but I get { "detail": "Method \"POST\" not allowed." } Tokens are correct views.py class MoleViewSet(ModelViewSet): queryset = Mole.objects.all() permission_classes = [AllowAny] def get_serializer_class(self): if self.request.method in SAFE_METHODS: return MoleReadSerializer return MoleWriteSerializer def get_queryset(self): if self.request.method in SAFE_METHODS: return self.queryset.filter(owner=self.request.user.id) return self.queryset def create(self, request, format=None,*args, **kwargs): print(allowed_methods(self)) return Response(request.data,status=200) @parser_classes((FormParser, MultiPartParser)) def create_mole(self, request,*args,**kwargs): owner = request.user.id serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.data['owner'] = owner serializer.data['malignant'] = 13 serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) urls.py from channels.routing import route from rest_framework.routers import DefaultRouter from .views import MoleViewSet router = DefaultRouter() router.register(r'moles', MoleViewSet, base_name='moles') models.py class Mole(models.Model): class Type: UNDEFINED = 0 BENIGN = 1 MALIGNANT = 2 title = models.CharField(max_length=42, null=True) owner = models.ForeignKey(to=Person, related_name='moles', null=True) image = models.ImageField(upload_to=get_image_path, ) malignant = models.IntegerField(null=True) body_part = models.ForeignKey(BodyPart, related_name='moles', null=True) date = models.DateField(auto_now_add=True, null=True) ModelViewSet's create() method sends the same error ............................................. -
Pass data from template to view in Django
I'm building a bus reservation website using Django. After user searches buses on a specific route, a list is displayed showing available buses. Each list item i.e. bus has a book button which leads to new page called 'seats.html'. I want to pass the bus number and other information to the view of 'seats' so that I can display the number of seats available and javascript can also use this info. Here is my code views.py def find_bus(request): form = forms.FormFindBus template = 'home.html' context = {'form': form} return render(request, template, context) def select(request): bus_type = request.GET.get('bus_type') bus_from = request.GET.get('bus_from') bus_to = request.GET.get('bus_to') date_string = request.GET.get('date') qs = Bus.objects.filter(type_of_bus=bus_type, route__location_from=bus_from, route__location_to=bus_to, date=date_string) context = {'qs': qs,} template = 'select.html' return render(request, template, context) def seats(request): template = 'seats.html' context = {} return render(request, template, context) select.html {% for info in qs %} <a href="{% url 'book:seats' %}">Book</a> <ul> <li><b>Bus Number -</b> {{ info.bus_number }}</li> <li><b>Route -</b> {{ info.route }}</li> <li><b>Date -</b> {{ info.date }}</li> <li><b>Time -</b>{{ info.time }}</li> </ul> </div> {% endfor %} As you can see query set gets passed in select.html where I use for loop to display all the buses available along with their information. I then … -
Developing a Podcast Website
I recently got a client who is looking to have a website built with the main purpose of it being an audio podcast. As I get ready to start planning and building this site I wanted to check what are the best options for building a podcast site? A lot of the Q/As I found on stackoverflow were from 2009 so I feel a lot has changed since then. Does anyone have experience in the recent past developing a podcast site? What are the best options for CMS or other system? So some of the info of needs for the podcast site are it will be weekly updated with a podcast and an accompanying blog post/description and that is really about it. Maybe some kind of sign in option for comments if that function is available as it is on WP. That's about it. If you need any other info I will gladly provide it. Thanks for the help! -
When preparing to upgrade Django is there an upgrade check?
Is there an easy way it identify potential issues when upgrading Django? What features have been deprecated? What 3rd party libraries have compatibility issues? I know there are release notes with some of this information. I'm upgrading several sites and several different version at the same time.