Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'MediaDefiningClass' object is not iterable
I'm attempting to implement django-progressbarupload. https://github.com/ouhouhsami/django-progressbarupload I'm getting the following error: for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable admin.py from django.contrib import admin from accounts.models import UserProfile class UserProfile(admin.ModelAdmin): change_form_template = 'progressbarupload/change_form.html' add_form_template = 'progressbarupload/change_form.html' admin.site.register(UserProfile) This is the traceback Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\jason\Desktop\jason3\accounts\admin.py", line 18, in <module> admin.site.register(UserProfile) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 102, in register for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable Thanks for the help! -
Is the combination of django and REST framework replace parts of django MVC architecture?
Started learning Django lately. To make long story short - If I choose to combine: django framework in my server side REST as the middleware layer some of the client side frameworks (such as React, Angular, etc) which of django's MVC components will become irrelevant? I presume that the templates components. Is there any other fundamental components that won't be necessary in this case? -
Django / Wagtail - Only first page of a parent
I'm trying to return a list of the latest children within a tree. RecordPage can only be added to a specific node, and I want to have a list on the homepage of the "latest" entries added, but return only on RecordPage child per parent node. I tried something like this: return RecordPage.objects.distinct("parent").live().order_by("-first_published_at")[:5] But Django to sad of me saying that the field parent doesn't exist in the model, which makes sense. I can't figure this out from the docs. Help plz? -
failure of migrate existing django project and the output is >> ImportError: cannot import name 'URLResolver'
I am failing to migrate an existing Django project for the first time. BTW, I've installed all the dependencies in a virtualenv, successfully. The output was: File "C:\Users\virtualenv\lib\site-packages\drf_autodocs\parser.py", line 5, in <module> from django.urls import URLResolver as RegexURLResolver ImportError: cannot import name 'URLResolver' I am on Win 7, Py3.5.4, Django 1.11.4 Thank you so much for helping. -
How to load weather icons with each day of yahoo weather forecast?
im new to Django and jquery. I was trying to make a weather app using yahoo weather api. Everything went fine expect the weather icons in the forecast .Previosly the same icon was used for all changing weather but how can i write code so that different icons can be seen for varying climates Here is my Jquery code : $(document).ready(function () { var content = $('#patti').text(); var iconurl = 'http://l.yimg.com/a/i/us/we/52/' +content+ '.gif'; $('#wicon').attr('src', iconurl); $.each($('.icon1'), function( ) { var content2 = $(this).text(); //console.log("content=",content2); var iconurl2 = 'http://l.yimg.com/a/i/us/we/52/' +content2+ '.gif'; console.log(iconurl2); var final = $('.wicon2').attr('src', iconurl2); console.log(final) }); }); My index.html file for the forecast of 7 days : <div id="container-fluid"> <div class="row"> {% if form.is_valid %} <div class="col-sm-3"> <div class="container text-center hi" style="background: whitesmoke"><br> <iframe class="clock" src="http://free.timeanddate.com/clock/i66pyson/n1906/fn4/tct/pct/ftb/ta1" frameborder="0" width="101" height="18" allowTransparency="true"></iframe> <h4 style="color: whitesmoke">{{text}}</h4> <br> <div id="icon"><img id="wicon" src="" alt="Weather icon"></div><h2 id="thendi" style="color: whitesmoke"><strong>{{temp}} °C</strong></h2> <br> <!--<p style="color: whitesmoke">{{date|slice:':3'}}</p>--> <p id="patti" style="visibility: hidden">{{code}}</p> </div> </div> {% endif %} <br> <br> <!--forecast--> <div class="col-md-offset-9"> <div class="row"> {% for obj in forecast|slice:":7" %} <div class="col-sm-offset-5 text-center" style="color: #7a43b6"> <div class="card"> <p style="color: whitesmoke"> {{obj.date}}</p> <p style="color: whitesmoke">{{obj.text}}</p> <div class="card-content"> <p class='icon1' style="visibility: hidden"> <div id="icon2"><img class="wicon2" src="" alt="Weather icon"></div> <p style="color: … -
Getting Type Error when include Djoser urls together with Swagger
I have django-swagger working properly with my API. However, when i try including Djoser urls to my urlpatterns, I get the following traceback: Internal Server Error: /docs/ Traceback (most recent call last): File "/Users/bo/env/home365/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/bo/env/home365/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/Users/bo/PycharmProjects/home365/home365/utils.py", line 47, in get schema = generator.get_schema(request=request) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/schemas/generators.py", line 286, in get_schema links = self.get_links(None if public else request) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/schemas/generators.py", line 324, in get_links link = view.schema.get_link(path, method, base_url=self.url) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/schemas/inspectors.py", line 195, in get_link fields += self.get_serializer_fields(path, method) File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/schemas/inspectors.py", line 337, in get_serializer_fields for field in serializer.fields.values(): File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/serializers.py", line 1026, in get_fields field_names, declared_fields, extra_kwargs File "/Users/bo/env/home365/lib/python3.6/site-packages/rest_framework/serializers.py", line 1373, in get_uniqueness_extra_kwargs field_names, declared_fields, extra_kwargs File … -
How to create a website that automatically updates itself daily by scraping data (Python, Django, Webscraping)?
My goal is to build a website that shows price charts for products on Amazon. The data should be represented visually with a price chart (time-series data), so that users can see how prices have changed over time. The price has to be updated daily for every product page. I plan to scrape price data with my python script in the backend - the script should be executed by a cronjob. The main functions of the script will be to scrape pricing data (with beautifulsoup) for every product page and to append that data to the database. I am really new to python web applications. What would be the best way to achieve my objective? Django? Or are there any frameworks that are better for my use-case ? PS: I dont't want to use Amazon's API. -
Django: update modal without form without overwrite database
I need to update a django model using 3 bootstrap modals. I use AJAX requests to modify this values. In every step I modify one field, but users can cancel de process so I only want to save changes into db when they confirm the action in the last modal. How can I do this without using forms? Only model.field = new_value syntax. -
Django URL's not working
My Django URLs.py ins't working it returns a 404. urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.forums, name='forums'), url('topics/<int:id>/', views.topics, name='topics'), ] -
Django cookiecutter docker build failing: maximum recursion depth exceeded
I've been using the cookiecutter docker setup for local development which has been working wonderfully. I'm now ready to build and deploy a production version of my application. I've followed the instructions here and here. It all seems pretty straight-forward, however when I run the build command: $ docker-compose -f production.yml build I get a RuntimeError: maximum recursion depth exceeded Traceback (most recent call last): File "bin/docker-compose", line 6, in <module> File "compose/cli/main.py", line 71, in main File "compose/cli/main.py", line 121, in perform_command File "compose/cli/command.py", line 40, in project_from_options File "compose/cli/command.py", line 110, in get_project File "compose/config/config.py", line 377, in load File "compose/config/config.py", line 508, in process_config_file File "compose/config/config.py", line 499, in interpolate_config_section File "compose/config/interpolation.py", line 44, in interpolate_environment_variables File "compose/config/interpolation.py", line 44, in <genexpr> File "compose/config/interpolation.py", line 39, in process_item File "compose/config/interpolation.py", line 39, in <genexpr> File "compose/config/interpolation.py", line 54, in interpolate_value ... ... RuntimeError: maximum recursion depth exceeded Failed to execute script docker-compose I'm at a loss of what might be causing this. The main difference between my local and production setup are the production.yml and .django env settings. See below. Ideas? Thanks! production.yml version: '2' volumes: postgres_data: {} postgres_backup: {} caddy: {} services: &django django: build: context: … -
django & Vue.js: Why is my VueJs component not showing in the frontend?
I am trying to implement vuejs in a current django project. but the components are not showing up in the frontend. my app is "homepage", I have a class in models called "Games", and function in views called "games" So here I have my basic vue component <template> <div id=""> <table> <tr><td>Titre </td><td>Nom </td></tr> <tr v-for="game in liste"> <td>{{game.fields.titre}}</td> <td>{{game.fields.nom}}</td> </tr> </table> </div> </template> <script> export default{ data(){ return{ liste: [] } }, mounted(){ this.$http.get("/homepage/games").then( (req) => this.liste = req.data) } } </script> <style> </style> App.js import Vue from 'vue' import VueResource from 'vue-resource' import Exemple from './components/Exemple.vue' Vue.use(VueResource) new Vue(Exemple).$mount(".exemple") index.html {% extends "layout.html" %} {% block content %} <h1>hello this is challenge 2 tow</h1> <div class="exemple"> <exemple></exemple> </div> {% endblock %} layout.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% block content %} {% endblock %} </body> <script src="{% static 'public/bundle.js' %}"></script> </html> views.py from django.shortcuts import render from django.core.serializers import serialize from django.http import HttpResponse from .models import Games def games(request): games = serialize("json", Games.objects.all()) return HttpResponse(games, content_type="application/json") I have vue dev tools installed, it tells me that "Vue.js not detected. any solution please?!! thank you in advence -
Confirmation email in django selenium tests
I'm trying to write simple login test for my django application using selenium for python but I'm getting error that credentials are not valid. For registration I'm using allauth package which provides email confirmation mechanism. As I understand credentials are not valid because newly created users didn't respond to confirmation email. Is there a way to turn it off for testing purpose? I was trying to set ACCOUNT_EMAIL_REQUIRED setting to False but it caused assertion (It is a result of runserver command): Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x7fccbb8cb400> Traceback (most recent call last): File "/pathToPython/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/pathToPython/python3.5/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/pathToPython/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/pathToPython/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/pathToPython/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/pathToPython/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/pathToPython/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/pathToPython/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/pathToPython/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", … -
Activation link url pattern Django
I'm new to django, thus the question. I'm sending the following activation link to users to activate their accounts. http://localhost/api/v1/bouncer/verify?id=6&&token=AE8C448C50C5249CF56DFDE893E2F6DD I'm a little lost as the url regex which will capture the id and the token value. Any help appreciated. -
Django - Returning new form output in new line without overwriting previous output
I have been developing a bot using python and nltk and it works on the command line. Now I want to capture input using a web page, and I am transferring the logic to Django. I will use a simpler example to demonstrate the problem I have. In my index.html, I have a user entering a question into a single input box and upon clicking send, the view simply returns what they entered: their 'question' and 'answer' below the input box. The problem is when they enter a new question it overwrites the previous one, but I would want the new question and answer to appear below the previous one as in a chat thread. If maybe you do not get what I mean, I'll use images. This happens: when the user enters first chat message. Then when the user enters second chat message. What I want is this: to have both of them as a thread and not two overwriting one I have just started using Django with this project and while with the cmd I could just use while True: I am a bit stumped on how to do it using the views and templates in Django. Here's … -
PythonAnywhere 'function' object has no attribute 'get_extra_actions' Django Rest
I've made a basic application with the Django framework and PythonAnywhere is not liking my code for some reason. When I ran the autoconfiguration for manual setup, I got an error that Django rest framework was required and the setup exited prematurely. The error was: ModuleNotFoundError: No module named 'rest_framework' I got into the venv and finished setup, though there were a few issues here and there. I manually installed djangorestframework from Github so that anything would show up, but I am still getting an unknown error that I have traced back to the routers.py file. The content of the error can be found on: nebrethar.pythonanywhere.com A sample of my routers.py file is as follows: def get_routes(self, viewset): known_actions = list(flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)])) extra_actions = *****viewset.get_extra_actions()***** not_allowed = [ action.__name__ for action in extra_actions if action.__name__ in known_actions ] I have starred out the section that causes the error. Most of the fixes I've run into have been installing packages but I've been stumped. -
Django Tag System
here I have the code, I want to create a post tag or category, I do not want to create a new tag when I already have tags that I have created and sent to the database, with the code below the tag is made duplicate class Post(models.Model): post = models.CharField(max_length=50) class Tag(models.Model): tag = models.CharField(max_length=50) tags = models.ManyToManyField(Post, through="Tagging") class Tagging(models.Model): posts = models.ForeignKey(Post, on_delete=models.CASCADE) taggings = models.ForeignKey(Tag, on_delete=models.CASCADE) def index(request): if request.method == "POST": post = request.POST['post'] tag = request.POST['tag'] posts = Post.objects.create(post=post) tags = Tag.objects.create(tag=tag) tp = Tagging(posts=posts, taggings=tags) tp.save() return redirect('index') return render(request, 'index.html') how to tag not duplicate? -
Python library for video processing
I want to build a website that will be able to play video and audio musics with django what the necessary Python libraries I need to know for video processing. -
Integrate a paypal button with another django function
I'm using paypal api in my django project. Here is the script put in html. <script type="text/javascript"> paypal.Button.render({ env: 'production', // Or 'production' client: { sandbox: '', production: "<my_production>", }, locale: 'en_US', commit: true, // Show a 'Pay Now' button payment: function(data, actions) { return actions.payment.create({payment: {transactions: [ { amount: { total: '0', currency: 'USD'} } ]}}); }, onAuthorize: function(data, actions) {return actions.payment.execute().then(function(payment) { document.getElementById("program").value = "program"; $('#program_form').submit(); });} }, '#paypal-button1'); Call this script with <div id="paypal-button1"></div> And I have a button which sends some user information to the database with method POST. <form> <div class="input-container"> <input type="email" placeholder="E-mail" name="email" required> </div> <div class="input-container"> <input type="submit" class="btn-style" name="post" value="Submit"> </div> </form> The function is in veiws.py. Now, is there any way I could integrate the two buttons? Too many buttons might be a bad UX design. Thank you. -
How do I sort my topics by category in Django?
Alright so I want to order my topics by the category in Django. What's the best way of doing this? views.py: from django.shortcuts import render from .models import Category from .models import Topic # Create your views here. def forums(request): categorys = Category.objects.all() topics = Topic.objects.all() return render(request, 'forums.html', {'categorys': categorys, 'topics': topics}) models.py: from django.db import models # Create your models here. class Attachment(models.Model): file = models.FileField() def __str__(self): return self.file class Category(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Topic(models.Model): title = models.CharField(max_length=150) description = models.TextField() category = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=150) body = models.TextField() forum = models.ForeignKey('Topic', on_delete=models.CASCADE) def __str__(self): return self.title Also, yes I know that categories is spelled wrong, I still need to add the Meta. -
Django-Viewflow, customize archive view
I am trying to customize the default /workflow/archive/ view from Viewflow. (as in http://demo.viewflow.io/workflow/archive/) I need to remove some of the columns and add some additional ones specific to my task. I can't seem to find an easy way. I have been digging and have found that I can try to override the class viewflow.frontend.views.AllArchiveListView and adding the mapping url('^test/', AllArchiveListView.as_view()) but I get no data when doing that (seems like the flow_classes internal parameter is empty when it gets called like that) I have also tried to create the viewflow/site_archive.html template but seems overkill. Any ideas that may point me in the right direction would be highly appreciated! -
Reverse {% url %}: Reverse for '"' not found. '' is not a valid view function or pattern name
I've been stuck on this for a while, can't seem to fix the error. I do not use reverse() anywhere in the view. urls.py urlpatterns = [ url(r"^book/", include("bookings.urls")), ] bookings.urls.py app_name = 'bookings' urlpatterns = [ url(r'^charge/$', views.charge, name='charge'), url(r'^booking/$', views.booking, name='booking'), ] views.py def booking(request): # some code render(request, 'bookings/template.html', {'listing': listing,}) def charge(request): # some code template.html <form action="{% url 'bookings:charge' %}" method="post"> I tried all different alterations and namespaces, e.g. trying to use just charge, different namespaces in urls.py etc. When I render the book/booking/, I get the following error: Reverse for 'charge' not found. 'charge' is not a valid view function or pattern name. -
How to get user in Django REST framework?
I'm using the Django REST framework and I'm trying to get the user like this in one of my class-based views: class ListPDF(PDFTemplateView): """ Return a PDF """ permission_classes = (IsAuthenticated,) template_name = 'pdf.html' def get_context_data(self, **kwargs): user = User.objects.get(id=self.request.user.id) but for some reason I keep getting the error User matching query does not exist. I'm using the rest_framework.authtoken for authentication. I've investigated and when I don't log in through the admin section the user is anonymous even though the user token is sent with the request. How do I get the user object in this view? -
Create input text fields based on value user selects in dropdown in Django forms
In my application on one page there is a dropdown. When user selects any value from available dropdown values ie; 1 to 10, based on that value I need to have that number of text fields in my form. How could I do that dynamic functionality/on-the-fly in forms.py of django project. -
django2.0 forms.ValidationError always return me 'password_mismatch'!
I want to valid email isn't exists, so I do this forms.py class RegisterForm(auth_forms.UserCreationForm): code = forms.CharField(label=_('valid code'), max_length=6) def clean(self): cleaned_data = super().clean() email = cleaned_data['email'] if email and User.objects.filter(email=email): raise forms.ValidationError(_('email already in use'), code='invalid') class Meta: model = User fields = ('first_name', 'last_name', 'email', 'code') and I want, when user register, if email is exists, I will return "email already in user" to him, now I just print it, when forms is invalid, so I do this in views.py views.py class RegisterView(SuccessMessageMixin, FormView): template_name = 'account/signup.html' form_class = RegisterForm extra_context = {'page': 'register'} success_url = '/' success_message = _('register success') def form_valid(self, form): user = form.save() login(self.request, user) return super().form_invalid(form) def form_invalid(self, form): print(form.error_messages) error_msg = list(form.error_messages.values())[0] return utils.ajax_error(error_msg) but, when I run it, I give some data to form, is all valid exists email I should get email aliready in use, but I always get {'password_mismatch': "The two password fields didn't match."} but the password1 and password2 is same! Why I always get the error about password ! -
Django issues passing variable from view to template javascript
Description: I have an view that is called every second to display temperature data to temperature.html from the backend of my project. In order for it to fulfill its purpose it needs an variable which will be passed through render to the template, where i want it to be used as an Javascript variable in order to update the canvas-gauge that I am using within the template to display temperature data. Problem: My view is being called through the console at the correct interval, so that is not the issue. However, what is not happening is the variable is not being passed through to the template at all. I have tried to have the template display the variable to see if the variable is at least being sent to the template. Answer: It is not reaching the template at all, variable outputs "undefined". I have passed forms in this manner through my other views in the same way I am attempting to pass this variable, and it works correctly. I do not understand where I am mistaken with my template/view. I have researched for at least 6 hours in attempt to find the solution and clearly I have not found …