Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do I receive a name error? 'AuthorAdmin not defined
Here is the code detail. admin.py from .models import Author, Genre, Book, BookInstance @admin.register (Author, AuthorAdmin) class AuthorAdmin(admin.ModelAdmin): pass models.py The neccesary imports have done. I have been trying to figure out why i recieve the error that AuthorAdmin has not be defined class Author(models.Model): first_name = models.CharField( max_length=100) last_name = models.CharField( max_length=100) date_of_birth = models.DateField(null = True, blank = True) date_of_death = models.DateField(null = True, blank = True) def get_absolute_url(self): return reverse('author-detail', args = [str(self.id)]) -
'RawQuerySet' object has no attribute 'distinct'
I have this django raw query User.objects.raw("Select distinct * from users") but brings `'RawQuerySet' object has no attribute 'distinct'. What could be the problem and the solution? -
How to remove extra data from JSONField in django rest framework?
I have a model like this: class Things(models.Model): data = models.JSONField(default=dict) and structure of data is like this: { "item" : "sugar", "quantity" : "2", "cost" : 220 } Note that it is not mandatory for data to contain all 3 keys, all of them are optional. The difficult part is that I don't want any other keys, apart from these 3 keys, to be present in data field. Creating a serializer can help to ensure presence and format of these 3 fields but it will not ensure absence of other fields. How can I achieve this thing in django rest framework? -
Typecasting from str to int inside jinja
I encountered a scenario where I need to fetch numeric data from the database and run that number of loops on my template, something like: in my views.py: def quesSetting(request): questionSet_obj = questionSet.objects.filter(id = pk).first() quesSetting_dict = { 'noNumeric' : questionSet_obj.noNumeric, } return render(request, 'app/quesSetting.html', quesSetting_dict) my template: {% for i in noNumeric|get_range %} <input type="text" class="form-control" name="numericQuestion" array_column="{{ i }}"> {% endfor %} Now it says following error: 'str' object cannot be interpreted as an integer So, I try to typecast the noNumeric into int like this: {% for i in int(noNumeric)|get_range %} <input type="text" class="form-control" name="numericQuestion" array_column="{{ i }}"> {% endfor %} This time it gives following error: Could not parse some characters: int|(noNumeric)||get_range How can I fix this issues? -
bootstrap5 sidebar appears above the block content, how to make it sticky-left
at start i must say that i'm noob especially when it comes to css. I did a django blog with bootstrap5, following the advices from python crash course book. every of my templates, extends base.html where i have code like below. The problem is that whatever i try, it always go above, between or under my block contents, I don't know how to "override" my blocks and stick my sidebar to the left. Under the code i'll post images with my little paint vizualizations. The upper one is how it is right now, and second how i want it to be. <body> <nav> <!--thats sticky top navbar i'll skip this cause it work good --> </nav> <div class="container-fluid"> <div class="row w-50 flex-column flex-md-row"> <aside class="col-12 col-md-3 col-xl-2 p-0 bg-dark flex-shrink-1"> <nav class="navbar navbar-expand-md sticky-start navbar-dark bd-dark flex-md-column flex-row align-items-center py-2 text-center" id="sidebar"> <div class="text-center p-3"> <img src="..." alt="profile picture" class="img-fluid rounded-circle my-4 p-1 d-none d-md-block shadow"> <a href="#" class="navbar-brand mx-0 font-weight-bold text-nowrap">RETOVSKEJ</a> </div> <button type="button" class="navbar-toggler border-0 order-1" data-toggle="collapse" data-target="#nav" aria-controls="nav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse order-last" id="nav"> <ul class="navbar-nav flex-column w-100 justify-content-center"> <li class="nav-item"> <a href="#" class="nav-link active">Edit profile</a> </li> <li class="nav-item"> <a href="#" class="nav-link">Projects</a> … -
What is the difference between request.GET.get("some_value") and request.data["some_value"] in Django REST Framework
When writing DRF views that interact with my React Native Frontend I often find myself wondering whether I should be sending the requests from the frontend as .get('/someAPI/', { some_value: something }) or .get('/someAPI/', { params: { some_value: something } }) From what I understand, the first request's syntax then requires django to reference the request's params as request.data["some_value"] vs the second requiring request.GET.get("some_value") Is there a best practice to using these syntaxes differently, or is it just preference?? Thanks! -
DJANGO relationship queries
I require assistance building a query for related fields. I need to show the each Product and its associated Product_Line item. The relationship between the Product Line Item to the Product is one to many with the Product_Line item being unique to the Product. I have included the following models, the relevant view and the html for the home as well as an output of the fields on the page. Please help formulary/models.py class Product(models.Model): #linkedProduct = models.ForeignKey(Product_Line, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=255) form = models.ForeignKey(Form, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.pk) + " " + self.name + " " + str(self.form) class Product_Line(models.Model): linked_product = models.ForeignKey(Product, on_delete=models.CASCADE) active = models.ForeignKey(Active, on_delete=models.CASCADE, null=True, blank=True) strength = models.IntegerField(default=0, null=True, blank=True) UoM = models.ForeignKey(Unit, on_delete=models.CASCADE, null=True, blank=True) class Meta: ordering = ['linked_product'] def __str__(self): return str(self.pk)+ " "+ str(self.active) + " " + str(self.strength) + " " + str(self.UoM) inventory/models.py from django.db import models from list.models import Form # Create your models here. class Active(models.Model): long_descr = models.CharField(max_length=10) drug_form = models.ForeignKey(Form, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.long_descr class Excipient(models.Model): long_descr = models.CharField(max_length=10) drug_form = models.ForeignKey(Form, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.long_descr formulary/views.py from django.shortcuts import render from .models … -
Django REST framework GET requests test
I am trying to test my API GET method, as you can see in my code, I have ProposalCallsViewSet which have call search method: class ProposalCallsViewSet(viewsets.ModelViewSet): queryset = BsfCall.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = BsfCallsSerializer @action(detail=False, methods=['GET']) def call_search(self, request): try: data = request.query_params['data'] print("this is the data:", data) data = json.loads(data) organization = data['organization'] tags = data['tags'] from_date = data['first_date'] to_date = data['second_date'] print(data) if organization == 'BSF': bsf_result = get_bsf_call_by(tags, from_date, to_date) else: bsf_result = get_bsf_call_by(tags, from_date, to_date) BSF = [] for value in bsf_result: BSF.append({'CallID': value.CallID, 'deadlineDate': value. deadlineDate, 'organizationName': value.organizationName, 'information': value.information, 'areaOfResearch': value.areaOfResearch}) response = {'BSF': BSF} except: response = {'BSF': [], 'Error': 'Error while searching for calls'} return Response(response, status=status.HTTP_200_OK) In this method the output I am trying to return is objects from the DB, since I don't have front end I need to check this manually. As you can see in the post man I passed the Query Params and its getting response = {'BSF': [], 'Error': 'Error while searching for calls'} I tried to print the query params in the method but it did not print anything in the pycharm console.Here is the postman photo -
How to keep three cards on the same line in bootstrap-5?
I have a Django template for loop, which loops over the first three cards in the database. But they aren't staying on the same line. Only 2 of them are, but I want three cards on the same line. <div class="row"> {% for jax in u_jaxes|slice:"0:3" %} <div class="col-5 m-2"> <div id="card2" class="card"> <div class="card-body"> <a href="{% url 'edit_jax' jax.title %}">{{ jax.title|truncatechars:21 }}</a><br><br> <img src="https://cdn1.iconfinder.com/data/icons/logotypes/32/badge-html-5-128.png" alt="Badge, html, html5, achievement, award, reward, trophy"/ height="17" width="17"> HTML, CSS, JS <small><span style="float:right"> {{ jax.date_created|timesince }} ago </span></small> <a href="{% url 'edit_jax' jax.title %}" class="stretched-link"></a> </div> </div> </div> {% endfor %} </div> Note, that there is a particular spacing between the cards. I want the spacing to be the same too, along with the three cards being on the same line. -
My query returns an Id instead instead of the actual values
I have the query below on the following tables but my output returns the product Id instead of the product name. Any suggestion or help would be highly appreciated. #my query Stock.objects.values('name').annotate(List=Count('name'), total=Sum('quantity')) #model.py class Product (models.Model): name = models.CharField(max_length=100, blank=True, null=True) class Stock (models.Model): name = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(defualt=0) ........ -
Sending base64 encoded image to Rekognition is coming back with "InvalidImageFormatException"
From what I can tell, I'm sending a base64 encoded image to Rekognition, but it comes back with: botocore.errorfactory.InvalidImageFormatException: An error occurred (InvalidImageFormatException) when calling the DetectFaces operation: Request has invalid image format Per the documentation, base64 should be fine: Amazon Rekognition Image operations can analyze images that are supplied as image bytes or images stored in an Amazon S3 bucket. These topics provide examples of supplying image bytes to Amazon Rekognition Image API operations by using a file loaded from a local file system. You pass image bytes to an Amazon Rekognition API operation by using the Image input parameter. Within Image, you specify the Bytes property to pass base64-encoded image bytes. Image bytes passed to an Amazon Rekognition API operation by using the Bytes input parameter must be base64 encoded. The AWS SDKs that these examples use automatically base64-encode images. You don't need to encode image bytes before calling an Amazon Rekognition API operation. For more information, see Images. What I am doing differently is I'm not opening a local file. I built a barebones Django application that requests access to the user's web camera, they can take a picture, then submit it where Rekognition analyzes it. So … -
Django Login With Google No Django-Allauth
This seems like a simple question, but after researching for a bit, all I got were tutorials for using django-allauth. I am not going to use django-allauth because... well I've got reasons. So my question is, can I register and login users using google WITHOUT django-allauth. Any help will be appreciated! -
Why Python django deployment in Heroku not executing ajax and jquery?
I am deploying a django application in Heroku where I have some js,jquery and ajax to be executed in the template. Everything works fine in my local machine. But the jquery and ajax part is not working in Heroku. I am including a template here for reference. Here I am using Skulpt(an option to run python in the browser). If anyone have idea of how to resolve this issue and what is the reason behind this, please help . Thanks for your feedback. {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Assessment</title> <style> .question, .code-area { display: table-cell; } .question { width:50%; left: 0; overflow-y:auto; overflow-x: auto; background-color: white; } .code-area { border-left: 2px solid navy; width:50%; right: 0; background-color: white; } </style> <script src="{% static '/codemirror-5.58.3/lib/codemirror.js' %}"></script> <link href="{% static '/codemirror-5.58.3/lib/codemirror.css' %}" rel="stylesheet"> <link href="{% static '/codemirror-5.58.3/theme/dracula.css' %}" rel="stylesheet"> <script src="{% static '/codemirror-5.58.3/mode/python/python.js' %}"></script> <script src="http://skulpt.org/static/skulpt.min.js" type="text/javascript"></script> <script src="http://skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script> <script src="http://www.skulpt.org/js/skulpt.min.js" type="text/javascript"></script> <script src="http://www.skulpt.org/js/skulpt-stdlib.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> // output functions are configurable. This one just appends some text // to a pre element. function outf(text) { var mypre = document.getElementById("output"); mypre.innerHTML = mypre.innerHTML + text; } // Here's everything you need to … -
403 Forbidden: AWS S3, Django, S3Boto3Storage, CKEditor
After several days of continuous attempts, I'm nearly ready to give up. I have a popular setup and I see many people have similar issues, but there is no comprehensive (and working!) answer. I get this sort of errors in browser: GET https://hull2hull-bucket.s3.amazonaws.com/ckeditor/ckeditor/?AWSAccessKeyId=AKIAVIMQUGHJHHUVNIPN&Signature=LDq%2F5bhKJUUIUIUUO3GGoH0Iksoho%3D&Expires=1618438498lang/en.js&t=K5H9 net::ERR_ABORTED 403 (Forbidden) My website is powered by Django and hosted on Pythonanywhere. Static files are on Amazon S3 with a private policy. I connect Django and S3 bucket with S3Boto3Storage. Most of my static files (picture library, admin files etc) are working fine, but not when it comes to some js files or specific components. Particularly CKEditor and Debug Toolbar are refusing to work. What I tried: make my bucket public - FAILED (but maybe did it wrong somehow? how can I check the effect?) edit CORS - FAILED (I had some CORS errors initially, those were fixed) My current CORS: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "HEAD", "GET" ], "AllowedOrigins": [ "https://hull2hull-bucket.s3.amazonaws.com", "http://127.0.0.1:8000", "http://127.0.0.1", "http://localhost", "http://localhost:8000" ], "ExposeHeaders": [] } ] change policy - FAILED My current policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::hull2hull-bucket/" } ] } install corsheaders - FAILED (again, maybe … -
working with Q in django and combining QuerySet
There are two models Orders and Clients, when created, the same related_uuid is generated for each. That is, they are so connected. When searching on the site, you need to find all occurrences in both models and display all Orders, including those where related_uuid occurs in the Clients model. models.py class Orders(models.Model): device = models.CharField(max_length=150) related_uuid = models.CharField(max_length=22, blank=True) def __str__(self): return self.device class Clients(models.Model): name = models.CharField(max_length=150) related_uuid = models.CharField(max_length=22, blank=True) def __str__(self): return self.name views.py def getQuery(self): search_query = self.request.GET.get('filter') results_query1 = Orders.objects.filter(Q(device__icontains=search_query)) results_query2 = Clients.objects.filter(Q(name__icontains=search_query)) conds = Q(related_uuid__icontains=results_query1) | Q(related_uuid__icontains=related_query2) search_filter_three = Orders.objects.filter(conds) return search_filter_three that is, I am looking for occurrences in both models. then I try to select all inputs in the Orders model by the related_uuid field from both models. outputs django.db.utils.OperationalError: (1241, 'Operand should contain 1 column (s)') -
Documenting Django project with Sphinx
I am following this tutorial in order to generate documentation for my Django project but, when I type make html, I get this error: Configuration error: There is a programmable error in your configuration file: Traceback (most recent call last): File "/Users/hugovillalobos/.local/share/virtualenvs/sacbeh-backend-lZZWPwwy/lib/python3.8/site-packages/sphinx/config.py", line 327, in eval_config_file execfile_(filename, namespace) File "/Users/hugovillalobos/.local/share/virtualenvs/sacbeh-backend-lZZWPwwy/lib/python3.8/site-packages/sphinx/util/pycompat.py", line 88, in execfile_ exec(code, _globals) File "/Users/hugovillalobos/Documents/Code/sacbeh-project/sacbeh-backend/docs/conf.py", line 18, in <module> django.setup() File "/Users/hugovillalobos/.local/share/virtualenvs/sacbeh-backend-lZZWPwwy/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/hugovillalobos/.local/share/virtualenvs/sacbeh-backend-lZZWPwwy/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Users/hugovillalobos/.local/share/virtualenvs/sacbeh-backend-lZZWPwwy/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/Users/hugovillalobos/.local/share/virtualenvs/sacbeh-backend-lZZWPwwy/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sacbeh_backend.settings' make: *** [html] Error 2 This is my conf.py file: import os import sys import django sys.path.insert(0, os.path.abspath('..')) os.environ['DJANGO_SETTINGS_MODULE'] = 'sacbeh_backend.settings' django.setup() # -- Project information ----------------------------------------------------- project = 'sacbeh_backend' copyright = '2021, Attractora' author = 'Attractora' # The full version, including alpha/beta/rc tags release = '0.1' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming … -
Annotating query with sum of multiplication of two fields from a related model in Django
Relevant models are: class Score(models.Model): chouette = models.ForeignKey( Chouette, on_delete=models.CASCADE, related_name="scores" ) game = models.IntegerField(blank=True, null=True) player = models.ForeignKey(User, on_delete=models.CASCADE, related_name="scores") position = models.CharField(max_length=10, blank=True, null=True) score = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True) objects = ScoreManager() class User(AbstractUser): name = CharField(_("Name of User"), blank=True, max_length=255) handle = CharField(max_length=10) xp = IntegerField(default=0) objects = CustomUserManager() I have a custom manager for User that builds a queryset with a lot of annotations, but the one I am struggling with relates to Score. I am trying to calculate a total_winnings annotation that does a subquery on each User and multiplies the score field in Score for each Score instance associated with a user by a field in the Chouette model (not shown--just a decimal field called stake). I have tried several variations of this as my subquery: def build_chwinnings(self): total_winnings = self.filter(pk=OuterRef("pk")).annotate( total_winnings = Sum(F("scores_score") * F("scores__chouette__stake") ) ) return self.annotate(total_score=Subquery(total_score.values("total_score")) But they all result in the following exception: django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression The "easiest" way to do this would be to add the calculated value (scores__score * scores__chouette__stake) as a field to the Score model, but all the boo birds hate duplicating data within … -
daphne failed to run in systemd service file
I created the following systemd service script for running django project using daphne: [Unit] Description=Service daphne After=network.target [Service] User=daphne_user WorkingDirectory=/home/daphne_user/Project-app Environment=DJANGO_SETTINGS_MODULE=ProjectApp.settings ExecStart=/home/daphne_user/project-app/venv/bin/daphne -b 0.0.0.0 -p 8000 ProjectApp.asgi:application 1>>/home/daphne_user/app.log 2>>/home/daphne_user/app.log Restart=on-failure [Install] WantedBy=multi-user.target The service fails to run and shows Start request repeated too quickly. Is their something am i missing in the service script ? service status -
How to execute Celery periodic tasks on Django project
Seems that it's very easy to implement periodic tasks with Celery, just do something like: from celery.schedules import crontab from celery.task import periodic_task @periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon")) def every_monday_morning(): print("This is run every Monday morning at 7:30") Some tutorials suggest to put these tasks on a file called "tasks.py", but after doing that now what?. How I tell django or celery to "activate" or "run" these tasks?. Also, those kind of tasks relays only on Celery or there's the need to use Celery + Redis (I already have configured it), but Redis it's never mentiones on tutorials or documentation for periodic tasks. -
How to fetch final destination URL after redirects?
I am trying to test valid URLs in my model using Django Custom Management Commands. I have the following model, and I need to test whether there are inactive URLs (HTTP 404 error). class Association(models.Model): name = models.CharField(max_length=25, blank=True, null=False) publication_doi_url = models.TextField(blank=True) Some URLs have multiple redirects; hence I wrote a function to fetch the final URL. It works mainly except few. For example, the URL https://doi.org/10.1603/EC11207 redirect shows this as the final URL https://academic.oup.com/jee/article-lookup/doi/10.1603/EC11207. However, this returns the HTTP response code is 302. There is one more redirect. How can I get the final URL? I assume the journals allows the access based on IP. The site doesn't require username/password. Any pointers will be helpful. def return_final_url(url_link): response = requests.get(url_link) finalurl = '' if response.history: for resp in response.history: pass finalurl = response.url return finalurl class Command(BaseCommand): help = 'Prints inactive urls (HTTP 404 error)' def handle(self, *args, **kwargs): for item in Association.objects.all(): base_url = "https://doi.org/" url = base_url + item.publication finalurl = return_final_url(url) print("finalurl", finalurl) response = requests.get(working_url) try: response.raise_for_status() except requests.exceptions.HTTPError: print("HTTPError") -
Django: How to access the previous model class instances while creating new instance of the same class?
I have a model in my django app like below: models.py class Profit(models.Model): month = models.CharField(max_length=100) amount = models.IntegerField() total_profit = models.IntegerField() Now, what I want to do is that whenever a new instance/object is created for this class, the user puts the month and the amount of profit for that month, But I want that it also calculates the total profit the user got up till the current profit, by adding all the profits that was being added in the past. For example. if the user is adding the profit for month April, then it add all the values in the amount field of previously added objects of (March, February, January and so on..) and put it in the field total_profit. So that the user can see how much total_profit he got at each new entry. -
'ManyToManyDescriptor' object is not callable while copying M2M relation
I have this relation defined in x\research.py file. research_groups = models.ManyToManyField(ResearchGroup, related_name='researchs', blank=True, through='ResearchResearchGroups') Then i want copy it to y\research.py file with research.research_groups.set(Research.research_groups.all()) And while im trying to use it i get 'ManyToManyDescriptor' object is not callable How can i handle assigning m2m relation to another place? -
'QuerySet' object has no attribute 'simplified'
I am trying to do a fairly simple GET request that leads to a query with DRF: def get(self, request, character): char_entry = Dictionary.objects.filter(Q(simplified=character) | Q(traditional=character)) serializer = DictionarySerializer(char_entry) return Response({"character": serializer.data}) My DictionarySerializer looks like this: from rest_framework import serializers from .models import Dictionary class DictionarySerializer(serializers.ModelSerializer): class Meta: model = Dictionary fields = ["id", "simplified", "pinyin_numbers", "pinyin_marks", "translation", "level", "traditional", ] And my Dictionary model looks like this: class Dictionary(models.Model): traditional = models.CharField(max_length=50) simplified = models.CharField(max_length=50) pinyin_numbers = models.CharField(max_length=50) pinyin_marks = models.CharField(max_length=50) translation = models.TextField() level = models.IntegerField() class Meta: db_table = 'dictionary' indexes = [ models.Index(fields=['simplified', ]), models.Index(fields=['traditional', ]), ] As far as I can tell, this should serialize all the fields from the Dictionary table, including simplified. Why can't Django find the attribute? What am I missing? -
Ajax call doesn't prefix window.location.href if url starts with /
I have been seeing this behavior while trying to translate some backend calls. What happens is that $.ajax gets called with given arguments and the call that is made may or may not have the current location of the window (current url). For instance, At localhost:8000, a .js file calls $.ajax({ type: "GET", async: false, url: /myendpoint/v1/, data: champs, dataType: 'html', success: function (response) { something... } }) The result request translates to: curl "http://myendpoint/v1/" ^ -H "Accept: text/html, */*; q=0.01" ^ -H "Referer: http://localhost:8000/" ^ -H "X-CSRFToken: a-csrf-token" ^ -H "X-Requested-With: XMLHttpRequest" ^ -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36" ^ -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" ^ --data-raw "some-data=1" ^ --compressed The preflight and the actual request fail. The preflight naturally gives a network/dns resolution error (failed) net::ERR_NAME_NOT_RESOLVED since "http://myendpoint/v1/" is not a valid hostname. However, if I declare the url without the leading slash, it actually calls the good host with the proper relative URL. Having http://localhost:8000 and a relative url to the server as /myendpoint/v1/ seems correct to me. I tried debugging ajax to see what it does but I didn't get to any conclusion. The RFC specification talks a bit … -
Pytest test suite randomly has errors on GitHub Actions without changes
I have a problem with running my tests for a Python project inside Github Actions. Locally the test suite works like a charm and always succeeds. When it is run on Github Actions it succeeds in 1 out of 3 runs with no changes between the individual runs. It seems as the creation of the Django app during the test doesn't always work as expected. Even though I try to assure it is created inside the pytest fixture. @pytest.fixture def installed_app(settings): app_name = f'test_theme_{str(uuid.uuid4()).replace("-", "_")}' app_path = Path(app_name) call_command("tailwind", "init", app_name) while not app_path.is_dir(): time.sleep(1) settings.INSTALLED_APPS += [app_name] settings.TAILWIND_APP_NAME = app_name app_label = app_name.split(".")[-1] app_path = Path(apps.get_app_config(app_label).path) yield app_name, app_path if app_path.is_dir(): shutil.rmtree(app_path) I am confused what the reason is. I also tried it with Travis CI with the same problem. Any help is highly appreciated. Here is the code of the tests. Tests: https://github.com/oliverandrich/django-tailwind-postcss/blob/main/tests/tests.py Pytest fixture: https://github.com/oliverandrich/django-tailwind-postcss/blob/main/tests/conftest.py ============================= test session starts ============================== 9 platform linux -- Python 3.7.10, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 10 django: settings: tests.test_settings (from ini) 11 rootdir: /home/runner/work/django-tailwind-postcss/django-tailwind-postcss, configfile: pyproject.toml 12 plugins: django-4.1.0, cov-2.11.1 13 collected 11 items 14 15 tests/tests.py .....E 16 17 ==================================== ERRORS ==================================== 18 ___________________ ERROR at setup of test_tailwind_install ____________________ 19 20 …