Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I display Django data from a related model of a related model?
I am trying to display data from several models that are related together through a QuerySet. My ultimate goal is to display some information from the Site model, and some information from the Ppack model, based on a date range filter of the sw_delivery_date in the Site model. Here are my models: class Site(models.Model): mnemonic = models.CharField(max_length = 5) site_name = models.CharField(max_length = 100) assigned_tech = models.ForeignKey('Person', on_delete=models.CASCADE, null = True, blank = True) hw_handoff_date = models.DateField(null = True, blank = True) sw_delivery_date = models.DateField(null = True, blank = True) go_live_date = models.DateField(null = True, blank = True) web_url = models.CharField(max_length = 100, null = True, blank = True) idp_url = models.CharField(max_length = 100, null = True, blank = True) def __str__(self): return '(' + self.mnemonic + ') ' + self.site_name class Ring(models.Model): ring = models.IntegerField() def __str__(self): return "6." + str(self.ring) class Ppack(models.Model): ppack = models.IntegerField() ring = models.ForeignKey('Ring', on_delete=models.CASCADE) def __str__(self): return str(self.ring) + " pp" + str(self.ppack) class Code_Release(models.Model): Inhouse = 'I' Test = 'T' Live = 'L' Ring_Location_Choices = ( (Inhouse, 'Inhouse'), (Test, 'Test'), (Live, 'Live'), ) site_id = models.ForeignKey('Site', on_delete=models.CASCADE) type = models.CharField(max_length = 1, choices = Ring_Location_Choices, blank = True, null = True) release … -
All javascript stops working on my child template when I perform an AJAX call to change the queryset
I have a comments.html child template that looks like this: <div class="commentsContainer"> {% for comment in comment_list %} ... {{ comment.text }} ... {% endfor %} </div> When I click on a button I call this AJAX function: $('.comments_new').on('click', function() { $.ajax({ type: 'GET', url: '/new_comments/', data: { }, success: function (data) { $('.commentsContainer ').replaceWith(data); } }) }); which calls this view to change the queryset (the inital queryset is comment_list = Comment.objects.filter().order_by('-score__upvotes'): def new_comments(request): if request.is_ajax(): comment_list = Comment.objects.filter().order_by('-timestamp') html = render_to_string('comments.html', {'comment_list': comment_list}) return HttpResponse(html) This successfully swaps the querysets, however for some reason no javascript works on the newly loaded template/queryset. I even tried just using a simple .css() jquery function but it doesn't work either. Only regular css works. Can somebody tell me why this happens and how I can fix it? -
Assertion Error loading graphene schema w/ Django choices
I'm pretty new to Django/Graphene, using it very basically in a new project. I have this class with choices: class Question(models.Model): """ A question that was asked. who asked, when and what answers did it get """ QUESTION_TYPES = ( ('YN', 'Yes No'), ('MC', 'Multiple Choice'), ('OP', 'Open ended') ) _question_type = models.CharField(max_length=2, choices=QUESTION_TYPES, default='OP') uid = models.CharField(max_length=512, unique=True, primary_key=True) by_user = models.ForeignKey(User) It seems that when the server is loading my Graphene's schema (I execute runserver and point my browser to the url), I get an assertion error in: graphene/types/typemap.py in graphene_reducer, line 73 using a debugger - I can tell the assertion break when the "type-maps" compares the enum generated by my Django model (Question) and the one Graphene is using (wrapped/converted). attached a snapshot of of the debugger's breakpoint: I fail to understand why the expression _type.graphene_type == type evaluates to False HALP PLEEZE!! :) Thanks in advance. I'm using phyton 3.5, Django 1.10.5, Graphene 1.2.1 -
How to undo changes from unfinished migration in django
I ran makemigrations and then ran migrate on django project. But due to some complications the migrations could not be completed and stopped in between. What is the easiest way to revert the database to earlier state or undo changes of the unfinished migration. I am using django 1.10 but I think same applies with versions of django after 1.6 -
Django Admin Google Map Plotter for Lat Lng Fields
So I've got a Camera model that requires two fields to be properly displayed within a Google Map template on the front end: lat and lng: class Camera(models.Model): name = models.CharField(max_length=30) model = models.CharField(max_length=30, default="Dummy") lat = models.FloatField(default=00.00) lng = models.FloatField(default=00.00) company = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name These fields are directly editable within the Django Admin, really, they're somewhat useless unless you know what your coordinates are already. I'd like to add a Google Map marker plotter that will allow a drag and drop interface (Widget? Django form?) to assign these two values using the Google Maps API. Now, I can deal with the Google Maps API no problem, but I really need help extending the Django Admin to allow this kind of widget (I'm assuming it would be a widget?) or Django Form. I'm thinking that the lat and lng fields could be either visible (for manual entry) or hidden and auto-filled by the Google Maps API. Your help and direction is greatly appreciated. -
Using the URLconf defined in TEST_PAGE, Django tried these URL patterns, in this order:
I've reviewed other posts related to my question, but I'm unable to find an answer for my question. When I try to access "http://127.0.0.1:8000/TEST_PAGE" I get the following error: "Using the URLconf defined in TEST_PAGE, Django tried these URL patterns, in this order: ^admin/ ^$ ^TEST_PAGE/ The current URL, TEST_PAGE, didn't match any of these." Here is what I have for Mysite/Mysite/urls.py: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include('Main_Page.urls')), url(r'^TEST_PAGE/', include('TEST_PAGE')), ] I have the APP installed in Mysite/Mysite/settings.py: INSTALLED_APPS = [ 'TEST_PAGE', 'Main_Page', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Here is what I have for Mysite/TEST_PAGE/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^TEST_PAGE', views.index, name='TEST_PAGE'), ] And here is what I have for Mysite/TEST_PAGE/views.py: from django.shortcuts import render def index(request): return render(request, 'TEST_PAGE/TEST_PAGE.html') The main/index/home app works fine, I'm just trying to access the second app. I'm new to this, so any help would be appreciated. -
Webhook Django API.AI - Unable to parse JSON object in POST request
When user/customer uses the api.ai chat bot then it sends JSON object to my django backend (webhook). I'm not able to understand from the documentation how webhooks can be created using django back-end. Sample Request to the Service(or my back-end): POST https://my-service.com/action Headers: //user defined headers Content-type: application/json POST body: { "originalRequest": { "data": { "text": "shipping costs for asia", "match": [ "shipping costs for asia" ], "type": "message", "event": "direct_message", "team": "T0FJ03RMP", "user": "U0FLW1N95", "channel": "D4VTEALFP", "ts": "1478131884.000006" }, "source": "slack_testbot" }, "timestamp": "2016-11-03T00:11:24.706Z", "result": { "speech": "", "fulfillment": { "speech": "Shipping cost varies for the location the item needs to be shipped to. We will show you the cost, when you form the order in your cart.", "messages": [ { "speech": "Shipping cost varies for the location the item needs to be shipped to. We will show you the cost, when you form the order in your cart.", "type": 0 } ] }, "score": 1.0, "source": "agent", "action": "shipping.cost", "resolvedQuery": "shipping costs for asia", "actionIncomplete": false, "contexts": [ { "name": "generic", "parameters": { "slack_channel": "D2VTEALFP", "shipping-zone.original": "Asia", "shipping-zone": "Asia", "slack_user_id": "U0FLW1N93" }, "lifespan": 4 } ], "parameters": { "shipping-zone": "Asia" }, "metadata": { "intentId": "e2eb1b9c-761d-4588-8b00-d7062128cb51", "webhookUsed": "true", "intentName": … -
How to configure django logging for production under gunicorn server?
I have this logging configuration set up: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'verbose' } }, 'loggers': { 'gunicorn.errors': { 'level': 'INFO', 'handlers': ['console'], 'propagate': True, }, } } It seems to have no effect at all. When the flag DEBUG is set to True then I can see some errors in the console. When however it's set to False, I cannot. So how to log the errors to the console despite DEBUG flag being set one way or the other? -
Django __str__ returned non-string (type tuple), i didn't define __str__
I'm working on a duplicate reporting system on Django, and i created a table on my models.py that goes class DupReport(models.Model): count = models.IntegerField() oldersub = models.ForeignKey('Submission', on_delete=models.CASCADE, related_name='older_sub') newersub = models.ForeignKey('Submission', on_delete=models.CASCADE, related_name='newer_sub') And when i go to admin to add a row, the menu that displays the rows works fine, but when i click add DupReport, i get this: TypeError at /admin/apppickoff/dupreport/add/ str returned non-string (type tuple) < a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}< /a> -
Why for loop only save the last file in Django?
When I choose two images in my template, the save method always save the last image selected but I don't understand what it is happens. this is my view: class imgcreate(CreateView): model = Archivos template_name = 'img.html' form_class = imgForm success_url = reverse_lazy('BackEnd:unidades') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('imagen') if form.is_valid(): a = 0 for imagen in files: a = a+1 img = form.save(commit=False) img.id_unidad = 1 img.tipo_archivo = 1 img.nombre_archivo ='hhh'+ str(a) img.save() print(a); return self.form_valid(form) else: return self.form_invalid(form) print always returns the name of the image with 2 that mean only the last image is saved -
Not getting score in my mcq app- Django
For my MCQ app, I created a view def process_data(request): question_set=Question.objects.all() choice_list=[] question_set for k, v in request.POST.items(): if k.startswith('choice'): choice_list.append(v) i=0 score=0 print type(question_set) for question in question_set: if question.answer1==choice_list[0]: #print question.answer1 i=i+1 score=score+1 return HttpResponse(score) html page contains the form look like this. {% extends 'quiz/base.html' %} {% block content%} <h1>You are at quiz page</h1> <form action="{% url 'quiz:process_data' %}" method="post"> {% csrf_token %} {% for question in question_set %} <h3>{{question.question_no}}.{{question.question_text }}</h3> <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option1 }}">{{ question.option1 }}<br> <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option2 }}">{{ question.option2 }}<br> <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option3 }}">{{ question.option3 }}<br> <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option4 }}">{{ question.option4 }}<br> <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option5 }}">{{ question.option5 }}<br> {% endfor %} <input type="Submit" name="Submit"> </form> {% endblock%} and this is the model for Questions class Question(models.Model): question_no=models.IntegerField(default=0) question_text=models.CharField(max_length=1000) option1=models.CharField(max_length=100) option2=models.CharField(max_length=100) option3=models.CharField(max_length=100) option4=models.CharField(max_length=100) option5=models.CharField(max_length=100) answer1=models.CharField(max_length=100) def __str__(self): return self.question_text The problem is that the score is not getting correctly. So that I tested it with the print statement and realized that only first questions answer is getting. How can I get the score correctly? Thank you -
Can I use getElementById() in a Maps infowindow in JavaScript?
I have an several markers placed on a Google Maps map and every marker has an infowindow with the following content: // Set the content of the infowindow of the marker. var infoContent = '<div id="iw-container" class="gm-style-iw">'+ '<div class="iw-title">'+ '<p>{{place.name}}</p>'+ '</div>'+ // For each photo associated with this place, add it. '<div class="container-fluid">'+ {% for photo in place.photo_set.all %} '<div class="row">'+ '<div class="col-md-4">'+ '<hr>'+ '<div class="">'+ // Check whether the attributes have a value and display them. {% if photo.info != "" and photo.info != None %} '<p class="iw-info">{{ photo.info }}</p>'+ {% endif %} {% if photo.year != "" and photo.year != None %} '<p class="iw-year">{{ photo.year }}</p>'+ {% endif %} {% if photo.source != "" and photo.source != None %} '<p class="iw-source">Bron: {{ photo.source }}</p>'+ {% endif %} '</div>'+ // Display the image with a link to the modal view. '<div class="iw-image">'+ '<img id="{{ photo.id }}" class="iw-image" src="../static/images/{{ photo.image }}">'+ '</div>'+ '</div>'+ '</div>'+ {% endfor %} '</div>'+ '</div>'; I want to add a modal view for every image in every infowindow, but I can not do this: var img = document.getElementById("{{ photo.id }}"); This is because every time the img variable is Null. Is it possible to access infowindow … -
Django import export: update without add
I'm using 'django import export' (DIE) for importing and updating some data. Import process starts from checking exists objects in DB, searching by values in ID-field, and if row with ID from import file not found - new entre will be created. How can i made "update only" scenario, where if 'id key' not found in DB, row will be skipped (not added new)? my model.py class Size(models.Model): id = models.AutoField(unique=True, primary_key=True, null=False, blank=False) height = models.SmallIntegerField() width = models.SmallIntegerField() class Product(models.Model): id = models.AutoField(unique=True, primary_key=True, null=False, blank=False) vendor_code = models.CharField(unique=True, max_length=50, null=False, blank=False) price = models.DecimalField(null=False, blank=False) size = models.ForeignKey(Size, verbose_name=u'Size') in resource.py class ProductSyncResource(resources.ModelResource): class Meta: model = ProductVariant import_id_fields = ('vendor_code',) fields = ('vendor_code', 'price',) export_order = ('vendor_code', 'price', 'status', ) skip_unchanged = True report_skipped = True dry_run = True import table (xls) If vendor_code 'Tк-12856' (Cell A3) will be not found, then DIE will try to add this row, and: We will get error from DB (foreignKey check for column 'size') I don't need to add this row to DB in my 'update scenario' -
rollyourown.seo app giving Apps aren't loaded yet error
I started with the SEO in Django and I wanted to use the Djang-Seo framework avaliable from: http://django-seo.readthedocs.io/en/latest/introduction/overview.html The problem is when I follow the steps, I add the line 'rollyourown.seo' to the Installed apps in settings.py but when I try to syncdb or start the server with the runserver command, I get the following error: Unhandled exception in thread started by <function wrapper at 0x039D65B0> Traceback (most recent call last): File "c:\python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "c:\python27\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "c:\python27\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "c:\python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "c:\python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "c:\python27\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "c:\python27\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "c:\python27\lib\site-packages\rollyourown\seo\__init__.py", line 4, in <module> from rollyourown.seo.base import Metadata, Tag, KeywordTag, MetaTag, Raw, Literal, get_metadata, get_linked_metadata File "c:\python27\lib\site-packages\rollyourown\seo\base.py", line 12, in <module> from django.contrib.sites.models import Site File "c:\python27\lib\site-packages\django\contrib\sites\models.py", line 86, in <module> class Site(models.Model): File "c:\python27\lib\site-packages\django\db\models\base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "c:\python27\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "c:\python27\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. … -
Django REST - Deny read access to ListAPIView
I'm trying to familiarize myself with djangorestframework's permissions setup. As part of that, I'm trying to establish a proof-of-concept for denying all access (incl. read access) based on a function's response and making sure it gets denied. (Basically making sure the function gets used when I think it's supposed to get used.) I've got a RetrieveAPIView and a ListAPIView set up identically. The Retrieve denies access as it should, but the List allows access, and I'm trying to figure out why there is a difference. # in views.py class TableList(generics.ListAPIView): queryset = MyModel.objects.all() serializer_class = MySerializer permission_classes = (RejectAll,) class TableDetail(generics.RetrieveAPIView): queryset = MyModel.objects.all() serializer_class = MySerializer permission_classes = (RejectAll,) # in permissions.py class RejectAll(permissions.BasePermission): def has_object_permission(self, request, view, obj): return False # for proof of concept -- this should always block all access? # in settings.py ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } # in serializers.py class MySerializer(serializers.ModelSerializer): class Meta: model = SolarData fields = (...) I understand that I can create a get_object() method that calls self.check_object_permissions(self.request, obj), but wouldn't that defeat the purpose of having permission_classes set? Shouldn't the generic view perform that same check on its own? -
django-filter dropdown menu
I'm trying to turn my django-filter fields into dropdowns. class UserFilter(django_filters.FilterSet): class Meta: model = Product fields = ['category', 'genre', 'instrument', ] def filter(request): filter = UserFilter(request.GET, queryset=Product.objects.all()) return render(request, 'filter.html', {'filter': filter}) I'm trying to achieve this by using ModelChoiceFilter, like this: category=django_filters.ModelChoiceFilter(queryset=Product.objects.all()) genre = django_filters.ModelChoiceFilter(queryset=Product.objects.all()) instrument=django_filters.ModelChoiceFilter(queryset=Product.objects.all))) It works! However instead of returning the desire column, it returns title filed on all of the django-form fields. That is coming from my model. def __str__(self): return self.title The same behavior can be observed when working with simple Django model forms. In this case I'm just overriding label_from_instance function of the ModelChoiceField class like this: class CategoryModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.category My question is how to override ModelChoiceFilter? Or probably there is another convenient way to achieve dropdowns with django-filter? -
Be able to add different subclasses with django-admin while just registered the parentclass
Let's say, I have this in models.py: class ParentClass(models.Model): def get(self): raise NotImplmentedException #Not sure about the name, just to show class SubClass1(ParentClass): def get(self): return '3' class SubClass2(ParentClass): def get(self): return 'hi!' Then I wanted to add this to my admin site: in admin.py I typed admin.site.register(ParentClass). But the parentclass isn't implemented, it isn't made to be used, it's just a kind of wrapper for its subclasses. Let's imagine, only for better understanding the question, them both having values, but different ones (for example: the first has an IntegerField, the second a CharField). Note: For better understanding I just said I've registered them directly to the admin. In reality they are differend inline elements of a text and I want to deal with every element in the same way so I decided to use subclasses for the differences. The problem is how to add them to the admin site in the right way. (I hope, my question is clearly.) I drew a few pictures to show what I want: django admin site - picture 1 | django admin site add model inline - picture 2 Now I want to be able to click at 'add Parentclass' and then get … -
InMemoryUploadedFile' object has no attribute 'save_book_to_database'
I'm currently trying to test out django-excel, but keep on running into an issue when I try there import functionality in the tutorial. When I go to the /polls/import/ url and try to upload the test data, I get the following error: InMemoryUploadedFile' object has no attribute 'save_book_to_database' ... ./polls/views.py in import_data request.FILES['file'].save_book_to_database( Any direction on how to resolve this is greatly appreciated! The package can be found here: https://github.com/pyexcel/django-excel -
Django: ascii codec can't decode byte 0xe2
I have create a Django application with python 3.4 on windows platform. Now I am trying to host it on AWS Linux instance. First time I faced the following error Non-ASCII character '\xe2' I resolved this issue by adding utf on each page. -- coding: utf-8 -- Now I am facing the following error 'ascii' codec can't decode byte 0xe2 in position 18: ordinal not in range(128) I have searched and tried to implement encoding etc but doesn't work. I have completed the application and mostly functions are doing request to http, parsing html etc. Its really worrying for me to debug on production server and encode each function. I am using Apache on production server and tried with both python version 2.7 and 3.5 Any idea how can I resolve this issue. Thanks -
conditional aggregate with distinct values in django
I newbie to django. I am facing problem in converting postgresql query to django ORM code. I have a query like SELECT COUNT(DISTINCT(CASE WHEN event = 'open' THEN email END)) as open, COUNT(DISTINCT(CASE WHEN event = 'delivered' THEN email END)) as delivered, COUNT(DISTINCT(CASE WHEN event = 'click' THEN email END)) as click, COUNT(DISTINCT(CASE WHEN event = 'bounce' THEN email END)) as bounce FROM email_events Please help me to write django equivalent to above query or similar one which gives same result Thank you ! -
Make django modelchoicefield readonly true
On my edit page,I am trying to allow user to edit/change what they have entered, with one condition that they cant edit Modelchoice field. So, I tried this command but it didn't work. With "readonly= True" user still can change the modelchoicefield "dropdown file" while with "disabled = True" user can't change the modelchoicefield but when they try to submit they get this error: "This field is required." myform.py class NameForm(forms.ModelForm): class Meta: model=Name fields = '__all__' def __init__(self, *args, **kwargs): super(NameForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['disabled'] = 'disabled' #self.fields['plotID'].widget.attrs['readonly'] = True Anyone with solution..? Thanks in advance -
Django form using HTML template
I'm new to Django and I have been trying to get this form to POST. I have read the documentation on forms but i'm a bit confused by it as I am not sure how to implement the Jquery date picker or drop down menu if i create a forms.py file. I have created the template and i can access it and it formats exactly how i want, however I can't workout how to get it to POST. The idea is to take the data in the form and insert it into a Postgres table. Template submit.py {% extends 'website/header.html' %} {% block content %} <p><b>Submit Job</b></p> <form action="/submit/" method="post"> {% csrf_token %} <b>Select Asset to transcode</b> <p>Material ID: <input type="text" name="material_id" size="30" value="" id="keyword"/> </p> <p>Profile: <select name="workflow"> <option value="">Select a transcode Profile</option> {% for i in object_list %} <option value="{{ i.name }}">{{ i.name }}</option> {% endfor %} </select> </p> script> $(function() { $( "#start_datepicker" ).datepicker({ dateFormat: 'dd-mm-yy' }); }); </script> <p>License Start Date: <input type="text" id="start_datepicker" name="start_date"></p> <script> $(function() { $( "#end_datepicker" ).datepicker({ dateFormat: 'dd-mm-yy' }); }); </script> <p>License End Date: <input type="text" id="e`enter code here`nd_datepicker" name="end_date"></p> <p> <input type="submit" name="submit" /> </p> </form> {% endblock %} Views.py … -
Using swagger-codegen with username and password basic auth
I have a django rest_framework API, Swagger and a Swagger UI. When I am not logged in I can see a very limited view of "login" and "docs". When I am logged in I can see lots of stuff. I am trying to use the swagger-codegen to generate a client: java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar \ generate -i http://127.0.0.1:8080/api/docs/ -l python -o myclient However, it only generates a very limited client that provides the "login" and "docs" functionality. How do I let swagger-codegen know how to login using http basic authentication, in order for it to generate a more complete client? The docs says I should do the following, but I do not know what it expects: -a <authorization>, --auth <authorization> adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values -
ImportError: cannot import name Upload
I am working on Django, django-rest project and as I have searched the problem, it is beleived I have circular problem, but I don`t think so... Relevant parts of problem are here: demo/views.py from django.shortcuts import render from rest_auth.models import Upload, UploadForm from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse # Create your views here. def home(request): if request.method=="POST": img = UploadForm(request.POST, request.FILES) if img.is_valid(): img.save() return HttpResponseRedirect(reverse('imageupload')) else: img=UploadForm() images=Upload.objects.all() return render(request,'home.html',{'form':img,'images':images}) rest_auth/models.py from django.conf import settings from rest_framework.authtoken.models import Token as DefaultTokenModel from .utils import import_callable from django.db import models from django.forms import ModelForm class Upload(models.Model): pic = models.ImageField("Image", upload_to="images/") upload_date=models.DateTimeField(auto_now_add =True) # FileUpload form class. class UploadForm(ModelForm): class Meta: model = Upload and demo/urls.py from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView, RedirectView from django.conf import settings from django.conf.urls.static import static from views import home from rest_framework_swagger.views import get_swagger_view import os PROJECT_DIR=os.path.dirname(__file__) urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="home.html"), name='home'), url(r'^upload/$', views.home, name='imageupload'), url(r'^signup/$', TemplateView.as_view(template_name="signup.html"), name='signup'), Problem is as stated this: File "/Desktop/zadnja/django-rest-auth/demo/demo/urls.py", line 6, in from views import home File "/Desktop/zadnja/django-rest-auth/demo/demo/views.py", line 2, in from rest_auth.models import Upload, UploadForm ImportError: cannot import name Upload -
Django not taking templates from installed third party apps(dj-stripe)
I am trying to integrate dj-stripe for payment processing with stripe in my django app. But django is not detecting base template from dj-stripe. It returns a TemplateDoesNotExist Exception. Here are relevant snippets from my error page: Request Method: GET Request URL: http://127.0.0.1:8000/payments/subscribe/ Django Version: 1.9 Exception Type: TemplateDoesNotExist Exception Value: base.html Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/xx/Virtual_Environments/App/project/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/xx/Virtual_Environments/App/local/lib/python2.7/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/xx/Virtual_Environments/App/local/lib/python2.7/site-packages/django/contrib/auth/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/xx/Virtual_Environments/App/project/extensions/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/xx/Virtual_Environments/App/local/lib/python2.7/site-packages/djstripe/templates/base.html (Source does not exist) Error during template rendering In template /home/xx/Virtual_Environments/App/local/lib/python2.7/site-packages/djstripe/templates/djstripe/subscribe.html, error at line 1 base.html 1 {% extends "djstripe/base.html" %} 2 {% load static djstripe_tags %} 3 4 {% block title %}Choose a Subscription{% endblock title %} 5 6 {% block content %} 7 {{ block.super }} 8 <ul class="breadcrumb"> 9 <li><a href="{% url 'djstripe:account' %}">Home</a></li> 10 <li class="active">Subscription</li> 11 </ul> In the subscribe.html template its extending djstripe/base.html but django is searching for base.html only. Here is possibly relevant snippet from my settings file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "django.contrib.sites", 'extensions', 'accounts', "djstripe", ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': …