Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO 1.11 - Can't find fixtures
Problem I was trying to use fixtures to populate my database, so I started by reading through the documentation for loaddata and by default, it looks in the fixtures directory inside each app for fixtures. My problem is that when I run python manage.py loaddata I'm getting an error, but when I give it the path for teams.yaml it works fine. Do I need to setup something for it to work? Documentation https://docs.djangoproject.com/en/1.11/howto/initial-data/#where-django-finds-fixture-files Error usage: manage.py loaddata [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--database DATABASE] [--app APP_LABEL] [--ignorenonexistent] [-e EXCLUDE] fixture [fixture ...] manage.py loaddata: error: No database fixture specified. Please provide the path of at least one fixture in the command line. Team App Dir team ├── admin.py ├── apps.py ├── fixtures │ └── teams.yaml ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20190204_0438.py │ ├── 0003_remove_team_team_name.py │ ├── `enter code here`0004_team_team_name.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-36.pyc │ ├── 0002_auto_20190204_0438.cpython-36.pyc │ ├── 0003_remove_team_team_name.cpython-36.pyc │ ├── 0004_team_team_name.cpython-36.pyc │ └── __init__.cpython-36.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-36.pyc │ ├── apps.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ └── models.cpython-36.pyc ├── tests.py └── views.py Model from django.db import models class Team(models.Model): team_name = models.CharField(max_length=32) team_description … -
'MediaDefiningClass' object is not iterable - django-import-export
I have a django app I am working on and in the admin page, I'd like to be able to export a model's list view as csv, xls and multiple other file formats. I'm using django-import-export package for that. I have installed and added it to my installed apps in settings.py. In my models.py I have.. class Student(models.Model): firstname = models.CharField(max_length=20) middlename = models.CharField(max_length=20) lastname = models.CharField(max_length=20) admission_number = models.CharField(max_length=10) grade = models.CharField(max_length=10) joined = models.DateField(auto_now_add=True) def __str__(self): return f'{self.firstname} {self.lastname}' My admin.py file class StudentAdmin(admin.ModelAdmin): list_display = ('firstname', 'lastname', 'admission_number', 'grade', 'joined') list_filter = ('grade', 'joined',) admin.site.register(Student, StudentAdmin) To handle the import and export functionality, I have created a file in the same directory called resource.py where I have the following django-import-export specific code. from import_export import resources from import_exports.fields import Field from .models import Student class StudentResource(resources.ModelResource): full_name = Field(column_name='name') class Meta: model = Student fields = ('full_name', 'admission_number', 'grade', 'joined') widgets = { 'joined': { 'format': '%d/%m/%Y}, } def dehydrate_full_name(self, student): return f'{student.firstname} {student.middlename} {student.lastname}' As you can see from the above code, I have created a new field full_name which I want to hold the full name of a student under the column name and I'd … -
AUTH_USER_MODEL refers to model 'core.User' that has not been installed
I hope you are very well. Since a few hours ago I have an error in extending the "User" model of Django, this with the intention of adding some fields for different users. To extend the model I relied on two main sources: The Django repository on Github - https://github.com/django/django/blob/master/django/contrib/auth/models.py and from a Blog - simpleisbetterthancomplex - https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractbaseuser Django version = 2.1 At the time of running the command - python manage.py makemigrations, I got the following error: "AUTH_USER_MODEL refers to model '% s' that has not been installed"% settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'core.User' that has not been installed When wanting to define in settings.py - AUTH_USER_MODEL = 'core.User' And yes, I have an application called "core" that is already in the INSTALLED_APPS settings.py import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')]) # Application definition DJANGO_APPS = … -
How to insert a second model into my ListView
views.py from django.shortcuts import render, get_object_or_404 from library.models import Game from .models import Post from django.views.generic import ( ListView ) from django.template import context # Create your views here. def home(request): context = { 'recent': Game.objects.all().order_by('post__date_posted')[:5], 'posts': Post.objects.all() } return render(request, 'main/home.html', context) class TitlePostListView(ListView): model = Post template_name = 'main/title_posts.html' context_object_name = 'posts' def get_queryset(self): title = get_object_or_404(Game, title=self.kwargs.get('title')) return Post.objects.filter(game=title).order_by('-date_posted')[:5] title_posts.html {% extends "main/base.html" %} {% load static %} {% block styles %} <link rel="stylesheet" type="text/css" href="{% static 'main/title_posts.css' %}"> {% endblock styles %} {% block content %} <style> body { background-image: url("{{ game.cover_display.url }}"); background-repeat: no-repeat; background-size: 100% 1000px; background-color: #171717; } </style> <div class="container margin-top-300"> <div class="row justify-content-center"> <div class="col-3 text-center"> <img src="{{ game.cover.url }}"> </div> <div class="col"> <p>{{ game.description| safe }}</p> </div> </div> <hr> {% for post in posts %} <div class="row"> <div class="col-4 article-column-height text-center"> <a href="#"><img class="article-image-height" src="{{ post.article_image.url }}"></a> </div> <div class="col-8 article-column-height"> <h2><a class="article-title" href="#">{{ post.article_title }}</a></h2> </div> </div> <hr> </div> {% endfor %} {% endblock content %} models.py class Post(models.Model): article_title = models.CharField(max_length=60, default="Article Title Place Holder") content = HTMLField(default="Article Content Pace Holder") date_posted = models.DateTimeField(default=timezone.now) game = models.ForeignKey('library.Game', on_delete=models.CASCADE) article_image = models.ImageField(default='/media/default.png') class Game(models.Model): title = models.CharField(max_length=100) description = … -
how to find a dictionary value in django template
I have a dictionary. {21: [<Trade: SPY 190204C00271000>], 20: [<Trade: SPY 190201P00265000>]} I wrote a filter to get the value from dict in Django template. from django import template register = template.Library() @register.filter def tradeItem(inputs, i): return inputs.get(i) in the template: {{ openTrades|tradeItem:trade.trade_number }} Now I am able to get this specific trade. but I need to get value of trade.price. how do i do that? I tried. {{ openTrades.price|tradeItem:trade.trade_number }} {{ (openTrades|tradeItem:trade.trade_number).price }} -
How to access parent information in the tamplate in django
<option value="">---------</option> {% for item in Book %} <p>item.name</p> <option value="{{ item.pk }}">{{ item.author }}</option> {% endfor %} A Book has a parent Library so my question is if it's possible to render a field inside of the library model {{item.libraryfied}} - {{ item.author }} -
django userform not showing in HTML page
I am new to django . here I want to register user and I have a problem , the user form doesnt show in registration html page here is my code: views.py : enter code here from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views import generic from django.views.generic import View from .forms import UserForm from .models import Album class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned (Normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # return user objects if info r correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('music:index') return render(request, self.template_name, {'form': form}) form.py : from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] I think there is nothing wrong with url.py as long as the page pops up, I dunno where I'm mistaken -
Django Not found favicon.ico
I just made a new django project but i cant seem to get past the original django site. On my command prompt i just get Not found favicon.ico. Doing some digging apprantly its something the browser looks for but isnt there?. Ive seen some suggestions but i dont quite understand them. One said put it in your static directory but i dont have one? Ive tried something like this from django.views.generic import RedirectView url_patterns=[ ... url(r'^favicon\.ico$',RedirectView.as_view(url='/static/images/favicon.ico')), ] i apoligise for the poor formatting i clicked the {} icon but i cant get the code to format right. Anyway that does not work i get a url not defined error?. Any help would be appreciated. Im very new at this so talk to me like im 5 -
Django how best to perform api request for large jobs
I need some direction as to how to achieve the following functionality using Django. I want my application to enable multiple users to submit jobs to make calls to an API. Each user job will require multiple API calls and will store the results in a db or a file. Each user should be able to submit multiple jobs. In case of some failure such as network blocked or API not returning results I want the application to pause for a while and then resume completing that job. Basically want the application to pickup from where it was left off. Any ideas as to how I could implement this solution or any technologies such as celery I should be looking at or even if you can suggest an opensource project where I can learn how to perform this would be a great help. -
Can't upload a BytesIO file to Google Cloud Storage (Django)
I'm using Django with django-storages to save images to Google Cloud Storage. But I'm getting an error anytime I try to upload a resized image. My model contains def save(self, force_insert=False, force_update=False, using=None, update_fields=None): image_asset = img.open(self.image) image_name = uuid.uuid4() image_asset.thumbnail((1200, 1200), img.ANTIALIAS) fi_io = io.BytesIO() image_asset.save(fi_io, format='JPEG', quality=90) self.image = InMemoryUploadedFile( fi_io, 'ImageField', '%s.jpg' % image_name, 'image/jpeg', sys.getsizeof(fi_io), None ) super(Image, self).save(force_update=force_update) Whenever I attempt to save an image I get this error (the exact size depends on the file uploaded): ValueError: Size 3984 was specified but the file-like object only had 3862 bytes remaining. Without this code, the image saves fine. Also when switching to an S3 storage this exact code works without a problem. -
Presented with TemplateDoesNotExist error
I have made two files market.py crypto.html The code in market py draws data from two API addresses and it is supposed to show them in crypto.html when I run the server and try to open crypto.html I'm presented with TemplateDoesNotExist at /crypto/ as other posts on sof have explained I tried to tinker with INSTALLED_APPS = [ however I cannot get the page to function. market.py import requests, time from django.shortcuts import render class CryptoData: def __init__(self): self.usd_url = "https://api.coingecko.com/api/v3/coins/markets?" \ "vs_currency=usd&order=market_cap_desc&per_page=250&page=1" \ "&sparkline=false&price_change_percentage=24h" self.gbp_url = "https://api.coingecko.com/api/v3/coins/markets?" \ "vs_currency=gbp&order=market_cap_desc&per_page=250&page=1" \ "&sparkline=false&price_change_percentage=24h" self.previous_request = None self.results1 = None self.results2 = None def get_crypto_data_dict(self, seconds_to_wait=60): crypto_dict = dict() if not self.previous_request or self.previous_request + seconds_to_wait < time.time(): print("requested", self.previous_request, time.time()) self.previous_request = time.time() crypto_dict = dict() requests1 = requests.get(self.usd_url) self.results1 = requests1.json() requests2 = requests.get(self.gbp_url) self.results2 = requests2.json() for i in range(0, 250): crypto_dict[self.results1[i]['id']] = { 'coin_name': self.results1[i]['name'], 'changes': self.results1[i]['price_change_percentage_24h'], 'usd': self.results1[i]['current_price'], 'gbp': self.results2[i]['current_price'] } return crypto_dict crypto_data = CryptoData() def crypt_view(request): context = { 'crypto_data': crypto_data.get_crypto_data_dict() } return render(request, 'crypto.html', context=context) crypto.html {% extends "blog/base.html" %} {% block content %} <ul> {% for crypto_datum, crypto_value in crypto_data.items %} <li>{{ crypto_datum }} <ul> {% for info, value in crypto_value.items %} <li>{{ … -
Django version (2.0.7) urlpatterns syntax
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('signIn', views.signIn, name='signin'), path('postsign', views.postsign, name='postsignin'), This is my urls.py from django.shortcuts import render import pyrebase config = { 'apiKey': "AIzaSyD0FzXtqNRhTCKmiGy0e-WGbsEAkP3Yaj0", 'authDomain': "cpanel-99cff.firebaseapp.com", 'databaseURL': "https://cpanel-99cff.firebaseio.com", 'projectId': "cpanel-99cff", 'storageBucket': "cpanel-99cff.appspot.com", 'messagingSenderId': "150154691173" } firebase = pyrebase.initialize_app(config) auth = firebase.auth() def signIn(request): return render(request,"signIn.html") def postsign(request): return render(request,"welcom.html") This is my views.py But whenever i'm giving the command "python3 manage.py runserver" on terminal i'm getting the following error Page not found at/signin <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>signIN</title> </head> <body> <form action="/postsign/" method="post"> {% csrf_token %} Email: <input type="email" name="email"> Password: <input type="password" name="password"> <input type="submit" value="SignIn" > </form> </body> </html> This is my signIn.html which is in templates folder <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>welcome</title> </head> <body> {% csrf_token %} Welcome </body> </html> This is my welcome.html which is also in the templates folder Please help me ! -
Is CPanel a good place to deploy a django site?
So I'm looking for an easy but also cheap way to deploy the eCommerce site I built for my family's take-out restaurant. I've tried the free Heroku account, but I find the 30min no activity shut-down annoying. So I'm looking at other options. I just found out that the CPanel hosting we already have can host a django site. But since everyone I've asked for recommendations says to either use a VPS or PaaS, and nobody has experience doing it via CPanel. Does anyone know if it's a good option since the hosting has already been paid up for the next 2 years? EG is it secure? Do I have to change my code to suit the MySQL database? -
django background task interval (miliseconds)
I want to create a system which backend will monitor for buttons states (Hardware buttons) changes. Each state change will be forwarded to upper layers (eg interface) using django channels 2.0. And in other way round -> pressing button on web interface will end up with turning on/off device by backend. I have two upcoming issues related to this conception: django-background-task minimum time interval is 1 second which is way to long. I want have something like 100 ms. is there any way to embeed threads in django application (if cant use background-task) Thanks for all support -
Can small changes be made to the built-in registration and login system?
So Django's built in registration, login, and database fit everything almost everything I need for my application, however, I need a boolean parameter in the database to determine if a user has permission to do something. Am I able to add this to the database while still being able to use the built-ins? -
Using requests library and django rest framework
I have one general question, so please bare with me. I need to use requests inside drf create method, I'm doing something like this def create(self, request): serializer = CustomSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() sort_serializer = json.dumps(serializer, indent=2, sort_keys=True) response = requests.post( url='{}/action'.format(URL), json=sort_serializer, headers=headers ) print("Response ", response) return Response({'response': response}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is this fine, somehow this looks totally wrong, I don't have any errors from drf but still, what is the best practice here? -
Django Management Command argument taken as a dictionary
I need to run a Custom Django Management Command (module named populate_db.py) included in a management/commands directory. It populates a database. The command takes a mandatory argument obtained as a dictionary from execution of another program named formDict.py So I want a one line command which will run formDict.py and consecutively take its result as an argument for my Custom Django Management Command python manage.py populate_db. Is it possible to form such a command in the way I described? -
Can't import: 'unable to import rest_framework' when importing serializer? (windows)
I have 'rest_framework' in my INSTALLED_APPS of settings.py and I can import it with no problem in cmd But I receive an "Unable to import 'rest_framework'" message I can import rest_framework no problem in my cmd prompt, so I really have no idea what the issue is? -
Django: form validation errors on form creation
Let's say I have a Django form with ChoiceField: class MyForm(forms.Form): name = forms.CharField(label="Name", required=True) some_object = forms.ChoiceField(label="Object", choices=[(0, '-----')] + [(x.id, x.name) for x in Obj.objects.all()]) Choisefield is being initialized with list of objects headed by 'empty choice'. There is no object with pk=0. In that form I have a clean() method: def clean(self): if not Obj.objects.filter(self.cleaned.data['some_object'].exists(): self.errors.update({'some_object': ['Invalid choice']}) It works well when I'm sending a form to a server, if data in it doesn't match conditions, field.is_valid returns False and I render form with error messages. But, when I create an empty form like this: if request.method == 'GET': data = {'name': 'Untitled', 'some_object': 0} form = MyForm(data) return render(request, 'app\template.html', {'form': form}) Django renders form with error message ('Invalid choice') even though form was just created and 'Object' select was intended to be set in empty position. Is it possible to disable form clean() method in specific cases? Or maybe I'm doing this all wrong? What is the best practice to create an empty form? -
Why do i get an Attribute Error when trying to assign the file to a Model.form??)
In my django project i am trying to generate a new edited file out of existing ones, so when i am editing the file and trying to save it to a new model called FileField it says AttributeError at /my_blanks/2/ 'str' object has no attribute 'get' . I need to save or asign my edited document and the name of it to my Model.forms so i can handle it later (download, upload), Can you Help me please? To solve my task i use DocEdited model then pass it to forms.py models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.core.files.storage import FileSystemStorage from my_pdf.settings import PRIVATE_STORAGE_ROOT # Create your models here. from blanks.validators import validate_file_extension class DocFile(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/', validators=[validate_file_extension]) # uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.description def delete(self, *args, **kwargs): self.document.delete() super().delete(*args, **kwargs) class DocFields(models.Model): doc_fields = models.CharField( max_length=50) fs_edited = FileSystemStorage(location=PRIVATE_STORAGE_ROOT) class DocEdited(models.Model): edited_description = models.CharField(max_length=250, blank=True) document_edited = models.FileField(upload_to='documents_edited/', storage=fs_edited) def __str__(self): return self.edited_description Here i use EditedDocumentForm class to make a ModelForm, and then i pass it to my views.py edit_files function , last 6 lines. forms.py from django import forms from .models import … -
sendgrid is messing with my django models in views file
In my views file, I add a feedback function that send email, I import this: import sendgrid import os from sendgrid.helpers.mail import * from django.conf import settings In the same file, I have this views: def post_by_category(request, category_slug): category = get_object_or_404(Category, slug=category_slug) posts = get_list_or_404(Post.objects.order_by('-id'),category=category) posts = pg_helpers.pg_records(request, posts, 3) context = { 'category':category, 'posts': posts, } return render(request, 'blog/post_by_category.html', context) The post_by_category would raise an error type object 'Category' has no attribute 'model' when it tries to get_object_or_404(Category, slug=category_slug) because queryset is this kind of category: <class 'sendgrid.helpers.mail.category.Category'> If I remove the import, it works normally, but I would like to be able to send email from feedback of users. What can I do? Rename the Category? -
Django UserCreationForm on homepage
I'm trying to create a usercreationform on the homepage of my website. After reading and watching tutorials on user creation I noticed everyone creates a separate HTML page for "signup", however, I want my signup page to be directly on my homepage - is this a possibility? I'm finding it difficult to understand with 'accounts' having its own separate app, as well as the homepage having its own app, which I have called mine 'game'. Do both apps have to be separate? Am I able to make the accounts app my main 'homepage' app? Can anyone recommend any tutorials on this? I think I should also mention I'm quite new to django. Thank you. My homepage app (titled game) urls.py from django.contrib import admin from django.urls import path from.import views urlpatterns = [ path('', views.game_start), ] views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from .models import Game def game_start(request): games = Game.objects.all().order_by('date') # grabs all records in game in db table, order by date return render (request, 'game/game_start.html', {'games':games}) def signup_view(request): form = UserCreationForm() return render(request, 'game/game_start.html', {'form': form}) accounts app urls.py from django.conf.urls import url from .import views app_name = 'accounts' urlpatterns = [ path('', game_views.game_start, name="home"), … -
How to add a contact form template into another template?
I'm very new to this and I'm trying to create a simple website for a company using django 2. I'm using this template that is a single page: https://html5up.net/astral I want to make the contact form work but I can't manage. I've tried putting {% block %} {% endblock %} in the HTML file but it won't render the form, {% include %} renders the html file I created but not the form. I was wondering if it is possible to make the form that is already rendered work. Thanks! -
Django - Models: for loop in query/filter
I have a list of reviews and each review has a rating average. My problem is trying to added each review id to the filter for the query result. For this, I assume a for loop in the filter is best. I've found a previous post with a similar situation, but the same result doesn't seem to be working for me. When I load my reviews page, I receive a TypeError: 'function' object is not iterable. Here is my view.py file with the queries. def reviews(request): context = { 'reviews': Employee.objects.all(), 'rating': Employee.objects.filter(id__in=[review.id for review in reviews]).aggregate(rate=Avg(F('value1')+F('value2')+F('value3').....+F('valueN'))/N) } return render(request, 'reviews/reviews.html', context) Reviews.html template. {% extends "reviews/layout.html" %} {% block content %} {% for review in reviews %} {% for rating in ratings %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ review.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <h4 class="mr-2">{{ review.company }} {{rating}}</h4> <small class="text-muted">{{ review.date_posted|date:"F d, Y" }}</small> </div> <h5><a class="article-title" href="{% url 'review-detail' review.id %}">{{ review.title }}</a></h5> <p class="article-content">{{ review.content }}</p> </div> </article> {% endfor %} {% endfor %} {% endblock content %} Any suggestions are much appreciated. -
Is there an equivalent of django-hitcount template tags but for views?
I am using django-hitcount and am stumped on counting hits within the views.py for my app. The documentation suggests using this from hitcount.models import HitCount from hitcount.views import HitCountMixin # first get the related HitCount object for your model object hit_count = HitCount.objects.get_for_object(your_model_object) # next, you can attempt to count a hit and get the response # you need to pass it the request object as well hit_count_response = HitCountMixin.hit_count(request, hit_count) # your response could look like this: # UpdateHitCountResponse(hit_counted=True, hit_message='Hit counted: session key') # UpdateHitCountResponse(hit_counted=False, hit_message='Not counted: session key has active hit') However, I am not looking for responses to a HitCount object. I only want to count the hits in a similar manner to how the template tags provide, like this {% get_hit_count for [object] within ["days=1,minutes=30"] %} How exactly do I get the hit count for an object in a given timeframe inside of the views.py ?