Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ensure that the database in django is created with utf8 collation
I created a database with wrong collation (not utf8) and I want django to report that on startup. How to do this a cleaner way. I can always do some hack like checking try: User.objects.filter(first_name__iexact="ÎÂhello") except OperationalError: print "Exit startup..." Is there a better way ! -
Numbers saved in Django session automatically rounded down when computing item sub totals
I have pricing data saved in my model like: price = models.DecimalField(max_digits=12, decimal_places=4, default=None) When I render the numbers, they show up as expected: 12.0, 10.75 etc. When I attempt to calculate totals and subtotals for items in my cart, it rounds down anything with a decimal point. So when I am trying to get a total for 2 items at $10.75, it will give me $20 when I want $21.50. How can I fix this? I figure it has something to do with the way I'm saving it to sessions. Here is my sessions data: class Cart(object): def __init__(self, request): self.session = request.session if not hasattr(settings, 'CART_SESSION_KEY'): raise KeyNotSet('Session key identifier is missing in settings') if not hasattr(settings, 'PRODUCT_MODEL'): raise KeyNotSet('Product model is missing in settings') cart = self.session.get(settings.CART_SESSION_KEY) if not cart: is_model_set = hasattr(settings, 'USE_CART_MODELS') if is_model_set and settings.USE_CART_MODELS: # cart = pass else: cart = self.session[settings.CART_SESSION_KEY] = {} self.cart = cart def add(self, product, price, quantity=1,): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'price': int(price), 'quantity': 0} self.cart[product_id]['quantity'] = int(quantity) self.save() self.cart[product_id]['quantity'] = int(quantity) self.save() def save(self): self.session[settings.CART_SESSION_KEY] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del … -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.User' that has not been installed
I know this specific topic has quite a few posts but I've tried most solutions to no avail. I'm working with Django-Rest Framework with a cassandra backend. Once I got to implementing user models I realized that cassandra lacked support for auth in general. I went through the steps to create a mysql db specifically for users and then started extending the user model. Whenever I try to do anything with migrate.py I get the exception django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.User' that has not been installed here are the relevant files settings.py from datetime import timedelta import os from os.path import abspath, basename, dirname, join, normpath from sys import path #from djcelery import setup_loader ########## PATH CONFIGURATION # Absolute filesystem path to the Django project directory: DJANGO_ROOT = dirname(abspath(__file__)) # Absolute filesystem path to the top-level project folder: SITE_ROOT = dirname(DJANGO_ROOT) # Site name: SITE_NAME = os.getenv('SITE_NAME', 'project') # Add our project to our pythonpath, this way we don't need to type our project # name in our dotted import paths: path.append(DJANGO_ROOT) ########## END PATH CONFIGURATION ########## DEBUG CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = True if os.getenv('DEBUG') == 'true' else False # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug TEMPLATE_DEBUG = DEBUG TEST_RUNNER = … -
Jquery-ui is not working. Just getting "Uncaught TypeError: Cannot read property 'ui' of undefined"
I am working on Django admin to customize it. Django version is 1.4, it's using too low jquery version(1.4.2). So I updated it by using: def media(self): extra = '' if settings.DEBUG else '.min' return forms.Media(js=[ 'device42/raw_id_asset/js/jquery-1.10.2.min.js', 'admin/js/jquery.init.js', 'device42/raw_id_asset/js/jquery-ui.1.10.2.min.js', 'device42/raw_id_asset/js/raw_id_field.js' ]) After loading, jquery version updated to 1.10.2. But I am getting this error: Uncaught TypeError: Cannot read property 'ui' of undefined I am not sure why jquery ui is not working well. It seems I'd imported compatible version of jquery(1.10.2), but getting this error in loading jquery-ui. Is this something you faced before? -
HTML Sanitizer - Safe to Whitelist Span?
When I underline a word in tinymce, I want the output to be underlined, but the output is span style="text-decoration: underline;">underline /span> I'm using django-bleach. It works for bold and italic and list elements. When I whitelist 'span' in settings.py (shown below), it works for underline as well. But is it safe to whitelist the 'span' html tag in settings.py? BLEACH_ALLOWED_TAGS = ['p', 'b', 'i', 'u', 'em', 'strong', 'a', 'ul', 'li' #,'span' ] Is there a smarter way to display underlined content? Thanks in advance for the help! -
How to have multiple Httpresponses in an array that I can iterate over using buttons
I want to show some sort of slideshow of various HttpResponse objects and iterate through them using buttons. Is this possible in Django? -
How can I use Zoomslider in django?
I'm new to django and jquery, how can I use Zoomslider in Django?? When i try to use data-zs-src='["images/2.jpg", "images/1.jpg", "images/3.jpg"]' it shows an error that those images are not found. could anyone help me out with this please. -
NoReverseMatch error Django with slug
I'm trying to make the index view show a list of "Journal"s, with each linking to a view that lists "Manuscripts" in the Journal. I also want journal_view to be located at a slug for the name of the journal, and likewise for manuscript_view. This is the traceback I get: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/journals/ Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['social_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'journal.apps.JournalConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template ... error at line 8 Reverse for 'view_journal' not found. 'view_journal' is not a valid view function or pattern name. 1 : {% load static %} 2 : 3 : <link rel="stylesheet" type="text/css" href="{% static 'journal/style.css' %}" /> 4 : 5 : {% if journal_list %} 6 : <ul> 7 : {% for journal in journal_list %} 8 : <li><a href=" {% url journal.get_absolute_url journal.slug %} ">{{ journal.title }}</a></li> 9 : {% endfor %} 10 : </ul> 11 : {% else %} 12 : <p>No journals are available.</p> 13 : {% endif %} ...(Traceback)... Exception Type: NoReverseMatch at /journals/ Exception Value: Reverse for 'view_journal' not found. 'view_journal' is not a valid view function or … -
Django REST Framework: email+password token-based authentication for one to one custom user
I need help with token-based authentication for a custom user model. I have a User model that inherits from AbstractBaseUser: class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, blank=True, null=True) USERNAME_FIELD = 'email' I have a DojoMaster model that extends the User model and am using a post_save receiver: models.py class DojoMaster(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) phone = models.BigIntegerField() country = models.ForeignKey(Country, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) I have added the following authentication classes: settings.py REST_FRAMEWORK = { 'Default_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } To access token authentication I have: urls.py urlpatterns = [ url(r'^get-token', obtain_auth_token) ] I have the following DojoMaster user: { "user": { "name": "XYZ", "email": "xyz@mail.com", "password": "p@55w0rd" }, "username": "iAmXYZ", "phone": 2685211, "country": 575 } When I try to get the authentication token with {"email": "xyz@mail.com", "password": "p@55w0rd"} I get a Status 400 error {"username": ["This field is required."]} When I use {"username": "xyz@mail.com", "password": "p@55w0rd"} I get a Status 400 error {"non_field_errors": ["Unable to log in with provided credentials."]} I tried using advice from posts such as this and this. How can I use email+password to perform token-based authentication for such a … -
Django REST Framework url link - Could not resolve URL for hyperlinked relationship
Newbie in Django REST framework and seems I'm missing some basics. Have read back and forth hundreds of questions here and on the web, yet can't find where the issue is. The aim is to have well linked and easy to explore REST api (clickable), like an example demonstrated as part of https://github.com/encode/rest-framework-tutorial. Any hints are more than welcome, as I'm pulling my hairs and can't find a working solution. class GroupManager(models.Manager): use_in_migrations = True def get_by_natural_key(self, name): return self.get(name=name) class Group(models.Model): name = models.CharField(_('name'), max_length=80, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) objects = GroupManager() class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __str__(self): return self.name def natural_key(self): return (self.name,) class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer Above results in very nice linked REST api with automatically generated URL which is clickable and takes to instance details: enter image description here enter image description here Trying to replicate it with my very simple model defined as below fails misreably: class Author(models.Model): name = models.CharField("Authorist", max_length=20) def get_by_natural_key(self,name): return self.get(name=name) def __str__(self): return self.name def natural_key(self): return (self.name,) class Book(models.Model): title = models.CharField("Tytuł",max_length=100) autorek = models.ForeignKey(Author,related_name='knicha',on_delete=models.CASCADE) … -
Django project not recognising Numpy Dependency
my django project does not recognise my numpy and pandas dependencies.I have installed numpy and pandas through pycharm but for some reason they are not recognised. I run my project through the terminal by doing "python3 manage.py runserver"in the desired directory where I have saved the numpy and pandas libraries. Here is my code: from django.shortcuts import render,get_object_or_404 from django import forms import pandas as pd def read_excel(ExcelFileName): File = pd.read_excel(ExcelFileName) return File template_name1 = 'multiplication/detail.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) def multiply_two_integers(x,y): return x*y def my_view(request): read_excel if request.method == 'POST': form = myForm(request.POST) if (form.is_valid()): x = form.cleaned_data['quantity1'] y = form.cleaned_data['quantity2'] product = multiply_two_integers(x, y) multiplied = True return render(request, template_name1, {'form': form,'product': product, 'multiplied': multiplied }) else: multiplied = False form = myForm() return render(request,template_name1,{'form': form, 'multiplied': multiplied} ) Here is the error I am getting: in <module> from multiplication import views File "/Users/NikolasPapastavrou/firstProject/multiplication/views.py", line 11, in <module> import pandas as pd File "/Users/NikolasPapastavrou/firstProject/pandas/__init__.py", line 19, in <module> "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] Please help me understand what is wrong with my project. Find attached an image of all the libraries I am using. -
Examples for using SAML Authentication against a G-Suite IDP for a Django app running in Google App Engine
I'm trying to get a Django (on Python3) app (running in GAE, though that shouldn't matter a lot) authentication using SAML. There seem to be a couple of packages available - python-social-auth, django-saml2-auth (required metadata.xml to be accessible by URL, which G-Suite doesn't support) and onelogin's python-saml (requires python2). I can't find a simple or well-documented way to achieve this. I've deployed some external SAML apps and have a general understanding of the process, but the terminology seems to differ between vendors, and I don't have a massive interest in learning SAML in detail as the existing libraries seem to require. Does anyone have any pointers? -
Django - media files not being shown on website
I've got a problem with user uploaded content not showing up on webpages. I have this working 100% on using my development settings.py file, but this doesn't work on my live site. A couple of notes My static files are working 100% on my live site. When a user uploads content on my live site, the file posts to the correct folder (i.e. the folder that I've specified in my settings.py file) When the webpage is rendered, and the broken link is investigated, to me, it looks like the link is correct. In other words, the image exists at the link indicated. Here are my media settings in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = '/home/jasonhoward/webapps/site_media/' If a user uploads cat.jpg, I've confirmed that it successfully saves to '/home/jasonhoward/webapps/site_media/' Now, when the user navigates to the image gallery on their profile, what should appear is the image of the cat. Instead, a broken link appears. The address of the image is '/media/cat.jpg' as per Chrome Inspect tool. To me, the link address seems correct and the image should be displayed. It's almost like the file path is correct, but the system is restricting access to this image for some reason. Is … -
Django UNIQUE constraint failed: Site_coach.user_id
I'am developing a website in Python Django. I have a template Register.html with a function "Register" I would like that my users put their additional informations on this page after they registered on an another page. My problem is when my users put their additional informations for the first time in my form it work but then if my users want to update their informations from the same form on the same page, they receive an error "UNIQUE constraint failed: Site_coach.user_id" I'am a beginner. Can you help me to fix this error ? My view.py from django.shortcuts import render from .forms import RegisterForm def Register(request): form = RegisterForm(request.POST or None, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user form.save() return render(request, 'Register.html', {'form': form}) My Site/models.py class coach(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) Telephone = models.IntegerField() TestResult = models.IntegerField(null=True, blank=True) Level = models.TextField() My users/models.py from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): objects = CustomUserManager() -
Issue with Django migrations when deploying in Prod via AWS Beanstalk
I am struggling with Django migrations when deploying into several environments. I have the following ones: Dev locally on my laptop with sqlite3 database Test in AWS (deployed via Beanstalk) connected to AWS RDS Production Database Prod in AWS (deployed via Beanstalk) connected to AWS RDS Production Database. My workflow is once I have done my dev locally, I deploy to the Test instance, which should make the backward compatible changes to the prod database, where I run my tests, before deploying to the Prod instance. In my .gitignore, I have excluded all the migrations folder as when I used to apply the same migrations I created in dev, it lead to some inconsistencies and errors during deployment. I thought it would be cleaner to recreate the migrations on the test or prod servers when deploying. In my .ebextensions I then have the following config that are executed when deploying the application: 01_makemigration: command: "source /opt/python/run/venv/bin/activate && python manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: true However when I deploy to the Test platform after having made changes to my models, the migrations don't seem to happen. I have tried to run … -
Django tutorial: reverse for 'detail' not found. 'detail' is not a valid view function or pattern name
I was following the Django tutorial when I got this problem. I tried to copy paste and to read the tutorial again and again but I can't fix it. The error is: "Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name." views.py: from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Choice, Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', null=True) def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] index.html <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action={% … -
Advanced search in Django using python
I am currently working on django. Now, I want achieve the advanced search, to be more specifically, achieve precise searching using imprecise key words. For example, when I type 'a$c', all the matching results will be 'ac', 'abc', 'a!c', 'Ac', 'AC' and so on. Basically, '$(or maybe other characters)' could be numbers, could be letters or nothing. Is there any method to do this? BTW, my code for achieving the basic search function is written as below: class MetaboliteAdmin(admin.ModelAdmin): search_fields = ['id', 'name', 'compartment', 'charge', 'formula'] class ReactionAdmin(admin.ModelAdmin): search_fields = ['id', 'name','metabolites', 'gene_reaction_rule', 'subsystem'] class GeneAdmin(admin.ModelAdmin): search_fields = ['id', 'name', ''] Thank you guys for helping me! -
How to have dropdown selection populate table in template from Django model?
Hopefully I can get some help with this. I've basically got a page on my site with a table, and the table is populated from the database with my models. My problem, is that I'd like to have a dropdown, where the user can select what data they want to see. I know that I need to use a django form in order to do this, but I've been searching, and have been having a really hard time finding what I need to do. The table is made with DataTables, and a bit of BS4 styling. Right now, I have the table being populated with just one of my models (Model1) and that's working great, but I'm not sure how to do what I want to do with making a selection from the dropdown, to populate with a different model. I kinda understand how forms work, but I'm not sure how to implement them how I want to. A lot of the stuff I see is just showing how to do a form with one model. Any sort of example, or guidance would be greatly appreciated :) Here's my models.py: class Model1(models.Model): date = models.DateTimeField(db_column='Date', primary_key=True, default='', max_length=40) data1 = … -
Django: How to use a PIL byte array conversion inside a ListView get_queryset?
This is my relevant view.py: class PersoListView(ListView): template_name = 'sconsult/search.html' context_object_name = 'search_list' def get_context_data(self, **kwargs): context = super(PersoListView, self).get_context_data(**kwargs) context['count'] = self.get_queryset().count() return context def get_queryset(self): get_search = self.request.GET.get('q') if get_search is not None: perso = File.objects.select_related().filter(citid__persoid=get_search,file__id='1').values('citiid__name', 'citiid__lastname', 'citid', 'file__image') return perso and this is my relevant search.html template: {% for person in search_list %} <div class="col-sm-5 col-lg-2"> <div class="thumbnail"> <a href="{% url 'sconsult:detail' person.fileid %}"> <img src="{{ person.file__image}}" class="img-responsive"></a> <div class="col-sm-14"> <div class="caption"> <h2>{{ person.citid__name }} {{ person.citid__lastname }}</h2> <a href="{% url 'sconsult:detail' person.citid %}" class="btn btn-primary btn-sm" role="button">Ver Detalles</a> </div> </div> </div> </div> {% endfor %} This field 'file__image' is in bytearray inside the database: I know it's not the best idea, but that's what found. Now I found out The image can easily be opened with the from PIL import Image import io variable = "Image.open(io.BytesIO(object))" variable.show() I don't know how to put that code inside the ListView, because if I use it on the perso variable, then the ListView does not pass the other fields to the template. How do I get only the file_image converted? Any help is appreciated. -
How to get the i'th item in an iterable object. Django/Python
In my Django/Python application I am passing multiple iterable objects from views.py to index.html. I am essentially trying to make a standard for loop in which you can get an item by its index. Once I am iterating through the first object, how can I get the respective index of another iterable in that same loop? Conditions: All of the arrays will always be equal in length, but their length will change on a daily basis. views.py name = ['John', 'Kim', 'Tim', 'Jill'] age = ['20', '30', '52', '27'] state = ['IN', 'IL', 'CA', 'TX'] city = ['Muncie', 'Champaign', 'Fresno', 'Dallas'] def index(request): args = {'names': name, 'ages': age, 'states': state, 'cities': city} return render(request, 'index.html', args) index.html {% extends 'base.html' %} {% load staticfiles %} {% block Data %} {% for name in names %} <p>{{ name }}</p> <p>{{ age.forloop.counter0 }}</p> <p>{{ state.forloop.counter0 }}</p> <p>{{ city.forloop.counter0 }}</p> {% endfor %} {% endblock %} As you can see, I thought I would use 'forloop.counter0' as my index. But it doesn't work that way apparently. Any suggestions on how to achieve this goal? Thanks in advance! -
How could i use custom manager of the related model, when using select_related?
For example, I have models as, class ModelBManager(models.Manager): def get_queryset(self): return self.super().get_queryset().select_related('y') class ModelA(models.Model): x = models.TextField() class ModelB(models.Model): y = models.ForeignKey(ModelA) objects = ModelBManager() class ModelC(models.Model): z = models.ForeignKey(ModelB) Now, if i do ModelC.objects.get(id=1).z i would get the ModelB instance with a prefetched ModelA instance( ModelBManager worked). But if i do ModelC.objects.select_related('z')[0].z, there would be no prefetched ModelA instance with ModelB instance.(Basically ModelBManager did not work!) Anyone has any idea how can i achieve this? Thanks -
Django: Cannot assign "'prof'": "coach.user" must be a "CustomUser" instance
I'am developing a website in Python Django. I have two "class CustomUser" it is used in order to login and another "class coach", this class contains information about users. I need to match these two class. My website identify the user who is logged in but it fail to assign this user a coach class. When I try to submit my form I receive the error "Cannot assign "'prof'": "coach.user" must be a "CustomUser" instance." I'am a beginner in Python Django. Can you help me to resolve this problem ? This is Site/models.py class coach(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) Telephone = models.IntegerField() Level = models.TextField() Study = models.TextField() This is my users/models.py from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): objects = CustomUserManager() This is my Site/views.py there I have a function which find the user and assign him a coach class. def Register(request): form = ContactForm(request.POST or None, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user.username obj.save() form.save() return render(request, 'Register.html', {'form': form}) -
How to update JSON objects in my Django app?
I have a json file in my products/fixtures/products.json. I am adding additional models to it, but it is never updated in my application. How can I get it to where they will actually update in the webview? This is the json file I have: [ { "model": "products.product", "pk": 6, "fields": { "title": "Anti Gravity Magnetic Levitation Science Kit", "slug": "Anti Gravity Magnetic Levitation Science Kit", "description": "This science kit teaches kids about magnetic force through several fun, hands-on experiments.", "price": "14.73", "image": "static_my_proj/img/470776354.png", "featured": false, "active": true, "timestamp": "2017-09-18T19:29:03.347Z" } }, { "model": "products.product", "pk": 5, "fields": { "title": "T-shirt", "slug": "t-shirt-y7f6", "description": "another one?>?", "price": "39.99", "image": "", "featured": false, "active": true, "timestamp": "2017-09-18T19:29:03.347Z" } } ] and this is my models.py for the products def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): # print(instance) #print(filename) new_filename = random.randint(1,3910209312) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format( new_filename=new_filename, final_filename=final_filename ) class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) def featured(self): return self.filter(featured=True, active=True) def search(self, query): lookups = (Q(title__icontains=query) | Q(description__icontains=query) | Q(price__icontains=query) | Q(tag__title__icontains=query) ) # tshirt, t-shirt, t shirt, red, green, blue, return self.filter(lookups).distinct() class ProductManager(models.Manager): def get_queryset(self): return … -
Django: How to run tests against empty (non populated) database
By running './manage.py test', data from local 'postgres' database are populated into 'test_postgres' database. I am not able to find way, how to disable this behavior. By running './manage.py test', I want to get non populated database with applied migrations. class Local(Common): DEBUG = True # Testing INSTALLED_APPS = Common.INSTALLED_APPS INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ BASE_DIR, '-s', '--nologcapture', '--with-coverage', '--with-progressive' ] # Postgres DATABASES = { 'default': dj_database_url.config( default='postgres://postgres:@postgres:5432/postgres', conn_max_age=int(os.getenv('POSTGRES_CONN_MAX_AGE', 600)), ) } -
Why is this plot not displaying in template but works fine if URL is viewed directly in Django app?
My problem I'm creating an interactive plot in my Django app. I have created a view for a plotting template and a view that generates only the plot itself so that I can use <img src= "{% url 'ozmod:plot' %}"/> to render the plot with the fancy plotting template. If I navigate to the URL I've assigned to the plotting template view I see a broken image link but the navbar and everything is extended fine. If I navigate directly to the URL for just the plot, the plot is displayed fine but, of course, the navbar and everything from page.html is not extended. I have included screen grabs of my error and my code: views.py class PlotView(generic.TemplateView): template_name = 'ozmod/plot.html' def RunOZCOT(request): fig = plt.figure() x = range(20) y = [i for i in range(20)] random.shuffle(y) plot = plt.plot(x,y) g = mpld3.fig_to_html(fig) return HttpResponse(g) urls.py app_name = 'ozmod' urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('metfiles/', views.MetIndexView.as_view(), name='metindex'), path('metfiles/<int:pk>/', views.DetailView.as_view(), name='detail'), path('runmodel/', views.PlotView.as_view(), name = 'runmodel'), path('plot/', views.RunOZCOT, name = 'plot'), ] plot.html {% extends "ozmod/page.html" %} {% block content %} <img src= "{% url 'ozmod:plot' %}"/> <!-- http://myserver:8000/ozmod/plot/ --> {% endblock %} page.html ... abbreviated for clarity {% load …