Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to check for empty value in field?
I am trying to get the set of objects which have no value for the field units The only way I can find to do this on the internet is by using objects.filter(units__exact = '') but this does not work for me as my field units is of type int, so I get a type error. How would I check for empy units field? -
Django union with annotate of 3 tables The used SELECT statements have a different number of columns
Currently i have these 3 models which not related to each other as followed: class TopUp(models.Model): class Meta: db_table = "topups" verbose_name = 'TopUp Request' verbose_name_plural = 'TopUp Requests' user = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_toptup', on_delete=models.CASCADE) currency = models.ForeignKey("backend.Currency", null=True, blank=True, related_name='user_topup_currency', on_delete=models.SET_NULL) TOPUP_METHOD_CHOICES = [ (1, 'bank account'), (2, 'blockchain address') ] method = models.PositiveSmallIntegerField("Method", choices=TOPUP_METHOD_CHOICES) amount = models.DecimalField("Amount", max_digits=65, decimal_places=0, default=0) TOPUP_STATUS_CHOICES = [ (0, 'Pending'), (1, 'Received'), (2, 'Rejected'), ] status = models.PositiveSmallIntegerField("Status", choices=TOPUP_STATUS_CHOICES, default=0) fiat_image = models.CharField("Fiat image", max_length=255, null=True, blank=True) fee = models.DecimalField("Fee", max_digits=65, decimal_places=0, default=0) created = models.DateTimeField(auto_now_add=True) received = models.DateTimeField(null=True, blank=True) class Withdrawals(models.Model): class Meta: db_table = "withdrawals" verbose_name = 'Withdraw Request' verbose_name_plural = 'Withdraw Requests' user = models.ForeignKey("backend.User", null=True, blank=True, related_name='user_withdrawal', on_delete=models.CASCADE) currency = models.ForeignKey("backend.Currency", null=True, blank=True, related_name='user_withdrawal_currency', on_delete=models.SET_NULL) WITHDRAWAL_METHOD_CHOICES = [ (1, 'to bank account (fiat)'), (2, 'to blockchain address (crypto)'), (4, 'to debit card (DB)') ] method = models.PositiveSmallIntegerField("Method", choices=WITHDRAWAL_METHOD_CHOICES) to_bank = models.ForeignKey("backend.UserBank", null=True, blank=True, related_name='user_withdrawal_userbank', on_delete=models.SET_NULL, db_column='to_bank') to_address = models.CharField("To address", max_length=255, null=True, blank=True, db_column='to_address') to_card = models.ForeignKey("backend.CardBinding", null=True, blank=True, related_name='user_withdrawal_to_card', on_delete=models.SET_NULL, db_column='to_card') amount = models.DecimalField("Amount", max_digits=65, decimal_places=0, default=0) WITHDRAWAL_STATUS_CHOICES = [ (0, 'Pending'), (1, 'Submitted'), (2, 'Confirmed'), (100, 'Failed') ] status = models.PositiveSmallIntegerField("Status", choices=WITHDRAWAL_STATUS_CHOICES, default=0) fee = models.DecimalField("Fee", … -
Issue in using Bidi library in Python Django template
I'm using a table in the template in which some columns have both LTR and RTL strings. I'm using django-bidi-utils 1.0 library as follow: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>{% block title %}CFP List{% endblock %}</title> {% load i18n %}<html dir="{{ LANGUAGE_BIDI|yesno:"rtl,ltr" }}"> {% block styles %} <link rel="stylesheet" href="/style/table.css" /> {% endblock %} </head> <body> {% block content %} {% load bidiutils_tags %} <table style="border-collapse: collapse; float:right"> <tr> <th style="border: 1px solid black; text-overflow: ellipsis; max-width : 500px;">System Addition Time</th> <th style="border: 1px solid black; text-overflow: ellipsis; max-width : 500px;">Student Name</th> <th style="border: 1px solid black; text-overflow: ellipsis; max-width : 500px;">Father Name</th> <th style="border: 1px solid black; text-overflow: ellipsis; max-width : 200px;">Student Number</th> </tr> {% for item in data_list%} <tr> <td style="border: 1px solid black; text-overflow: ellipsis; max-width : 500px;" align="center">{{item.std_add_date}}</td> <td style="border: 1px solid black; text-overflow: ellipsis; max-width : 500px;" align="right">{{item.std_name|add_direction:"rtl_only"}}</td> <td style="border: 1px solid black; text-overflow: ellipsis; max-width : 500px;" align="right">{{item.std_father_number}}</td> <td style="border: 1px solid black; text-overflow: ellipsis; max-width : 200px;">{{item.std_number}}</td> </tr> {% endfor %} </table> {% endblock %} </body> </html> I've also added bidi in INSTALLED_APPS and TEMPLATE_CONTEXT_PROCESSORS, but the result is not changed from the normal situation and without bidi library. -
Update Environment Variables
I'm in the process of porting my local django app to heroku and am hitting a snag. Mainly with my environment variables. I can't very well create a .env file on my webserver, it would just get overwritten when I push from github again. So I've set environment variables using heroku config:set VAR='' --app <app>. These seem to work, however, I'm working with an API that requires I refresh my token every 60 min. Locally, I developed a method to update my .env every time the task that refreshed this token was executed, but this solution clearly isn't sufficient for my web server...I've attempted to update server-level variables in Python, but I don't think that's possible. Has anyone had to deal with an issue like this? Am I approaching this all wrong? What is the best way for me to update an environment variable on a web server (ie heroku config:set VAR='' --app <app> but in my python code)? I need this variable to update every 60 minutes (I already have the celery task code built for this). Should I modify the task to simply write it to a text file and use that text file as my "web server … -
Django cant connect to mongoDB atlas
Recently I started a project to make a Webserver using a Django backend with and a mongoDB database hosted on their Atlas platform so i don't have to worry about running it locally. Im still in the early stages of setting it up and encountered the this error: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it It might also be relevant to mention that i currently have no documents on the database or models in the form of Django apps, but I doubt that this is the probelm as when i run manage.py migrate i get the above error and not a "no app with label" error. My database config in my settings.py currently looks like this: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'house-project', 'HOST': 'mongodb+srv://<my-user-name>:<my-password>@house-project-9g5fo.gcp.mongodb.net/test?retryWrites=true&w=majority' } } I know that one of the common errors is having special characters in your password and username, i have made sure not to include any or escape them with hex characters. I have made sure to add my ip and user on the Atlas side. I have checked online for an exiting answer, to no avail. The closest question i found was: … -
channels get url parameter without spaces
Hi i'm fiddling with django-channels 2 and want to grab the URL parameter and use it in a function, but it seems like it contains a space or something similiar which causes issues with my function. My function takes 1 argument but when I try to pass the URL parameter in it gives me the following error task_status() takes 1 positional argument but 2 were given. I can see when I try to print the URL it prints the correct value but a new line is also created. Is there any way to grab ONLY the URL parameter and be able to use it directly in a function? consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept" }) user = self.scope['user'] get_task_id = self.scope['url_route']['kwargs']['task_id'] print(get_task_id) get_info = await self.task_status(get_task_id) print(get_info) await self.send({ "type": "websocket.send", "text": "hey" }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) def task_status(task_id): command = "golemcli tasks show {}".format(task_id) taskoutput = subprocess.getoutput(command) print(taskoutput) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/dashboard/task/(?P<task_id>[0-9a-f-]+)', consumers.ChatConsumer), ] website URL http://localhost:8000/dashboard/task/aa3c6c12-5446-11ea-b237-1e0f691c9a55 -
Check if Model is a Foreign key of another Model in Django
I would like to find out if Account has a Foreign Key to Profile. This is what I tried: def check_if_model_has_one_to_many_relationship(account_model, profile_model) for foreign_key_model in profile_model._meta.get_all_related_objects(): if f'{account_model._meta.model_name}_set' == foreign_key_model.get_accessor_name(): return True return False And I think it works, but I'm trying to see if there is something built in? -
Fundamentals question: Django + Python Virtual Env + pyCharm and CLI -- are two separate virtual environments required?
Bottom Line: I can get everything to work by configuring two separate virtual environments, one for pyCharm and one for the CLI. Is this really necessary or should I be able to use 1 virtual environment for both as I expected? More Detailed explanation: I'm very new so this is probably a facepalm type of question so i'll try to be terse. I'm using Linux Mint, Python 3.6, django 3.0.3, and pyCharm 2019.3.1. I can create a virtual env using venv in the cli and it works. I can also create a NEW virtual env in pyCharm through the settings: Project: Interpreter interface, and it works, however it doesn't have venv as an option, it only has virtualenv. But if I try to activate the virtual env i created in pyCharm from the cli (using virtualenv of course, not venv), it fails hard and thinks i'm using python 2.7 which isn't even installed on my system. If it try to point pyCharm at the virtual env I setup on the cli, I get an error 134. Is this just a known/expected issue? Must I have two virtual environments for every project I want to access via both pyCharm AND the … -
Django imagekit 'SafeString' object has no attribute 'name'
I'm currently trying to process an image using django-imagekit in my project. I'm quite new to the package, so I'm trying to implement a simple processor that converts the image to grayscale. I followed some samples from the docs. I decided to use spec, which I've included in models.py. However, when I wanted to generate the image on a template, I came across the following error: AttributeError: 'SafeString' object has no attribute 'name' FULL ERROR Traceback (most recent call last): File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/imagekit/cachefiles/__init__.py", line 37, in __init__ name = generator.cachefile_name File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/imagekit/specs/__init__.py", line 95, in cachefile_name return fn(self) File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/imagekit/cachefiles/namers.py", line 40, in source_name_as_path '%s%s' % (generator.get_hash(), ext))) File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/imagekit/specs/__init__.py", line 134, in get_hash self.source.name, AttributeError: 'SafeString' object has no attribute 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/Image-Analysis-Web-App/pipeline/views.py", line 33, in playground_view return render(request, "playground.html", {"image": image}) File "/mnt/c/Users/Gilang R Ilhami/Desktop/personal_projects/random_mini_projects/image_analysis_app/app/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render … -
How do I send an axios request to Django with CORS?
I'm trying to send a CORS request and manually set the headers as in the documentation const options = { method: 'POST', headers: { "X-CSRFToken": getCookie("csrftoken"), }, data: { 'username': this.username, csrfmiddlewaretoken: csrftoken, }, xsrfHeaderName: 'X-CSRFToken', url, }; axios(options); However, I'm getting the 403 Forbidden Django page, saying CSRF cookie is not set.' -
Django template tag left / right
Given text. Is there a django template tag to do: text = 'hello there' text[:3] ==> 'hel' text[-3:] ==> 'ere' Something like: {{ text|left:3 }} If not I can build a template tag for it but was wondering if it's already provided. -
AttributeError: 'property' object has no attribute 'filter'
#courses/models.py from django.db import models from django.urls import reverse from memberships.models import Membership class Course(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) description = models.TextField() allowed_memberships = models.ManyToManyField(Membership) def __str__(self): return self.title def get_absolute_url(self): return reverse('courses:detail', kwargs={'slug': self.slug}) @property def lessons(self): return self.lessons_set.all().order_by('position') class Lesson(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) position = models.IntegerField() video_url = models.CharField(max_length=200) thumbnail = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse('courses:lesson-detail', kwargs={ 'course_slug': self.course.slug, 'lesson_slug': self.slug }) #courses/models.py from django.shortcuts import render from django.views.generic import ListView, DetailView,View from memberships.models import UserMembership from .models import Course, Lesson # Create your views here. class CourseListView(ListView): model = Course class CourseDetailView(DetailView): model = Course class LessonDetailView(View): def get(self,request,course_slug,lesson_slug, *args,**kwargs): course_qs = Course.objects.filter(slug=course_slug) if course_qs.exists(): course = course_qs.first() lesson_qs = Course.lessons.filter(slug=lesson_slug) if lesson_qs.exists(): lesson = lesson_qs.first() user_membership = UserMembership.objects.filter(user=request.user).first() user_membership_type = user_membership.membership.membership_type course_allowed_mem_types = course.allowed_memberships.all() context = { 'object' : None } if course_allowed_mem_types.filter(membership_type=user_membership_type).exists(): context = {'object': lesson} return render(request, "courses/lesson_detail.html",context) Traceback (most recent call last): File "C:\Users\ASUS\Envs\web\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ASUS\Envs\web\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ASUS\Envs\web\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ASUS\Envs\web\lib\site-packages\django\views\generic\base.py", line 71, in view return … -
Django restricting drag and drop based on database conditions
hopefully I can make this clear: I have javascript code that allows for drag and drop functionailty of my website. I need the drop to only be allowed if certain objects from my database are not all ready on the div. To do this I would need to query the DB. But, apperantly we cannot query django DB using templating language, so I am not sure how to do this. Specific use case: I have course objects and a prerequestie realation that shows which courses a prerequistie for other courses. I want to be able to drop the course on the planner only if all the courses prerequites are already on the planner. So I would need to query the courses prerequistes to see if any are in the planner already. would I need to use something like AJAX for this? When I first started with django I thought I would be able to use its template tags to do this but they dont seem to work well with querying or with javascript -
Django's collectstatic ignores a folder in Heroku environment
I'm building a Django+Vue monolith and the release pipeline I'm trying to achieve supposes building the Vue frontend into the static folder of a Django app, running collectstatic and starting the server. Static files are served via WhiteNoise. It works perfectly on my machine. The built folder ends up in the collected static files destination and its contents get nicely served: → But when hosted on Heroku, everything else gets collected except for this built on the fly folder, it just doesn't end up in the staticfiles even though it's present in the static folder of the app. I made sure that the order of execution was correct and even ran collectstatic manually after ensuring that the folder was successfully built. As you may have noticed, I have this folder in .gitignore, but I've tried removing it from there to no avail. What could be the reason for such a strange behavior? p.s. Setting DEBUG to True and serving static files through Django's development server results in a working application, which once again proves the files are in their correct places. -
Celery tasks are executed by different program binaries
I have a Django web application that executes tasks via celery. It is run with a combination of Apache, uWSGI, and Redis. For some reason, one of the tasks is being executed by the uWSGI server and the other is executed by the Python interpreter. This is causing permissions issues as uWSGI doesn't run as the same user as Python does. What could cause the tasks to be run by different programs? Is there a setting somewhere? -
how do i create a profile page that shows all users post to the user and to other users
am new to Django and am trying to create a blog site where users can sign up and post articles, but my problem is how can I display a user's post on the user's profile page so that when other users reading the post clicks on the author's name it takes them to the post.author's profile page with the post.author's recent post listed and not the request.user's post. here is my code. here is accounts/views.py views.py @login_required() def user_profile_view(request, username): post = User.objects.filter(courses__author=username) context = {'courses': courses} return render(request, 'accounts/user_profile_view.html', context) and here is post/models.py models.py class Posts(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) cover = ProcessedImageField(upload_to='post_featured_image', processors=[ResizeToFill(600, 300)], format='png', options={'quality': 80}, blank=True) slug = models.SlugField() title = models.CharField(max_length=200) body = models.TextField() summary = models.TextField(max_length=200) here is the template post_list.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="col-lg-6"> {% for course in courses_list %} <div class="central-meta item"> <div class="user-post"> <div class="friend-info"> {% if post.author.profile.avatar %} <figure> <img src="{{ post.author.profile.avatar.url }}" alt=""> </figure> {% else %} <img src="{% static 'default.ico' %}" alt=""> {% endif %} <div class="friend-name"> <ins><a href="{% url 'accounts:user_profile' post.author.username %}" title="">{{ course.author.get_full_name|title }}</a></ins> <span>published: {{ post.published }}</span> </div> <div class="post-meta"> {% if course.cover %} … -
java script internal problrm
my java script code doesnt work internal (it works external) what is the problem i tried external and it worked wll but when i add js file to ststics in django i can load css with {% load static%} well but my js file doesnt work . function animatethis(targetElement, speed) { var scrollWidth = $(targetElement).get(0).scrollWidth; var clientWidth = $(targetElement).get(0).clientWidth; $(targetElement).animate({ scrollLeft: scrollWidth - clientWidth }, { duration: speed, complete: function () { targetElement.animate({ scrollLeft: 0 }, { duration: speed, complete: function () { animatethis(targetElement, speed); } }); } }); }; animatethis($('#scroll-div'), 22000); -
Message on logout
I'm wanting to display a message to the user after they are logout and are redirected to the homepage. I know this likely doesn't work because I am trying to display the message before returning a redirect to the homepage. views.py def logout_request(request): logout(request) messages.info(request, "Logged out successfully!") return redirect("main:homepage_view") -
How to loop through django forms ValidationErrors?
I have a ValidationError that is a list of ValidationErrors. I need to loop through them on the template, to HTML format each error. This is my list: [ValidationError([u'123456']), ValidationError([u'STRING']), ValidationError([u'123STRING'])] In my templates, I tried this: for error in form.non_field_errors.all # Doesn't work for error in form.non_field_errors # Doesn't work either form.non_field_errors.all.0 # Nope form.non_field_errors # Works, but won't let me format the error, one by one form.non_field_errors.as_ul # Works, but won't let me format the error, one by one What should I do differently to get this working? -
How to break '302 0 loop' in django
I know that this topic has already appeared on the forum many times, but somehow none of the previously mentioned methods to solve the problem does not work. The problem is, at least it seems to me that the application has fallen into a kind of loop by which it adds double values to the database. Maybe some of you will look at it with a fresh eye and find out when I made a mistake Here is my views, urls and log: class CourseView(View): def get(self, request, pk): course_data = Course.objects.get(id=pk) teacher = Profile.objects.get(user=course_data.teacher) user = self.request.user try: user_points = Mark.objects.get(student=self.request.user, course=course_data).mark max_points = course_data.points except Mark.DoesNotExist: user_points = '' max_points = course_data.points files = File.objects.filter(course=pk) senders = [i.sender for i in files] student = Profile.objects.filter(projects__course__id=course_data.id).order_by('last_name') students = [i.user for i in student] late = list(set(students)-set(senders)) late = Profile.objects.filter(user__in=late) context = { 'files': files, 'course': course_data, 'teacher': teacher, 'user': user, 'user_points': user_points, 'max_points': max_points, 'pk': pk, 'late': late, } return render(self.request, 'projects/course.html', context) class MarkCreateView(CreateView): model = Mark form_class = MarkForm template_name = 'projects/mark.html' success_message = 'Success: mark set' print("before", Mark.objects.all()) # TODO: double marks def form_valid(self, form, **kwargs): print("sanity check I", form.instance.course, form.instance.mark, form.instance.student) print(Mark.objects.all()) form.instance.course = get_object_or_404(Course, … -
Corrupt excel file when serving file using Django and openpyxl
I have an issue with trying to serve my excel file as an httpresponse, it is coming out almost double in size and is corrupt when I try to open it. My setups is as follows: I have an excel template which I make a copy of using shutil2 I then open the copy using load_workbook() in openpyxl I populate the workbook with data I then (as per the openpyxl docs) save the workbook as a stream and save it as an httpresponse object to be returned to my website through django with NamedTemporaryFile() as tmp: wb.save(tmp.name) tmp.seek(0) stream = tmp.read() response = HttpResponse(content=stream, content_type="application/ms-excel") # I've also tried with application/vnd.openxmlformats-officedocument.spreadsheetml.sheet response['Content-Disposition'] = 'attachment; filename=Excel.xls' return response In my template I have some jquery code which downloads the excel for the user. This is done following the answer from this question: Get excel file (.xlsx) from server response in ajax This all works fine, but the resulting download file is corrupt and while I am expecting it to be around 7mb in size, its actually 16mb. Does anyone have any idea what I am doing wrong? -
How to keep POST data in Django?
I have a code similar to this: <form method="post"> <!-- INPUTS --> <a href="{% url 'app:edit' person.id %}" class="btn btn-gradient-primary">Edit Person</a> <a href="{% url 'app:delete' person.id %}" class="btn btn-light">Delete Person</a> </form> Deletion works because in the delete view I only need person.id, but editing a person doesn't work because the post data (i.e data from input fields) is lost when clicking the button. How should I fix this? -
page that only admins can visit
hello I would like to know if we can make a page accessible only to administrators (superuser) I can find nothing in the documentation but I would like my analysis page to be accessible only by superuser without using a boolean in the profile -
ElasticBeanstalk suddenly starts failing to deploy Django App
I am using elastic beanstalk to deploy my Django application. Today it suddenly stopped working without any breaking changes from the application side (I've changed some templates, nothing more). The deployment time outs after 10 minutes of trying to deploy the app and nothing happens. The only more or less useful hints I can see in the log is this: [2020-02-20T15:00:20.437Z] INFO [19057] - [Application update .../postbuild_0_myproject/Command 01_migrate] : Activity execution failed, because: SystemCheckError: System check identified some issues: ERRORS: education.Author.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". education.Course.cover_image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". education.CourseCategory.icon_image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". Using staging settings education app receivers connected analytics app receivers connected (ElasticBeanstalk::ExternalInvocationError) [2020-02-20T15:00:20.437Z] INFO [19057] - [Application update .../postbuild_0_myproject/Command 01_migrate] : Activity failed. [2020-02-20T15:00:20.437Z] INFO [19057] - [Application update .../postbuild_0_myproject] : Activity failed. [2020-02-20T15:00:20.437Z] INFO [19057] - [Application update ...] : Activity failed. [2020-02-20T15:00:20.507Z] INFO [19057] - [Application update app-9a24-200220_145942-stage-200220_145942@142/AppDeployStage0/EbExtensionPostBuild] : Activity failed. [2020-02-20T15:00:20.507Z] INFO [19057] - … -
How to mock a model method from unittesting a django view?
I am trying to mock a downstream function call in order to get my unittest for a DRF view to pass. I have a create() method location in a model, that is calling an external upload_files() function. I am trying to figure out how to mock upload_files() from a view unit test Since the view calls the serializer, and the serializer calls the model, I need to figure out the correct namespacing in order to mock the path. Here is my code which shows what I'm TRYING to do, however I think, the path being passed to mock.patch is incorrect. Receiving this error when I run the unittest ERROR: test_post (tests.api.views.test_stage_execution_view.StageExecutionViewTest) ModuleNotFoundError: No module named 'myapp.models.stage_execution.StageExecution'; 'myapp.models.stage_execution' is not a package unittesting a view from a drf api: # myapp/tests/api/views/test_stage_execution_view.py class StageExecutionViewTest(APITestCase): @mock.patch('myapp.models.stage_execution.StageExecution.create.upload_files', side_effect=mocked_upload_files) def setUp(self, arg): self.stage_execution = StageExecution.manager.create( stage="test", job_execution="test", time_start="2018-12-20T12:05:00.258797-08:00", ) @mock.patch('myapp.models.stage_execution.StageExecution.create.upload_files', side_effect=mocked_upload_files) def test_post(self): start_stage_execution_payload = {"bla"} response = self.client.post( "/api/v2/stage_execution", start_stage_execution_payload, format="json" ) assert response.status_code == 201 models: #myapp/models/stage_execution.py class StageExecution(JsonableModel): stage = models.CharField(max_length=150, blank=True, null=True) job_execution = models.CharField(max_length=150, blank=True, null=True) time_start = models.DateTimeField() class StageExecutionManager(models.Manager): def get_queryset(self): return StageExecutionQuerySet(self.model, using=self._db) def create(self, **kwargs): from myapp.tasks import upload_files upload_files() serializer: # myapp/api/serializers/stage_execution_serializer.py class StageExecutionSerializer(serializers.ModelSerializer): class …