Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch: Unable to pass parameter from template to view.
I am trying to create a simple search form in Django. Here is what I have so far: form: <form action="{% url 'search_pub' pub_name=pub_name %}" method="get"> Publication name: <input type="text" id="pub_name" name="pub_name" value="herald"> <input type="submit" value="Search"> </form> urls.py url(r'^search/$', views.search, name='search'), url(r'^results/(?P<pub_name>[\w]+)/$', views.search_pub, name='search_pub'), views.py def search(request): return render(request, 'urlapp/search.html') def search_pub(request, pub_name): pubs = Publication.objects.all().filter(title__icontains=pub_name) return render(request, 'app/results.html', { 'publications': pubs }) models.py class Publication(models.Model): title = models.CharField(max_length=30) I get the following error when I open the search page at http://localhost:8000/search/: NoReverseMatch at /search/ Reverse for 'search_pub' with keyword arguments '{'pub_name': ''}' not found. 1 pattern(s) tried: ['results/(?P<pub_name>[\\w]+)/$'] I verified that the regex is valid using the site pythex. If I go to the URL: http://localhost:8000/results/herald, I get the correct results. What am I missing? -
Django logging requests
I'm using django 1.11 in aws elastic beanstalk and i've been tryinf to get my app to log with no luck... i have these in my settings.py LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/opt/python/current/app/staging.log', }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } import logging.config logging.config.dictConfig(LOGGING) then I try to call one of my API and expecting something would show up in the log but it didn't. I django.request logger supposed to automatically log all incoming request or do i have to create a middleware that does logger.debug('something')? logging in django is a lot more complicated than i tought :( -
AttributeError: 'file' object has no attribute '_committed' . Renaming image django models
I am downloading images by links using requests and saving them to the model f = open('00000001.jpg','wb') f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content) event.image = f f.close() Error on event.save() happens: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/base.py", line 734, in save force_update=force_update, update_fields=update_fields) File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/base.py", line 762, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/base.py", line 824, in _save_table for f in non_pks] File "/Users/TheKotik/tick-tock2/denv/lib/python2.7/site-packages/django/db/models/fields/files.py", line 312, in pre_save if file and not file._committed: AttributeError: 'file' object has no attribute '_committed' Googled for a while, and understood that something is just likely wrong with the method of naming images with id instead, but can't really understand what's exactly wrong and why def get_image_path(instance, filename): return 'event_img/{0}'.format(instance.event.id) class Event(models.Model): image = models.ImageField(upload_to=get_image_path) -
Django templates tag
I have a views.py returns a values as follows: [{'host_id': 1, 'count': 8}, {'host_id': 3, 'count': 1}, {'host_id': 5, 'count': 3}] how to use {% for %} ... {% endfor %} ... {% else %} tag on html? If the end of the for loop does not match the value, a default value of 0 is set <tr> <td> {% for i in count_result %} {% if i.host_id == request.session.user.hid %} {{ i.count }} {% endif %} {% endfor %} {% else %} 0 </td> </tr> Thanks! -
Hosting a web app on a cloud outside of a company's IT infrastructure - security concerns.
I am a CS student and my internship offer depends on how I address this, so please bear with me. Scenario: A huge company "ABC" has its own IT infrastructure and ERP. In one department, however, there is still a lot of manual paper work and I am creating a web-app that would address this problem. The web-app is built in python and django with MySQL as a backend database. Everybody loves the idea BUT: 1) There is a big security issue as the company "ABC" is concerned with the web-app being hosted on the cloud and the database being exposed to threats. How do I address that? Is there a way to host my web-app on a company's server? How do companies create apps to address their needs and build security around it? 2) The department is concerned with who is going to maintain the web-app after I leave? Apart from documenting my work, what else could be done? Where should I look into to conceptually understand all this? Would greatly appreciate any help! -
Django 1.11 : templates extending
Today I've encountered a weird thing. in my site i used a main.html template as a base template for the others today when I've maid some changes in it, the changes were not rendered but the old version kept showing up. so i created another file containing the new changes called "base.html" and replaced the main.html with base.html in the other templates and it worked. can someone explain to me the phenomenon? is there a way to not create a new file for each change? -
how to disable a button which acts as a link django
What is the best way to disable the "deny" button when "approve" button is clicked ? I have {{some}} that stores the value of approve or deny value. <a href="{% url 'hrfinance:edit' id=item.id status='a' %}"><button>Approve</button></a> <a href="{% url 'hrfinance:edit' id=item.id status='d' %}"><button>Deny</button></a> -
Best approach to using Django in front of a queue-based Python application
I'm new to Django, but not Python. I've been reading over the Django docs but I'm not finding what I'm looking for. I have a Python application that takes a report and then creates and configures a virtual machine based on that report. This is tied to a fairly dumb queue system - basically a user adds a report to an input queue, and then the application has one thread that will take items from the queue and then formats the data into a more usable form. Another thread then takes this formatted object and connects to the virtual platform and creates a VM to match that object's specifications. These threads are started from a start() method and reports are added with a add_report() method. E.G. at its most basic, this will get me a VM: from myapp import vmcreator creator = vmcreator() creator.start() creator.add_report(path_to_report) That all works fine. What I am wanting to do now is put a webui in front of it, and I'm looking at Django for that. What would be the proper way to call creator.start() when Django starts the webserver so that the worker threads start as well? Further, what would the right approach to … -
DRF Serialize fields from both directions of foreign key?
Let's say I have three models: class ThingOne: field1 = ... field2 = ... class ThingTwo: thingone = models.ForeignKey("ThingOne") field3 = ... field4 = ... class ThingTree: thingtwo = models.ForeignKey("ThingTwo") field5 = ... field6 = ... Let's also say I've made top level ViewSets and Serializers for the above. Easy peasy. Now I'd like to create a custom endpoint (detail_route) that is based on a subset of ThingTwo and includes corresponding fields from ThingOne and ThingThree. I'll use a custom serializer to pack my data: class MyComboThingSerializer(ModelSerializer): field1 = serializers.SerializerMethodField() field5 = serializers.SerializerMethodField() def get_field1(self, obj): return ? def get_field5(self, obj): return ? class Meta: model = ThingTwo fields = "__all__" What would I put into either return statement to achieve the values I'm looking for? -
Kubernetest deployed on GKE
I followed the tutorial here https://cloud.google.com/python/django/container-engine#initialize_your_cloud_sql_instance I have successfully deployed my service but the tutorial stops before getting to updating the deployment. What I've tried to do is this. But it doesn't seem to actually update the pods or deploy the code. docker build -t gcr.io/<my-app>/polls . gcloud docker -- push gcr.io/<my-app>/polls kubectl apply -f polls.yaml -
dictionary error update sequence length - django
I am getting the following error. So I have a django project and I am trying to send a api call and print out the response of the api call in an html template. When I send the request, within the terminal, it prints a response 200 which means that the request was good. I am then passing in the response into a template in order to display the repsonse that was gathered. Does anyone know how to properly display a json response into a html file. ValueError at /signup dictionary update sequence element #0 has length 8; 2 is required Request Method: POST Request URL: http://127.0.0.1:8000/signup Django Version: 1.8.6 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 8; 2 is required Exception Location: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\context.py in __init__, line 20 Python Executable: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Thu, 31 Aug 2017 01:07:06 +0000+ I am going to attach my view and html template that I have right now to display the json response in an html file... Here is the views.py def createUserSynapse(request): url = 'http://uat-api.synapsefi.com' headers = { 'X-SP-GATEWAY' : 'client_id_asdfeavea561va9685e1gre5ara|client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv', 'X-SP-USER-IP' : '127.0.0.1', 'X-SP-USER' : 'ge85a41v8e16v1a618gea164g65', … -
Why are Django REST API decorators breaking the Django non_atomic_requests decorator?
I have a Python Django REST API view like this: from rest_framework.decorators import api_view, permission_classes from django.db import transaction @api_view( [ 'POST' ] ) @permission_classes( ( IsAuthenticated, ) ) @transaction.non_atomic_requests def myview( request ): with transaction.atomic(): db_do_something1() with transaction.atomic(): do_do_something2() return some_response The SQL actually run against my PostgreSQL database in this case creates savepoints before and after db_do_something1 and 2 - but critically does not commit after leaving the with blocks. The entire view is still wrapped within a BEING and COMMIT is only issued to the database at the end of the view. If I move the @transaction.non_atomic_requests decorator to the beginning of the decorator list, then I get the correct behavior, with each with block being in its own transaction and committing at the end. What is going on here? -
Limit filling out a form for an instance of User to once a day (Django)
I'm working on this web app that let people sign in, and be able to create: users, create beers and reviews for the different types of beers. This is my models.py for creating a beer: from django.db import models from django.conf import settings # Models User = settings.AUTH_USER_MODEL class BeerModel(models.Model): user = models.ForeignKey(User, default=1) name = models.CharField(max_length=254, default="") style = models.CharField(max_length=254, default="") ibu = models.IntegerField(default="") calories = models.IntegerField(default="") abv = models.IntegerField(default="") location = models.CharField(max_length=254, default="") class Meta: verbose_name_plural = 'Beers' def __str__(self): return self.name def avg(self): return This is my forms.py: from django import forms from django.contrib.auth.models import User from .models import BeerModel, RateModel # Forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password') help_texts = { 'username': None, } class NewBeerForm(forms.ModelForm): name = forms.CharField(label="Beer Name") ibu = forms.IntegerField(label="IBU") abv = forms.IntegerField(label="ABV") location = forms.CharField(label="Brewery Location") class Meta: model = BeerModel fields = '__all__' And this is my views.py: @login_required def new_beer(request): if request.method == "POST": beer = NewBeerForm(request.POST) if beer.is_valid(): beer.save(commit=True) return HttpResponseRedirect(reverse('beer_tracker:home')) else: beer = NewBeerForm() return render(request, 'beer_tracker/new_beer.html', {'beer':beer}) As you can see, to create a beer, you need to fill out a couple of details including the "User" field. … -
Add checkbox and delete actions to customized Django admin change_list
I've been customizing Django's change_list.html following this tutorial. My question concerns something that wasn't covered in that tutorial: How to easily add the checkbox and the actions (delete selected items)? I took a look in the templatetags of the admin section (mainly here, but I couldn't understand how to easily add the delete action to each item in a customized change_list.html template and what should be added to the ModelAdmin class). -
Can python social auth work for both web and rest in the same Django app?
I have an Strava API application that's been web based for ~6 months. Working to build an iOS UI for it and as a result I'm now seeking to serve JSON via the djangorestframework. Questions on this at the present: Can I serve both web and api views from a single application or do I need to create a new web app for the REST api app? Can I use python social auth for the rest_framework views without adding a library like django-rest-framework-social-oauth2? Once I clear this hurdle I have a few other questions about django-rest-framework-social-oauth2 if it's required to authenticate REST apps via Django. My experience so far is I get 302 back from every request made outside of a browser session (e.g. p_OAuth2 from iOS or curl from OSX) no matter what configuration I've tried:( Thanks in advance for any suggestions. Mike -
Passing Data from Django View to Angular
Is this possible without using a REST API? I have a context in my Django view in which I place a variable after making a call to the database and this needs to percolate to my Angular front-end. Your help would be much appreciated. Thanks. -
Registering models to admin app
The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data. The admin application can also be useful for managing data in production, depending on the type of website. All you must do to add your models to the admin application is to register them, as shown below from django.contrib import admin from blog.models import Post # Register your models here. admin.site.register(Post) Question: In production environment, Is this the recommended/standard approach to create/update/view data for a model using django admin app(django.contrib.admin)? -
How can I set two Foreign Keys in a class? DJANGO ORM
I need to make a table 'Friend' with foreignkeys that store instances of the User class- two of them one for the friend and one for the user attribute. (Table is of relationships) How to do this? OnetoOneField doesn;t work. It gives me an error in the terminal if I try to make both of them keys. So this is two Many to Many relationships from User to Friend. If it's impossible, what is a better way to set this up? Can the User table have a One-to-Many relationship to itself? class Friend(models.Model): id = models.IntegerField(primary_key=True) friend_id= models.ForeignKey(User, null=False) user_id = models.ForeignKey(User, null=False) -
Django-Haystack text field returns blank lines "\n\n"
I trying to work with django-haystack(2.6.0) and solr(4.10.4) to implement two fields search. I would like to search my model by ship name or ship country(returns a list of ships from a given country) but here I have a problem if I define one field with document=True I get no results. I fallowed the documentation and this answer and it looks fairly easy. I have created the following search_indexes.py: class ShipListIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return ShipList def index_queryset(self, using=None): return self.get_model().objects.all() and I created a new template inside my app that specifies all the fields to be used in a search: search/indexes/myapp/shiplist_text.txt {{ objects.ship }} {{ objects.country }} so here it's my model: class ShipList(models.Model): ship = models.CharField(max_length=200) country = models.CharField(max_length=200) region = models.CharField(max_length=250, blank=True) city = models.CharField(max_length=250, blank=True) ship_class = models.CharField(max_length=200, blank=True) ship_type = models.CharField(max_length=200, blank=True) remarks = models.CharField(max_length=200, blank=True) url = models.URLField(max_length=200) slug = models.SlugField() and the view: def ship_search(request): results = None cd = None form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(ShipList).filter(content=cd['query']).load_all() return render(request, 'core/draft/search.html', {'form': form, 'results': results, 'cd': cd}) simple template {% block search %} {% if "query" in request.GET … -
Reverse for 'path' with no arguments not found. 1 pattern(s) tried.
So I have recently started learning Django, after finishing the tutorial I decided to create my own website and have run into an error that I honestly just don't understand. The error is: Error during template rendering In template /home/phil/Projects/mysite/homepage/templates/_partial.html, error at line 13 Reverse for 'bio' with no arguments not found. 1 pattern(s) tried: ['$bio/'] homepage/templates/_partial.html <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="{% url 'home:index' %}">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="{% url 'home:bio' %}">Bio</a> <!--Attention--> <a class="nav-item nav-link disabled" href="{% url 'home:index' %}">Technologies</a> </div> </div> homepage/url.py from django.views import generic class IndexView(generic.ListView) : template_name = 'homepage/index.html' class BioView(generic.ListView) : template_name = 'homepage/bio.html' homepage/urls.py from django.conf.urls import url from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^bio/', views.BioView.as_view(), name='bio'), url(r'^skills/', views.SkillsView.as_view(), name='skills'), ] As I said I had followed the Django tutorial and honestly can't see what the error is. Index works as expected, but when I call bio or skills it throws this exception. :( -
Viewing and parsing JSON response - djanog
I have sent a JSON rquest that i have sent. I an getting a 200 response which means that the request that was sent is accepted and that there is a response. I am trying to view the full response that was sent back from the request. I have tried 3-4 different ways of viewing the response, but no matter what i try, i cant figure out how to view the full response... Can anyone help me figure out how to see the information.. Request - def createUserSynapse(): url = 'http://uat-api.synapsefi.com' headers = { 'X-SP-GATEWAY' : 'client_id_asdfeavea561va9685e1gre5ara|client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv', 'X-SP-USER-IP' : '127.0.0.1', 'X-SP-USER' : 'ge85a41v8e16v1a618gea164g65', 'Contant-Type' : 'application/json', } payload = { "logins":[ { "email":"test@test.com", } ], "phone_numbers":[ "123.456.7890", "test@test.com", ], "legal_names":[ "Test name", ], "extras":{ "supp_id":"asdfe515641e56wg", "cip_tag":12, "is_business":False, } } print(url) print(headers) print(payload) call = requests.post(url, data=json.dumps(payload), headers=headers) print(call) return call The response that i am getting from the request (I have a line to print the request)... <Response [200]> -
Allow user to edit profile information and submit it causing page to redirect to profile page.
In django I am attempting to allow that user to edit his/her profile information, press submit, and have the the change reflect in his/her profile page. This is the code : In the views.py document in my application User is allowed to view the profile page def view_profile(request): var = { 'user' : request.user } return render(request, 'accounts/profile.html', var) User is allowed to edit the profile page def edit_profile(request): if request.method == 'POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('account/profile') else: form = UserChangeForm(instance=request.user) var = {'form' : form } return render(request, 'accounts/edit_profile.html', var) This is the urls.py document Import modules from django.conf.urls import url from . import views Defined the urls urlpatterns = [ url(r'^profile/$', views.view_profile, name = 'view_profile'), url(r'^profile/edit/$', views.edit_profile, name = 'edit_profile') ] This is the edit_profile {% extends 'base.html' %} {% block head %} <title>{{ user }}</title> {% endblock %} {% block body %} <div class = "container"> <form method = "post"> {% csrf_token %} {{ form.as_p }} <button class = "btn btn-default" type="submit">Submit</button> </form> </div> {% endblock %} When I edit user model on the edit_profile.html page and submit, it redirects from : http://127.0.0.1:8000/account/profile/edit/ To : http://127.0.0.1:8000/account/profile/edit/account/profile This latter urls is not accurate, … -
Get average of user input ratings for different model instances (Django)
Ok, so here is the deal. I'm working on this web-app that lets you create users, beers, and reviews for beers. models.py: from django.db import models from django.conf import settings class BeerModel(models.Model): user = models.ForeignKey(User, default=1) name = models.CharField(max_length=254, default="") style = models.CharField(max_length=254, default="") ibu = models.IntegerField(default="") calories = models.IntegerField(default="") abv = models.IntegerField(default="") location = models.CharField(max_length=254, default="") class Meta: verbose_name_plural = 'Beers' def __str__(self): return self.name def avg(self): return class RateModel(models.Model): FIVE_REVIEWS = ( ('5', '5'), ('4', '4'), ('3', '3'), ('2', '2'), ('1', '1'), ) TEN_REVIEWS= ( ('10', '10'), ('9', '9'), ('8', '8'), ('7', '7'), ('6', '6'), ('5', '5'), ('4', '4'), ('3', '3'), ('2', '2'), ('1', '1'), ) user = models.ForeignKey(User, default=1) beer = models.ForeignKey(BeerModel) aroma = models.PositiveIntegerField(max_length=2, choices=FIVE_REVIEWS, default="5") appearance = models.PositiveIntegerField(max_length=2, choices=FIVE_REVIEWS, default="5") taste = models.PositiveIntegerField(max_length=2, choices= TEN_REVIEWS, default= "10") class Meta: verbose_name_plural = 'Ratings' def __str__(self): return str(self.beer) As you can tell, you can create a review for different beers using different users. My goal is to have django output on the HTML, an "Average" value for "Aroma, appearance, and taste" for each beer. This is what I have in my views.py: @login_required def home(request): beers = BeerModel.objects.order_by('name') rates = RateModel.objects.order_by('user') avg = RateModel.objects.aggregate(aroma = Avg('aroma'), appearance … -
If / else in Django View
I'm trying to display a different template depending on a condition: class RouteList(ListView): model = DailyRoute template_name = 'route_list.html' def get_queryset(self): if DailyRoute.objects.filter( stage = '1').exists(): query_set = DailyRoute.objects.filter(owner=employer, stage = '1').order_by('route') else: query_set = [] return query_set If True - go to template 1.html If False - go to template 2.html The above works for template 1.html only. I can't figure out how properly use the if/else statements to return the correct template and query_set for True/False. Feeling like a dope on this one. -
Query on generic display views - Django
For the below url routing for blog app, from django.conf.urls import url, include from django.views.generic import ListView, DetailView from blog.models import Post urlPatterns=[ url(r'^$', ListView.as_view( queryset=Post.objects.all().order_by("-date")[:25], template_name="blog/blog.html", ) ) ] template blog.html is, {% extends "personal/header.html" %} {% block content %} {% for post in object_list %} <h5>{{post.date|date:"Y-m-d"}}<a href="/blog/{{post.id}}"> {{post.title}} </a></h5> {% endfor %} {% endblock %} where model for blog app is defined as, class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __str__(self): return self.title Question: post.id is internally created as primary key, for every row in the table, but, What does /blog/{{post.id}} mean in the template(blog.html)?