Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-storage + S3, certain images retun erorr 403
I am having an issue with django-storages returning error 403. Only certain images trigger these though. From what I've tested, all photos taken on iPhone's (perhaps due to their large filesize? I've also transferred them to my pc and then uploaded- same thing) return a 403. Here is an example from an iPhone. Also, this is a random stock photo that errors out too. Anyway, this is my relevant settings.py (note: I only want to upload images): AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'media' MEDIAFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') AWS_DEFAULT_ACL = "public-read" The model: class Face(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE) image = models.ImageField() faceid = models.TextField() The HTML form: <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <input type="file" multiple name="image"> <button type="submit" class="px-4 py-4 rounded bg-gray-300 text-gray-600 hover:shadow">Add files </button> </form> @login_required def addface(request, personid): person = models.Person.objects.get(pk=personid) form = FaceForm(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): try: # some processing here .... # .... # This prints a URL print(form.instance.image.url) form.save(commit=False) form.instance.person = person // … -
Django multiple signals with one receiver
I'm trying to add a post_save and a post_delete signal to a receiver. However, I am getting an error that says: TypeError: change_followers() missing 1 required positional argument: 'created' @receiver([post_save, post_delete], sender=Following) def change_followers(instance, created, **kwargs): if created: instance.follower.following_count += 1 instance.target.follower_count +=1 instance.save() else: instance.follower.following_count -= 1 instance.target.follower_count -=1 instance.save() Why am I getting this error and how can I fix it? -
How to Group dictionary values in python
I have the following dictionary #BEFORE data={ 'cell_1':['13a'], 'jam_1': ['07-08'], 'model_1': ['SUPERSTAR'], output_1':['10'],'output_jam_1': [''], 'time_1': [''], 'output_ot_1': [''], 'time_ot_1': [''], 'cell_2':['13a'], 'jam_2': ['07-08'],'model_2':'SUPERSTAR'], 'output_2': ['20'], 'output_jam_2': [''], 'time_2': [''], 'output_ot_2': [''], 'time_ot_2': [''], 'cell_3':['13c'], 'jam_3': ['07-08'], 'model_3': ['SUPERSTAR'], 'output_3': ['40'], 'output_jam_3': [''], 'time_3': [''], 'output_ot_3': [''], 'time_ot_3': [''], 'cell_4':['13b'], 'jam_4': ['08-09'], 'model_4': ['SUPERSTAR'], 'output_4': ['30'],'output_jam_4': [''], 'time_4': [''], 'output_ot_4': [''], 'time_ot_4': [''], 'cell_5':['13d'], 'jam_5': ['16-17'], 'model_5': ['SUPERSTAR'], 'output_5': ['40'], 'output_jam_5': [''], 'time_5': [''], 'output_ot_5': [''], 'time_ot_5': [''], 'cell_6':['13d'], 'jam_6': ['16-17'], 'model_6': 'SUPERSTAR'], 'output_6': ['40'], 'output_jam_6': [''], 'time_6': [''], 'output_ot_6': [''], 'time_ot_6': [''], 'cell_7':['13d'], 'jam_7': ['17-18'], 'model_7': ['SUPERSTAR'], 'output_7': ['10'], 'output_jam_7': [''], 'time_7': [''], 'output_ot_7': [''], 'time_ot_7': [''], 'cell_8':['13d'], 'jam_8': ['18-19'], 'model_8': ['SUPERSTAR'], 'output_8': ['60'], 'output_jam_8': [''], 'time_8': [''], 'output_ot_8': [''], 'time_ot_8': [''], } #AFTER data={ 'cell_1':['13a'], 'jam_1': ['07-08'], 'model_1': ['SUPERSTAR'],'output_1': ['10'], 'output_jam_1': ['30'], 'time_1': ['0.33'], 'output_ot_1': [''], 'time_ot_1':[''], 'cell_2':['13a'], 'jam_2': ['07-08'], 'model_2': ['SUPERSTAR'], 'output_2': ['20'], 'output_jam_2': ['30'],'time_2': ['0.67'], 'output_ot_2': [''], 'time_ot_2':[''], 'cell_3':['13c'], 'jam_3': ['07-08'], 'model_3': ['SUPERSTAR'], 'output_3': ['40'], 'output_jam_3': ['40'], 'time_3': ['1'], 'output_ot_3': [''], 'time_ot_3':[''], 'cell_4':['13b'], 'jam_4': ['08-09'], 'model_4': ['SUPERSTAR'], 'output_4': ['30'], 'output_jam_4': ['30'], 'time_4': ['1'], 'output_ot_4': [''], 'time_ot_4':[''], 'cell_5':['13d'], 'jam_5': ['16-17'], 'model_5': ['SUPERSTAR'], 'output_5': ['40'], 'output_jam_5': [''], 'time_5': [''], 'output_ot_5': ['80'], 'time_ot_5':['0.5'], 'cell_6':['13d'], 'jam_6': ['16-17'], 'model_6': ['SUPERSTAR'], 'output_6': ['40'], … -
Django/Vue/Nuxt confusion: Why can't I register an account twice in the same "session"? (403 forbidden error)
Of course I can't, I'm not supposed to, but why/how is Django preventing me from doing that? I'm using Django with all-auth, rest-framework and rest-auth. The Django API lives at http://localhost:8000. My Vue/Nuxt.js app lives at http://localhost:8000. So I've coded up a registration form that passes username, password1, password2 and email to the registration endpoint at localhost:8000/api/accounts/auth/registration. What I haven't done is set any logic for logging-in or out, nor am I saving anything after that. The frontend app does nothing with the token returned by the Django API. So how come when I then try to register again, I keep getting a Forbidden error: HTTP POST /api/accounts/auth/registration/ 403 [0.01, 127.0.0.1:51661] But when I close the browser/open an incognito tab, and try the form again - the form works? I'm assuming it has something (or everything) to do with Django sessions, but how is that working behind the scenes? I mean all I'm getting is a string (the token) and I'm not doing anything with that. When that get cleared up I will hopefully know what my steps are, but just to be sure: would I want to disable Session authentication in my Django app? (it's strictly an API backend) -
How to upload image to db in django instead of static folder
I would like to deploy an image to my page using Django, still in a debig mode. I created a model for the image along some other fields, and all the information is migrated to the database except the image which is storaged in the directory folder for /media/. How can i upload this image to the db and deploy it from there? class Products(models.Model): title = models.CharField(max_length=30) image = models.ImageField(blank=True, null=True) def __str__(self): return self.title -
How to make multiple api calls with python requests
I am trying to make parallel calls to external apis from django using requests or any other library that allows me to do this. I have already tried using grequests to make this calls, sometimes it works but most times I get 'NoneType' object has no attribute 'json' error on the client side. Here are my codes views.py def get_fixtures(request, league_id): league_id = league_id urls = [ "https://api-football-v1.p.rapidapi.com/v2/fixtures/league/%d" % league_id, "https://api-football-v1.p.rapidapi.com/v2/leagues/league/%d" % league_id ] headers = {'X-RapidAPI-Host': "api-football-v1.p.rapidapi.com", 'X-RapidAPI-Key': X_RapidAPI_Key} resp = (grequests.get(u, headers=headers) for u in urls) responses = grequests.map(resp) a = responses[0].json() b = responses[1].json() fix_1 = a['api']['fixtures'] api_2 = b['api']['leagues'] context = { 'fix_1': fix_1, 'api_2': api_2, } return render(request, "pages/fixtures.html", context) On the server side i get this error: File "src\gevent\_greenlet_primitives.py", line 60, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch File "src\gevent\_greenlet_primitives.py", line 64, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch File "src\gevent\__greenlet_primitives.pxd", line 35, in gevent.__greenlet_primitives._greenlet_switch greenlet.error: cannot switch to a different thread. Can I use requests or any other library to perform the calls without getting these errors? if yes how do i implement it in my work? -
Gunicorn is not seeing new settings
I updated one environment variable inside settings.py and restarted gunicorn, but it is seeing the old settings. Here is the command I use to start it: nohup /opt/my_proj/.virtualenvs/my_proj/bin/python2 /opt/my_proj/.virtualenvs/my_proj/bin/gunicorn --bind=0.0.0.0:8008 --timeout=1800 --log-level=debug --error-logfile=/opt/my_proj/gunicorn_nik.log --enable-stdio-inheritance --capture-output --user=me --pythonpath=/opt/me/code/my_proj,/opt/me/code/my_proj/seqr_settings wsgi & I printed out paths to make sure that the scripts are running under my 'my_proj' directory and also looked up in 'gunicorn_nik.log' verifying that there I see it pointing to 'my_proj' folder. Then I removed settings.py to make sure still that it is the file gunicorn is picking up. The startup failed. I tried modifying settings.py printing out something from it but it is not working, logger.info is not printing from there. I have several Django projects on one cluster node running (not sure that it is important). Its as if Django is storing some cached file and using it, but how come gunicorn restart does not fix it? Seems weird to me. Any suggestions would be greatly appreciated. -
django-celery-beat break django unexpectedly
I am working with django-celery-beat with celery 4.2.1 and django2. At first it works perfect but after some time in gunicorn log appears the following error Traceback (most recent call last): File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 366, in import_app __import__(module) File "/var/infra/app/smartwaypanel-backend/src/restfull_api/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/usr/local/lib/python3.5/dist-packages/django_celery_beat/models.py", line 8, in <module> from celery.five import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' It is a very strange behaviour and I cannont find more information about. -
How to handle HTTP responses in client side? [ReactJS & Django]
I have an endpoint to produce the token for authentication using JWT method. I send the request with Axios. Now assume I get back HTTP_BAD_REQUEST_400. If we look to console of browser in client side we get some message like this: POST http://127.0.0.1:8000/users/api/token/ 400 (Bad Request) How should I prevent of displaying the message? -
How to integrate sitemaps to django-oscar?
I want to integrate sitemaps for my oscar project and I used django-sitemaps package I followed the same, created an app called sitemaps-django, configured views.py, sitemaps-django/pages/sitemaps.py, URLconf in main urls.py file Views.py from sitemaps_django.pages.sitemaps import PagesSitemap def sitemap(request): sitemap = Sitemap( build_absolute_uri=request.build_absolute_uri, ) # URLs can be added one-by-one. The only required argument # is the URL. All other arguments are keyword-only arguments. for p in Page.objects.active(): url = p.get_absolute_url() sitemap.add( url, changefreq='weekly', priority=0.5, lastmod=p.modification_date, alternates={ code: urljoin(domain, url) for code, domain in PAGE_DOMAINS[p.language].items() }, ) # Adding conventional Django sitemaps is supported. The # request argument is necessary because Django's sitemaps # depend on django.contrib.sites, resp. RequestSite. sitemap.add_django_sitemap(PagesSitemap, request=request) # You could get the serialized XML... # ... = sitemap.serialize([pretty_print=False]) # ... or use the ``response`` helper to return a # ready-made ``HttpResponse``: return sitemap.response( # pretty_print is False by default pretty_print=settings.DEBUG, ) sitemaps-django/pages/sitemaps.py from django.urls import reverse_lazy from django.conf.urls import url urlpatterns = [ url(r'^robots\.txt$', robots_txt( timeout=86400, sitemaps=[ '/sitemap.xml', reverse_lazy('articles-sitemap'), ..., ], )), ] urls.py from django_sitemaps import robots_txt from sitemaps_django.views import sitemap urlpatterns = [ url(r'^sitemap\.xml$', sitemap), url(r'^robots\.txt$', robots_txt(timeout=86400)), ... ] I get this error url(r'^robots\.txt$', robots_txt( NameError: name 'robots_txt' is not defined -
Annotations in django with model managers
I have two models with an one to many relation. One model named repairorder, which can have one or more instances of work that is performed on that order. What I need is to annotate the Repairorder queryset to sum the cummulative Work duration. On the Work model I annotated the duration of a single Work instance based on the start and end date time stamps. Now I need to use this annotated field to sum the total cummulative Work that is performed for each order. I tried to extend the base model manager: from django.db import models class WorkManager(models.Manager): def get_queryset(self): return super(OrderholdManager, self).get_queryset().annotate(duration=ExpressionWrapper(Coalesce(F('enddate'), Now()) - F('startdate'), output_field=DurationField())) class Work(models.Model): #... order_idorder = models.ForeignKey('Repairorder', models.DO_NOTHING) startdate = models.DateTimeField() enddate = models.DateTimeField() objects = WorkManager() class RepairorderManager(models.Manager): def get_queryset(self): return super(RepairorderexternalManager, self).get_queryset().annotate(totalwork=Sum('work__duration'), output_field=DurationField()) class Repairorder(models.Model): #... idrepairorder = models.autofield(primary_key=True) objects = RepairorderManager() For each Repairorder I want to display the 'totalwork', however this error appears: QuerySet.annotate() received non-expression(s): . and if I remove the output_field=DurationField() from the RepairorderMananager, it says: Cannot resolve keyword 'duration' into field. -
Upload a file, display the data and store them in a database
How to upload a file, parse it, display the content, modify the data and store them in a database in Django? Let's assume a Django model with name, date of birth, address... I'm using a form to upload a CSV file with different data per line. Now my question is, what is the best (and a save) way to display the data for modification and completing before storing them into the database? -
Post LIST OF OBJECTS from HTML/axios with multipart/form-data to DRF multipart parser
This is my serializer: class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) # reverse FK relation ParentSerializer also has an image field, so the request has to be multipart/form-data to support both image and data in a single request. The following code/test works fine: test_data = QueryDict('', mutable=True) dictionary = { 'name': ['test'], 'children[0]': [{'key1': 'val1', 'key2': 'val2'}] } test_data.update(MultiValueDict(dictionary)) test_serializer = self.get_serializer(data=test_data) test_serializer.is_valid(raise_exception=True) test_instance = test_serializer.save() ...because I'm manually creating the children list. The problem is I'm not able to do the same through axios/HTML form. The data being sent is converted to string. What are my options? I want to send list of child objects along with other data. DRF v3.9 & Django v2.2. -
How to I play an .wav file in an <audio> field by setting the source to my Audio field Model(DataBase)?
I haven't been able to find anything online that can help me with this yet. I am trying to play some .wav audio files that I have stored in my Django Model. I am having trouble finding a way to create an instance/query to my database and then being able to use that in my HTML page where my audio field is. Here is what I have so far... HTML <audio controls id="listen "> <source class="form-control" src="{{ }}" type="audio/wav"> </audio> Model.py class Media(models.Model): title = models.CharField(max_length=100) key = models.IntegerField() audioFile = models.FileField() duration = models.FloatField() isPlaying = False view.py def audioPlayer(request): return render(request, "Website/myWebSite.html" I am just trying to figure out a way I can set the source on the tag to pull from the Media Model. Any suggestions? -
How to access a parent model from one of my fk fields?
I'am trying to access a parent instance from its child. I have the following models class ModelA(models.Model): user_name = models.Charfield() points = models.Charfield() class ModelB(models.Model): user = models.ForeignKey(ModelA) points = models.Charfield() class ModelC(models.Model): model_b = models.OneToOne(ModelB) info = models.TextField() And I'am doing a query like this: ModelB.objects.filter({somefilters}).values('user__user_name') But I want to check if there is a reference to B in C, and if there is get the info. I can't start from ModelC as: ModelC.objects.filter({somefilers}).values('model_b__user__user_name') Because there maybe or not a record relating both models. Is possible to get starting from ModelB to get info from its parent ModelC? -
Aggregation in Django
Model: class A(models.Model): nr = models.IntegerField() class B(models.Model): points = models.IntegerField() class C(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) So for every A there are many entries in C, and for every B there are also many entries in C. But every entry in C there is exactly one entry in A and one in B. I would like to sum up the B.points for a given A. How can I do that in Django? I would know how to do that in SQL if that helps? -
passing headers to Django channels using Javascript Websockets to authenticate user using Token
i have no idea how to connect and authenticate django channels using token authentication because javascript websockets doesnt support passing headers to the server class TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 """ def __init__(self, inner): self.inner = inner def __call__(self, scope): headers = dict(scope['headers']) if b'authorization' in headers: try: token_name, token_key = headers[b'authorization'].decode().split() if token_name == 'Token': token = Token.objects.get(key=token_key) scope['user'] = token.user except Token.DoesNotExist: scope['user'] = AnonymousUser() return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) I have found this answer regarding authentication using token but the thing is I don't understand how to pass headers to the server token = Token.objects.get(key='175f76fd9b63a9477bf5f9a6f2e9a7f12ac62d65') if token.user: scope['user'] = token.user else: scope['user'] = AnonymousUser() return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) when ever i manually authenticate users the channels can recognize user and authenticate him i have tried def get(request): for user in User.objects.all(): token=Token.objects.get_or_create(user=request.user) if token.user: print("ok") else: print("not okay") print(token) adding this function in the same class TokenAuthMiddleware i thought this would work but it's not working so that i can use the token generated to authenticate users I just want to know is there any way where i can authenticate users using token -
Creating a comment-system in Django 2
I've tried creating a comment-system in Django 2 I have tried assigning the comment to a post ID. I still cant seem to figure it out. My models.py: class post_id(models.Model): user_post_id = models.IntegerField(null=True) class Comments(models.Model): post = models.ForeignKey(post_id, on_delete=models.CASCADE, null=True) post_comment = models.TextField(null=True) comment_id = models.CharField(max_length=255, null=True) class posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_text = models.TextField() post_likes = models.IntegerField(null=True) post_id = models.ForeignKey(post_id, on_delete=models.CASCADE, null=True) post_category = models.ForeignKey(Category, on_delete=models.CASCADE) post_likes = models.IntegerField(default=0, null=True) post_comments = models.ForeignKey(Comments, on_delete=models.CASCADE, null=True) datetime = models.DateTimeField(auto_now_add=True) user_ip = models.CharField(max_length=100) user_agent = models.CharField(max_length=255) -
Django TypeError at /url/ get() missing 1 required positional argument
I'm having trouble with this because in my localhost the url can receive 2 optional arguments, the url can receive just one but not both. testing the route locally works, but not when in production, i get this error: TypeError at /url/ get() missing 1 required positional argument: 'pk' in the urls.py file: urlpatterns = [ path('url/<int:pk>', Class.as_view()), path('url/', Class.as_view()), path('url/<int:option>',Class.as_view()), #etc... more routes below in my Class.py file: class Class(APIView): def get(self, request, pk = None, option = None): # more code below... Note: i change the name of the class & routes for job reasons... Not sure why works locally but not in server production, any ideas? what i'm missing? -
Django default session
I want to give user some default session when joining website, without pressing anything.One way is to include request.session['lang']='en' at the home page class but what if first time joining user tries to access another class. -
Why isn't Django detecting the data I'm sending in a javascript fetch POST request?
I'm POSTing data using the fetch api. In the body I send the employee_id, yet I'm getting a MulitDictKey error from Django saying it (and the other data, for that matter) wasn't received. Why isn't it sending? Is there something I'm missing? In my html file (in the script tag): const graduateEmployee = row => { const token = row.querySelector('INPUT').value fetch('/questions/ajax/update_employee', { method: 'POST', headers: { "X-CSRFToken": token, "Accept": "application/json", 'Content-Type': 'application/json' }, body:JSON.stringify({ employee_id: row.id, column: 'mentor_status', new_value: false }) }).then((res) => res.json()) .then((response) => console.log('Success:', JSON.stringify(response))) .catch((err)=>console.log('Error:', err)) } In my views.py: def update_employee(request): employee_id= int(request.POST["employee_id"]) column = request.POST["column"] new_value = request.POST["new_value"] employee = Employee.objects.get(employee_id = employee_id) employee[column] = new_value employee.save() return HttpResponse(f'{column} column for employee with id{employee_id} set to {new_value}') Error Page: MultiValueDictKeyError at /questions/ajax/update_employee 'employee_id' Request Method: GET Request URL: http://127.0.0.1:8001/questions/ajax/update_employee Django Version: 2.2.2 Exception Type: MultiValueDictKeyError Exception Value: 'employee_id' Exception Location: C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in getitem, line 80 Python Executable: C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['C:\Users\dklaver\mentor-program\mentor', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32', 'C:\Users\dklaver\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages', 'C:\Users\dklaver\mentor-program\mentor\helpers', 'C:\Users\dklaver\mentor-program\mentor\cron'] Server time: Fri, 5 Jul 2019 17:42:18 +0000 Traceback Switch to copy-and-paste view C:\Users\dklaver\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in getitem list_ = super().getitem(key) … ▶ Local vars During handling of the above exception ('employee_id'), another exception … -
Django: how to mock a class inside the API view
Title might be a little confusing. Say I have an APIView with a post method. Inside the post method, I introduced a class that has its own method. In this case, it's a class that deals with uploading to S3, which is something I want to skip when running unittest. class SomeView(APIView): def post(self): # do something here input1 = some_process(payload_arg1) input2 = some_other_process(payload_arg2) uploader = S3Uploader() s3_response = uploader.upload_with_aux_fxn(input1, input2) if s3_response['status_code'] == 200: # do something else return Response('Good job I did it!', status_code=200) else: return Response('noooo you're horrible!', status_code=400) Real code has different function calls and responses, obviously. Now I need to mock that uploader and uploader.upload_with_aux_fxn so I don't actually call S3. How do I mock it? I tried in my test script class SomeViewTestCase(TestCase): def setUp(self): self.client = APIClient() uploader_mock = S3Uploader() uploader_mock.upload_support_doc = MagicMock(return_value={'status_code': 200, 'message': 'asdasdad'} response = self.client.post(url, payload, format='multipart') But I still triggered S3 upload (as file shows up in S3). How do I correctly mock this? -
Django create related objects in save() not saving to DB
I have a mode Profile that has a related object set of ProfileSiteFields (ProfileSiteFields has a FK to Profile). I want to create ProfileSiteFields on creation of a new Profile based on some business logic. For some reason, the related objects are created fine, but not saving to the DB. def save(self, *args, **kwargs): is_new_object = self._state.adding super(Profile, self).save(*args, **kwargs) if is_new_object: self._create_profile_site_fields_objects() def _create_profile_site_fields_objects(self): site_ids_to_create = SiteWhiteLabeling.objects.filter( copy_profile_id_to_site_fields=True ).values_list('site', flat=True) for site_id in site_ids_to_create: site_field_obj = ProfileSiteFields.objects.create( profile=self, site_id=site_id, external_id=self.unique_id ) When I log out site_field_obj in the for loop, everything is as expected - something like this: { '_profile_cache': Profile : TEST NEW PROFILE 6 - Unknown, '_state': <django.db.models.base.ModelState object at 0x7f21644dd2d0>, 'site_id': 7, 'external_id': u'P3DAB584', 'id': 23498, 'profile_id': 28611 } ... it just doesn't save to the DB. I also tried this syntax site_field_obj = ProfileSiteFields(...) site_field_obj.save() and calling .save() from the debugger, but when I query for the object in ProfileSiteFields, it's not there. Any suggestions on what is missing? -
How to have a field represent the count of related objects
I have a couple of Django models, Channel and Recording. Channels have a one-to-many relationship with recordings, such that a channel may have many recordings. Within the Channel model, I currently have 2 fields, num_recordings, and storage_size, which are right now created as Integers, but which I want to have dynamically generated as the result of a DB query. E.g. num_recordings should be the current count of recordings on a given channel, and storage_size should be the sum of a field "size" for each of the recordings on a given channel. I'm using Django rest framework to give a JSON representation of the models, and want it so that when I query the Channel, I see these two fields as Integers, but don't want to have to calculate these separately, e.g. it would be ideal if when you query the Channel endpoint, it would perform a count on the recording relationship, and return that as "num_recordings" and a sum on the recording.size field for all recordings in the relationship and report that on the storage_size field. How can I do this? -
My domain name keep switching from example.com to mydomainname.com
After struggling to finish the project, I built a sitemap. After pushing it digital ocean, I and signing up to Google search console it gave out an error (from Google console) invalid domain name. When I looked at the generated file from mydomainname.com/sitemap.xml I saw that example.com is appended to sitemap instead of my domain name. I removed example.com from Sites. But it's showing same thing. I found an article on stackoverflow and realised that I should've changed the name from instead of deleting it. I went on my server and turned the id of mydomainname.com to 1 from the database, now mydomainname.com and example.com is swapping ..? How can I fix this?