Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamic queryset
I have a view which can receive from none to four different filter lookups. Let's say it starts with Model.objects.all() and then if filter_option is not None and filter_option != '' the idea is to add that filter to the queryset. Making a lot of ifs is a solution but it's really ugly. This is what I'm trying but I'm not getting the expected behavior: class CourseList(ListView): model = Course paginate_by = 10 def get_queryset(self, queryset=None): q = self.request.GET.get('q') sort = self.request.GET.get('sort') level = self.request.GET.get('level') qs = Course.objects.all() if q is not None and q != '': qs.filter(Q(title__icontains=q) | Q(description__icontains=q)) if sort is not None and sort != '': qs.order_by(sort) if level is not None and level != '': sq.filter(level=level) return qs For each "if true" condition I want those options added to the queryset. But instead I'm just getting Course.objects.all() as result all the time. -
Download zip file from http api in react, Receiving error: "Unable to expand file.zip. It is an unsupported format"
Thanks in advance for taking a look. I am working on being able to download a zip file from react through a django api request. I am able to click on my pop up that downloads the zip file, but when I double click on the zip file to open, I get this error: "Unable to expand file_name.zip. It is an unsupported format" My response with the zip file seems to be passing correctly to the front end, so I am thinking it may be something wrong with the react code when making the "blob"? Thanks again. Django code: class DownloadZip(APIView): def post(self, request, format=None): # information to find file to create zip profile_name = request.data["profile"] profile_year = request.data["year"] # file path to create zips from path = str(Path(__file__).parent.resolve()) zip_dir = shutil.make_archive(profile_name + profile_year, "zip", path + "profile_name") s = io.StringIO(zip_dir) response = HttpResponse(s, content_type = "application/zip") zip_name = profile_name + profile_year + ".zip" response["Content-Disposition"] = f"attachment; filename={zip_name}" return response React code: downloadZip = async () => { const params = { profile: this.state.profileName, year: this.state.year, }; axios({ url: `${serverUrl}/download_zip`, method: "post", data: params }).then( (res) => { const url = window.URL.createObjectURL(new Blob([res.data],{type:'application/zip'})); const link = document.createElement('a'); link.href = url; … -
saving images on a local files with heroku
Hello i am new to django and I am almost done with my first web development but I have this Problem that I noticed. images are not getting saved on the File that is set for saving images on my local PC and therefor I was wondering if its a problem on my part or heroku dose not work like the localhost. I would be thankful for some explaining and thanks Here is some codes of my project: Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], ..... STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' displaying the image on an html {% for topic in result %} <div class="card-mb3"> <div class="card-header" style="background-color:lightgrey"> <table class="table"> <tr> <th>Image</th> <th>Title of the topic</th> <th>Edit</th> <th>Delete</th> </tr> <div class="card-body" style="background-color:white"> <tr> <td> {% if topic.image %} <image src="{{topic.image.url}}" style="width:200px"> upload.html {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <input type="file" name="document"> <button type="submit"> Upload image <i class="fas fa-upload"></i> </button> </form> {% endblock content %} views.py def upload(request): context = {} if request == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'learning_logs/upload.html', context) -
How do I update an object that was made with POST in a React front-end... in a Django backend?
I'm trying to follow a tutorial, these are the videos in the series I watched so far: Part 1 Part 2 (Handling Post Requests) Of course you don't want to watch the videos, so here's the project on GitHub: here My method for handling post requests is pretty much the same as his. It looks like this: class CustomForm extends React.Component { handleFormSubmit = async (event, requestType, profileID) => { const postObj = { user_name: event.target.elements.user_name.value, } if (requestType === "post") { await axios.post("http://127.0.0.1:8000/api/create/", postObj) .then(res => { if (res.status === 201) { this.props.history.push(`/`); } }) } else if (requestType === "put") { await axios.put(`http://127.0.0.1:8000/api/${profileID}/update/`, postObj) .then(res => { if (res.status === 200) { this.props.history.push(`/`); } }) } } So I have a question. What if I did it they way he did it, but instead of just posting to the server (posts happen on form submission)... I want to post to the server AND have my backend start asynchronously updating that posted object as soon as it's posted? How would I go about doing that (based off his / my code [kinda identical] ? The closest thing I can think of is using the views.py file to take in … -
Django is useless can't even update db while saving a form
I am trying to save a form but the db doesn't update whenever I upload. I don't know what's happening. Had some issues with django not getting the user_id or setting it to Null when uploading so I changed my views.py and now nothing happens in the db but the upload seems successful . my views.py: from django.shortcuts import render from .forms import UserProfileForm def index(request): if request.user.is_authenticated: return details(request) else: return render(request, 'soc_auth/index.html') def details(request): if request.method == "POST": form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): current_user = form.save(commit=False) current_user = request.user current_user.save() img_obj = form.instance return render(request, 'soc_auth/details.html', {'form': form, 'img_obj' : img_obj}) else: form = UserProfileForm() return render(request, 'soc_auth/details.html', {'form': form}) forms.py from django import forms from django.core.files.images import get_image_dimensions from soc_auth.models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile #fields = '__all__' fields = ['avatar', 'name', 'description'] def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 1000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', … -
I'm getting an IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id
Im trying to remove the dropdown so that the user can only see his/her username.Image of the author dropdown.[Image that i want to happen][2] The code -
Using django-dbbackup with parameters not working in view
I am trying to make a view for my user to save and restore database using django-dbbackup. I need my user to be able to decide the name of file for saving and the file to be restored using FormView. But commands dbbackup and dbrestore are not accepting parameters when I call them with call_command in view.py, but doing manage.py dbbackup -o mycopy in terminal works. Still learning. error in backup: raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'dbbackup -o mycopy' Is there another way to restore and backup without using terminal? -
Template Not Found
Hey i am new to django and I am almost done with my first project but I am getting a problem when I open my Site with heroku using heroku open in the terminal when the Site open I get an error that my base template is missing. Settings BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] any html {% extends "learning_logs\base.html" %} ......... error TemplateDoesNotExist at / learning_logs\base.html django.template.loaders.filesystem.Loader: /app/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/learning_logs/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/users/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/bootstrap4/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/templates/learning_logs\base.html (Source does not exist) If any other code might help please tell me. -
Django makemigrations not finding tables
I have a Django APP that work perfectly fine. I downloaded the repository from Github to a new laptop, but when I try to run: python manage.py makemigrations runserver etc I get django.db.utils.OperationalError: no such table: catalog_categorias_producto Already tried: Deleted db.sqlite3 Deleted all migration files (except __init__) Tried makemigrations again No difference. Any clues? Thanks! -
Deploy Django Server with a built-in Vue.js App built with Wepback on Heroku
I am stuck in the deployement of a vue.js django together on heroku. I have tried to load the code on heroku and the is deployed correctly. The problem is that the frontend isn't loaded correctly but, when I click on view, I receive the the message: "An error occurred in the application and your page could not be served" Following the tips "heroku logs --tail", the terminal shows the messages 2020-11-10T22:08:40.000000+00:00 app[api]: Build succeeded 2020-11-10T22:08:40.477011+00:00 app[web.1]: 2020-11-10T22:08:40.477025+00:00 app[web.1]: > frontend@0.1.0 start /app 2020-11-10T22:08:40.477026+00:00 app[web.1]: > node bundle.js 2020-11-10T22:08:40.477026+00:00 app[web.1]: 2020-11-10T22:08:40.516540+00:00 app[web.1]: internal/modules/cjs/loader.js:969 2020-11-10T22:08:40.516541+00:00 app[web.1]: throw err; 2020-11-10T22:08:40.516542+00:00 app[web.1]: ^ 2020-11-10T22:08:40.516542+00:00 app[web.1]: 2020-11-10T22:08:40.516542+00:00 app[web.1]: Error: Cannot find module '/app/bundle.js' 2020-11-10T22:08:40.516543+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15) 2020-11-10T22:08:40.516543+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:842:27) 2020-11-10T22:08:40.516544+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) 2020-11-10T22:08:40.516544+00:00 app[web.1]: at internal/main/run_main_module.js:17:47 { 2020-11-10T22:08:40.516544+00:00 app[web.1]: code: 'MODULE_NOT_FOUND', 2020-11-10T22:08:40.516544+00:00 app[web.1]: requireStack: [] 2020-11-10T22:08:40.516545+00:00 app[web.1]: } 2020-11-10T22:08:40.520609+00:00 app[web.1]: npm ERR! code ELIFECYCLE 2020-11-10T22:08:40.520813+00:00 app[web.1]: npm ERR! errno 1 2020-11-10T22:08:40.521710+00:00 app[web.1]: npm ERR! frontend@0.1.0 start: `node bundle.js` 2020-11-10T22:08:40.521801+00:00 app[web.1]: npm ERR! Exit status 1 2020-11-10T22:08:40.521915+00:00 app[web.1]: npm ERR! 2020-11-10T22:08:40.522006+00:00 app[web.1]: npm ERR! Failed at the frontend@0.1.0 start script. 2020-11-10T22:08:40.522077+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging … -
How to get object with largest number of related objects in django
I have model A(Post): class Post(models.Model): title = models.CharField(max_length=30) and model B(Like): class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) How would I retrieve the Post object with the largest number of likes? -
crispy form not populating with data from primary key
I have a form that I want to send data to from another page. The data is definitely sending as I have a test template tag which populates based on the FK but the form itself won't populate the data. models.py class Project(models.Model): curr_choices = ( ('USD', 'USD'), ('GBP', 'GBP'), ('EUR', 'EUR'), ) production_title = models.CharField(max_length=200, unique=True) budget = models.FloatField() currency = models.CharField(max_length=3, choices=curr_choices, default='USD') distributor = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True, upload_to="static/images") proj_media = models.CharField(max_length=200) licencee = models.CharField(max_length=200) rating = models.CharField(max_length=20) release_date = models.DateField() synopsis = models.TextField() term = models.CharField(max_length=20) territory = models.CharField(max_length=20) writer_spot = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.production_title views.py def update_project(request, pk): update = Project.objects.get(id=pk) if request.method == "POST": form = ProjectForm(request.POST, request.FILES, instance=update) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('projects') else: form = ProjectForm() context = { 'form': form, 'update': update } return render(request, "projectsync/create_project.html", context) forms.py class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( PrependedText('production_title', "", placeholder="Example Title"), PrependedText('licencee', "", placeholder="Example Licencee"), PrependedText('distributor', "", placeholder="Example Distributor"), PrependedText('writer_spot', "", placeholder="Example Writer of Spot"), PrependedText('synopsis', "", placeholder="Example Synopsis"), Row( Column('currency', css_class='form-group col-md-2 mb-0'), Column(PrependedAppendedText('budget', "", '.00'), css_class='form-group col-md-10 mb-0'), css_class='form-row' ), Row( Column(PrependedText('term', … -
Django Multiple Forms One Page
I have two forms on one page (enquiry / make a booking). At any one time only one of these two forms will be submitted. This is my current views.py. def contact_us(request): if request.method == 'POST': # booking form if 'timezone' in request.POST: # timezone field only in booking_form booking_form = BookingForm(request.POST, request.FILES) if booking_form.is_valid(): booking_form.save() return redirect('thankyou') else: enquiry_form = EnquiryForm(request.POST, request.FILES) if enquiry_form.is_valid(): enquiry_form.save() return redirect('thankyou') else: booking_form = BookingForm() enquiry_form = EnquiryForm() context = { 'booking_form' : booking_form, 'enquiry_form' : enquiry_form, } return render(request, 'contact_us/contact_us.html', context) It works fine apart from when the form validation fails and it should return an error (for example, I have a datefield and if the user enters a date outside of the accepted range). When this happens I get the following error: local variable 'enquiry_form' referenced before assignment Any help would be greatly appreciated. Thank you. -
Django loses connection to MySQL db after initialization (Docker)
I'm starting to work with Docker, I'm running a Django app in a container, and a MySQL db in another one. Both of them are connected through a docker-compose.yml file. After building the containers, Django migrations run successfully and the application starts properly. However, if I connect to the Django container and execute a command (i.e. python manage.py createsuperuser) an OperationalError is raised saying that it is not possible to connect to the database. What can be the problem? The picture below shows that tables are created in the database (at some point Django does have access to the db) Accessing the 4rs_backend container (Django) with docker exec -it <container id> sh and executing python manage.py createsuperuser raises: docker-compose.yml: version: '3' services: db: image: mysql:5.7 ports: - "7000:3306" environment: MYSQL_PORT: 3306 MYSQL_USER: admin_test MYSQL_ROOT_PASSWORD: '*****' MYSQL_PASSWORD: '*****' MYSQL_DATABASE: forrealstate container_name: mysql_db api: build: backend command: bash -c "BUILD_TYPE='DOCKER' python manage.py makemigrations && BUILD_TYPE='DOCKER' python manage.py migrate && BUILD_TYPE='DOCKER' python manage.py runserver 0.0.0.0:8000" container_name: 4rs_backend volumes: - ./backend:/backend ports: - "8000:8000" depends_on: - db DATABSE config in Settings.py: BUILD_TYPE = os.environ.get('BUILD_TYPE') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'forrealstate', 'USER': 'admin_test' if BUILD_TYPE == 'DOCKER' else 'root', 'PASSWORD': '********', 'HOST': … -
Prepolate django model form
I have an Event Model and a Nominate Model. The Event Model is a Foreign Key in the Nominate Model. I want my form to be pre-populated with the current event. Any help on how to handle it with the forms or model will be appreciated. class Event(models.Model): """ Model used to store events """ name = models.CharField(max_length=256) class Nominate(models.Model): name = models.CharField(max_length=256) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="nominees") -
How do I query django parent and child by a one to many relationship?
So I am fairly new to django and I am trying to create a website keeps a log of who took out their families' dogs last. I have made my models to include tables for each individual post, dog, and their actions that correspond with the posts themselves. I want to make it so that a list of posts will be placed in order of latest to earliest post followed by all of the actions that each dog did (i.e. if there are two dog objects then there will be two action objects that accompany the post). models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Dog(models.Model): name = models.CharField(max_length = 20) class Post(models.Model): walker = models.ForeignKey(User, on_delete = models.CASCADE) time_posted = models.DateTimeField(default = timezone.now) issues = models.TextField(max_length = 300) class Action(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE) dog = models.ForeignKey(Dog, on_delete = models.CASCADE) peed = models.BooleanField(default = False) pooped = models.BooleanField(default = False) views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import Post, Dog, Action from django.http import HttpResponse class ActionList(ListView): def home(request): context = { 'posts': Post.objects.all(), 'actions': Action.objects.all(), 'dogs': Dog.objects.all() } return render(request, 'dog_log_app/home.html', context) main.html: <!DOCTYPE html> … -
My project is not finding my django module
Here is my project's git: https://github.com/DieterClaessens67/SOA I keep getting this error when I do python manage.py runserver: despite executing pip install django in de venv As I already mentioned I am using virtual environments. Here is a quick overview of my project structure for clarity: Can anyone please tell me what is going wrong here? -
Django get OAuth user id while submitting a form (This field is required while uploading)
I'm trying to make an "upload avatar" form for users that are registered through OAuth. If I only have 'avatar' as my choice of fields for the form I get "This field is required" as the response every time. I need a way to get the currently logged in user and submit his id alongside the uploaded avatar. forms.py from django import forms from django.core.files.images import get_image_dimensions from soc_auth.models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile #fields = '__all__' fields = ['avatar'] #def __init__(self, user, *args, **kwargs): #self.user = user #super(UserProfileForm, self).__init__(*args, **kwargs) def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 1000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are updating the user profile and do not … -
How to change Django views into Django rest framework views?
hi I'm coding a shopping cart and I write the cars session but I couldn't write the view .I searched and found a code that had the view but it was for django and had forms could you please help me to change the views into django rest framework??? actually my problem is the cart_add function in views this is the code??? #cart CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['total_price'] = int(item['price']) * item['quantity'] yield item def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def get_total_price(self): return sum(int(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[CART_SESSION_ID] self.save() #views.py def detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart':cart}) @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddForm(request.POST) if form.is_valid(): cd = … -
Send back data changed on backend
I made a POST method to send data from user input , recive it with Django views.py . Now i want to do some changes(ex. calculate return on invest) on that data and then send it again to display it on my page. Im stuck in it right now. I would really appreciate some help. views.py def valid(request): if request.is_ajax(): request_data = request.POST.getlist("invest")[0] investment = calculate_return_on_invest(request_data) return JsonResponse(investment, safe=False) script.js function ajaxdata(){ let invest = document.getElementById('investment').value; $.ajax({ method:'POST', url:'/valid/', data: { 'invest': invest, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (data){ alert("works"); }, error: function(data){ alert("doesn't work") } }); }; -
how to order by 1 in Django template
I have this Django template, which works template = '%(function)s(%(expressions)s ORDER BY "col_name")' However, I want to replace "col_name" with 1, e.g. template = '%(function)s(%(expressions)s ORDER BY 1)' This does not do the ordering properly what can I do? -
Django backend authentication with NextJS frontend form - best practices
I have an API hub that I've built in Django and a frontend end application I've built in NextJS. I'm currently working on authenticating to the Django API in Nextjs and I'm curious about best practices. Currently, the NextJS app posts the users username/password to an endpoint. This endpoint either returns the users token or the error illustrating the issue. React const login = async () => { let token = await axios.post('/api/accounts/', { email: email, password: password }).then(r => r.data.token).catch(function (error) { console.log(error) }) if (token) { router.push({ pathname: '/home/', query: { token: token }, }) } } nexjs server api/accounts export default async (req, res) => { if (req.method === 'POST') { try { // retrieve payment intent data const {data} = await axios.post('https://website/api/api-token-auth/', req.body) res.status(200).send(data) } catch (err) { res.status(500).json({ statusCode: 500, message: err.message }) } } else { res.setHeader('Allow', 'POST') res.status(405).end('Method Not Allowed') } } Django API @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def obtain_auth_token(request): email = request.data.get("email") password = request.data.get("password") if email is None or password is None: return Response({'error': 'Please provide both email and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(email=email, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) Once … -
How to implament teacher student functionality into django?
Hi im working on a school project. I am supposed to make a teacher control panel that lets the teacher group students and stuff. How do i do such thing? Is there anything implamented in django. Also i cant just use the admin panel build into django because it should be a admin more of a like moderator. Hopefully you have some answers. -
Unable to import installed package in Python
I'm attempting to use the following Python package: https://github.com/amadeus4dev/amadeus-python I have installed it as a global package via the pip3 install amadeus command and can see that it has been installed correctly, as reported by pip3 list Despite it being installed, I am receiving the following error when trying to import it into a Django view: Unable to import 'amadeus'pylint(import-error) Troubleshooting Uninstalled the package and reinstalled using sudo pip3 install amadeus Uninstalled the package and reinstalled using python3 -m pip install amadeus Checked that the package has been installed within a directory in my system path. I'm currently all out of ideas for why it won't work for me and would be grateful if somebody had any ideas? Thank you! -
Django - running both Functional and Unit test in a single test file
I am using Django 3.1 and Python 3.6 I have an app that I want to run both functional and unit tests for, by running ./manage.py test myapp /path/to/project/myapp/test.py import os from django.test import TestCase from selenium import webdriver from django.contrib.staticfiles.testing import StaticLiveServerTestCase import time # Create your tests here. class FunctionalTestCase(StaticLiveServerTestCase): fixtures = ['user_test_data.json','foo_test_data'] @classmethod def setUpClass(cls): super().setUpClass() loc='/path/to/some/loc/' chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("user-data-dir=/home/morpheous/") # cls.browser = webdriver.Chrome(os.path.join(loc, 'chromedriver'), chrome_options=chrome_options) @classmethod def tearDownClass(cls): cls.browser.quit() super().tearDownClass() def test_functest_one(self): pass def test_functest_two(self): pass # Create your tests here. class UnitTestCase(TestCase): def test_some_unit_test(self): pass When I run ./manage.py test myapp It only run the functional tests and says two tests failed (as expected). How do I run BOTH the functional and unit tests?