Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run docker image on local server
I am so new in Docker and i need to run a dokcerized django project which is already writen by another developer , this is Dockerfile.dev: FROM python:alpine RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && apk add jpeg-dev zlib-dev libjpeg ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt COPY entrypoint.sh /app/ ENTRYPOINT [ "./entrypoint.sh" ] EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and dcoker-compose.yml : services: event: build: context: . dockerfile: Dockerfile.dev volumes: - ./:/app env_file: - ./envs/development.env command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" depends_on: - event-database event-database: image: postgres:alpine env_file: - ./envs/development.db.env networks: default: name: mizban when i create an image with docker build --tag and then run it with docker run imageid it does not run CMD part to run project on the 0.0.0.0:8000 port any suggestions? -
How to write health check for graphql apis without http
I have a K8s cluster in which there is a pod which has Gjango + Graphql apis. I need to write a health check job which makes sure that my apis are up and running. I do not want to use http style request to check the health. Rather I would like to use Django. Please guide me how can I do that? -
Is there a way to preserve html checkbox state after reload in Django?
Sample code is below. I would like to keep the checkbox checked after page reload once submit button has been pressed <td><input type="checkbox" value="{{ item }}" name="selectedcheckbox"/></td> -
login_oculto() takes 1 positional argument but 2 were given
mi codigo parece funcionar, cuando pongo mal el usuario o la contraseña me funciona el mensaje de error, sin embargo cuando quiero ingresar realmente a la pagina oculta, me arroja lo siguiente: TypeError at /administracion/ingreso login_oculto() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://localhost:8000/administracion/ingreso?next=/oculto Django Version: 3.2.8 Exception Type: TypeError Exception Value: login_oculto() takes 1 positional argument but 2 were given Exception Location: C:\Users\OGT\Museum\mu2\views.py, line 48, in login_oculto Python Executable: C:\Users\OGT\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\OGT\Museum', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib\site-packages'] login.html <div class="contenedor_formulario"> {% if error %} <p style="color: black;">{{ error }}</p> {% endif %} <form action="" method="POST" style="text-align: center;"> {% csrf_token %} <table class="tabla_formulario"> <form method="POST" action="{% url 'anyname' %}"></form> <input type="text" placeholder="Usuario" name="username" /> <input type="password" placeholder="contraseña" name="password" /> </table> <input class="boton_formulario" type="submit" value="Ingresar"> </form> </div> urls.py urlpatterns = [ path('administracion/ingreso', views.login_oculto, name='anyname'), path('oculto', views.oculto,name='oculto') ] views.py def login_oculto(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') usuario = authenticate(request, username = username, password = password) if usuario: login_oculto(request, usuario) return redirect('oculto') else: return render (request, 'mu2/login.html', {'error': 'usuario o contraseña incorrecta'}) return render(request, 'mu2/login.html') -
DoesNotExist - matching query does not exist
I have this django class-based view where i am trying to overwrite the get_queryset function because i want get to the inserted values from the frontend to search in my database after the subject with that name and then get the id. but when i call the view it gives me a "Subject matching query does not exist." because the subject_val is None. That makes sense because the user has not submitted the values jet.. so how do i get it to wait until a user have choosen "submit class AttendanceList(LoginRequiredMixin, ListView): model = AttendanceLog template_name = "./attendancecode/showattendance.html" def get_queryset(self): class_val = self.request.GET.get('class') subject_val = self.request.GET.get('subject') sub = Subject.objects.get(name=subject_val).id new_context = get_statstic(class_val, sub) return new_context def get_context_data(self, **kwargs): context = super(AttendanceList, self).get_context_data(**kwargs) context['class'] = self.request.GET.get('class') context['subject'] = self.request.GET.get('subject') return context -
Why Bokeh radioButtonGroup doesn't work in my django application?
i'm trying to develope a webapp for my master thesis. I used Bokeh to do interactive plot, and i embedded it in a django app. The problem is that i don't manage to do something with js_on_change or js_on_click of radiobuttongroup. This is my view: def DTA_webAPP(request): context={} result = None imps = pd.DataFrame(columns=["1","2","3","4","5"]) # i need this to avoid problem in create_grid in plotting.py dta = pd.DataFrame(columns = ["3","4"]) fig = myfig(imps,dta) script,div = components(fig.layout) form = DTAselection(request.POST,request.FILES) if request.method == 'POST' and "Compute" in request.POST: if form.is_valid(): data = pd.read_csv(request.FILES["ImportData"],sep = "\t", skiprows = [1,2]) imps, dta = main(data, form['method_of_discretization'].value(),float(form['regularization_parameter'].value()), int(form['regularization_order'].value()), int(form['number_of_point'].value()), form['col_selection'].value()) fig = myfig(imps, dta) script, div = components(fig.layout) imps.to_csv("result_imps.csv", index = False) dta.to_csv("result_dta.csv", index = False) result = "Ok, boy" context = {'form': form, 'script':script, 'div':div, "result":result} return HttpResponse(render(request, "dta_webapp.html", context)) the figure is created in the class myfig. This is my class myfig: LABELS = ["IMPS","REAL RESIDUALS", "IMAG RESIDUALS"] class myfig(object): def __init__(self, df_data, df_dta): self.df_data = df_data self.df_dta = df_dta self.radio_button_group = RadioButtonGroup(labels=LABELS, active=0) self.source = None self.plot = self.create_grid() self.radio_button_group.js_on_change('active', CustomJS(args= dict(s=self.source, p = self.plot.children[0], x = self.df_data.columns[1], y = self.df_data.columns[2], ), code=""" console.log('radio_button_group: active=' + this.active, this.toString()); const s1 = new … -
No Module named <module_name> but i have the module correctly linked
My actual folder structure is the next one >django_app/ >django_models/ >Model_1 >django_views/ >View_1 >models.py >views.py Inside 'models.py' i have this: from django_app.django_models.Model_1 import Model_1(This is the class name) but when i try to run server i get this error: from django_app.django_models.Model_1 import Model_1 ImportError: No module named django_models.Model_1 i have done this before in django 3.2 and restframework, but rn isn't working as expected *Python == 2.7 *Django == 1.6.5 this is an old project from my company and we dont have time to uptade it to newer versions. -
MPTT Django how to get children with user_id = some_user_id. NOT ALL children
def get_queryset(self): if not self.request.user.is_authenticated: # for swagger generation only return CannedAnswer.objects.none() if self.action in ['list']: return CannedAnswer.objects.filter( Q(agent=self.request.user) | Q(agent__isnull=True) | Q(group__in=self.request.user.groups.all())).get_cached_trees() else: return CannedAnswer.objects.filter(agent=self.request.user) This code returns me all children, but I want to get children who have agent = self.request.user -
wagtail api how to expose snippets and serialize nested data
the problem is this, i've created a snippet and i want to expose it but i don't know how to serialize nested data. here my code: models.py @register_snippet class TeamMember(ClusterableModel): name = models.CharField(max_length=80) description = models.CharField(max_length=80) panels = [ FieldPanel('name'), InlinePanel('tasks', label=('Tasks')), ] class Task(Orderable): team_member = ParentalKey('adm.TeamMember', related_name="tasks") task_name = models.CharField(max_length=80) endpoints.py class TeamMemberAPIEndpoint(BaseAPIViewSet): model = TeamMember body_fields = BaseAPIViewSet.body_fields + [ 'name', 'description', 'tasks', ] listing_default_fields = BaseAPIViewSet.listing_default_fields = [ 'name', 'description', 'tasks', ] the result is: "items": [ { "name": "python team", "description": "", "tasks": [ { "id": 1, "meta": { "type": "adm.Task" } }, { "id": 2, "meta": { "type": "adm.Task" } } ] } how can i resolve this problem? -
Select latest record in the group with ordering
I am having trouble writing a query using Django ORM, I want to find the latest record in each group. I am putting chat messages in the model and I want to find the latest chat of each user and show chats latest chat of each user and with the latest user's chat on the home screen just like in WhatsApp, Skype or similar apps. Currently, I am using the following query, Chats.objects.all().order_by('user_id', '-date').distinct('user_id') Using this I am able to get the latest chat of each user but I am not able to get the sequence correct. The result of the query is in the order of which the users were created in the database which I understand is correct, but I want to show the user who sent the latest chat at the top. My Models.py class Chats(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) chat = models.CharField(max_length=1023, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) Thank you so much, Please let me know if any other information is required. -
Deleting and creating in CreateView django
Hello I am making django to-do list and I have a question. Am i able to delete and create elements in one view? Personally I would not use CreateView for that and make it like in 'def post' and ignore 'get_success_url' but is it good and djangonic practice? views.py class Home(CreateView): model = Item template_name = 'home/todo.html' form_class = itemCreationForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['items'] = Item.objects.all() return context def get_success_url(self): return reverse('home-page') def post(self, request): form = itemCreationForm() if 'delete' in self.request.POST: print('deleted') return redirect('home-page') if 'add' in self.request.POST and form.is_valid(): form.save() return HttpResponse('home-page') HTML <div class="card__items-list"> {% for item in items %} <div class="card__item-row"> <p class="card__item">{{ item.name }}</p> <form action="{% url 'home-page' %}" class="card__delete" method="POST"> {% csrf_token %} <button class="card__delete__button" name="delete" type="submit">&#10008</button> </form> </div> {% endfor %} </div> <form name="add" method="POST"> {% csrf_token %} {{ form }} <button name="add" class="submit-button" type="submit">Submit</button> </form> </div> -
psql query returns blank rows
I store data from django in a postgreSQL database. My data is a huge nested list of floats with about 3 thousand rows. It looks like this: [[0.1, 0.2, 0.3], [0.3, 0.5, 0.6], [0.7, 0.8 0.9]] I tried to query it in pgAdmin 4, but it gives an output with a huuge delay. Now I am trying to query it with psql and it gives out only blank rows. my query: SELECT * FROM public."abc" LIMIT 1; what I get: id | and then a lot of blank rows. -
How to (de)serialize float list into models using Django REST Framework model serializer?
TL; DR How to create both serializers.Patient and serializers.Temperature in such way that: models.Patient has one-to-many relationship with models.Temperatures serializers.Patient is a subclass of serializers.ModelSerializer serializers.Patient (de)serialize temperatures as a list of floats Details Given a quick-dirty patient medical records RESTful API implemented with Django framework. Patient is defined at models.Patient as: class Patient(models.Model): created_at = models.DateField() name = models.CharField(max_length=200) updated_at = models.DateField() and the models.Temperature: class Temperature(models.Model): created_at = models.DateField() patient = models.ForeignKey( Patient, db_column='patient', related_name='temperatures', on_delete=models.CASCADE, ) updated_at = models.DateField() CRUD operations at /patients (de)serialized models.Temperature as float lists, thus a POST should only require: { "name": "John Connor", "temperatures": [36.7, 40, 35.9] } while a GET operation { "created_at": "1985-03-25", "name": "John Connor", "temperatures": [36.7, 40, 35.9], "updated_at": "2021-08-29" } However operations at /patients/<id>/temperatures/ endpoint should return all properties: { "created_at": "1985-03-25", "name": "John Connor", "temperatures": [36.7, 40, 35.9], "updated_at": "2021-08-29" } Can this feature be implemented subclassing standards DRF serializers or does it require a customized serializers.Serializer subclass? -
Browser keeps adding path in request in Django+Docker setup
I'm not sure how this is happening, but the browser keeps adding the path (/code) where the Django app is stored in the container. If I make a curl request to the same url, it works fine. This is my Dockerfile: FROM python:3.10 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . . and this is my docker-compose version: '3.8' services: backend: build: context: ./backend dockerfile: Dockerfile.dev command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend:/code ports: - 8000:8000 env_file: - ./backend/.env.dev -
Fetch: Authentication credentials were not provided
Im a beginner in Javascript and I dont know how can I send to the API that the user is authenticated and has a token. Js const api = 'http://127.0.0.1:8000/player_stats/api/players/' const get_players = async()=>{ const response = await fetch(api,{ method:'GET', headers:{ 'Content-Type' : 'application/json', } }) const data = await response.json() console.log(data) } Views.py class PlayersView(ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = PlayersSerializer queryset = Players.objects.all() def list(self, request): queryset = Players.objects.all() serializer = PlayersSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Players.objects.all() qs = get_object_or_404(queryset, pk=pk) serializer = PlayersSerializer(qs) return Response(serializer.data) Settings.py CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:3030',] CORS_ALLOWED_ORIGIN_REGEXES = [ 'http://localhost:3030',] -
Django: Error during WebSocket handshake: Unexpected response code: 500
I have been following this tutorial to build a chat application. I have been facing WebSocket connection to 'ws://127.0.0.1:8000/ws/lobby/' failed: Error during WebSocket handshake: Unexpected response code: 500 error. I checked other solutions too but they don't seem to work. The console displays the error at (room.html) 'ws://' + window.location.host + '/ws/' + roomName + '/' ); in the console. The following is displayed in the terminal: HTTP GET /favicon.ico/ 200 [0.01, 127.0.0.1:53842] HTTP GET /lobby/?username=darsh 200 [0.01, 127.0.0.1:53842] WebSocket HANDSHAKING /ws/lobby/ [127.0.0.1:53844] HTTP GET /favicon.ico/ 200 [0.01, 127.0.0.1:53842] Exception inside application: No route found for path 'ws/lobby/'. Traceback (most recent call last): File "/home/darsh/.local/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/darsh/.local/lib/python3.8/site-packages/channels/routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/lobby/'. WebSocket DISCONNECT /ws/lobby/ [127.0.0.1:53844] I am attaching the … -
Weasyprint failed to load image at url: Name or service not known
I am working with weasyprint after I migrated from xhtml2pdf, and I am finding some issue with getting static files. I get the following error: 2021-12-03 14:45:50,198 [ERROR] Failed to load image at "http://api.dashboard.localhost:8000/static/logos/logo.png" (URLError: <urlopen error [Errno -2] Name or service not known>) but when I access the same URL weasyprint couldn't, either on my browser or curl, I am able to view/ access the file. Here is my code: from io import BytesIO import mimetypes from pathlib import Path from urllib.parse import urlparse import logging from django.conf import settings from django.contrib.staticfiles.finders import find from django.core.files.storage import default_storage from django.urls import get_script_prefix from django.template.loader import render_to_string import weasyprint from weasyprint import HTML logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("debug.log"), logging.StreamHandler() ] ) # https://github.com/fdemmer/django-weasyprint/blob/main/django_weasyprint/utils.py def url_fetcher(url, *args, **kwargs): # load file:// paths directly from disk if url.startswith('file:'): mime_type, encoding = mimetypes.guess_type(url) url_path = urlparse(url).path data = { 'mime_type': mime_type, 'encoding': encoding, 'filename': Path(url_path).name, } default_media_url = settings.MEDIA_URL in ('', get_script_prefix()) if not default_media_url and url_path.startswith(settings.MEDIA_URL): media_root = settings.MEDIA_ROOT if isinstance(settings.MEDIA_ROOT, Path): media_root = f'{settings.MEDIA_ROOT}/' path = url_path.replace(settings.MEDIA_URL, media_root, 1) data['file_obj'] = default_storage.open(path) return data elif settings.STATIC_URL and url_path.startswith(settings.STATIC_URL): path = url_path.replace(settings.STATIC_URL, '', 1) data['file_obj'] = open(find(path), 'rb') return data … -
AttributeError when trying to return Id from queryset
I'm building a API to get some informations from a Chess board in Django, I have a model with fields: id, piece_name, color, initial_position. MODEL class ChessB(models.Model): class Meta: db_table = 'chess' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) piece_name = models.CharField(max_length=200) color = models.CharField(max_length=200) initial_position = models.CharField(max_length=200) SERIALIZERS class ChessBSerializer(serializers.ModelSerializer): class Meta: model = ChessB fields = '__all__' VIEW class ChessBList(generics.ListCreateAPIView): serializer_class = ChessBSerializer def get_queryset(self): queryset = ChessB.objects.all() piece_name = self.request.query_params.get('piece_name') if piece_name is not None: queryset = queryset.filter(piece_name=piece_name) queryset = queryset.values_list('id', flat=True) return queryset What i'm trying to do is: informing my piece_name as paramether, should return just my Id For example: call http://127.0.0.1:8000/chessb/?piece_name=queen should return: { "id":"id-from-queen-here" } But when I tried to use values_list('id') on my View, I got a error as follow: Internal Server Error: /chessb/ Traceback (most recent call last): File "C:\Users\luizg\Python\Python310\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "C:\Users\luizg\Python\Python310\lib\site-packages\rest_framework\fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'UUID' object has no attribute 'piece_name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\luizg\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\luizg\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\luizg\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in … -
document the debugging process -Logical Error
How I can document the debugging process for a Django? I mean if I have a Logical Error and I have been asked to document it how I can do so, where I don't know How to solve this error -
Why doesn't Django does recognise an app?
I an new to Django and I wrote a program which should print a text in the browser page. I therefore wrote urls.py and views.py, but the browser only shows the welcome page ("The install worked successfully"). What can the mistake be? -
SSL connect to mysql from django
We just had a migration from a "unsecured" mysql DB to a SSL mysql but my Django application cannot connect anymore. content of settings.py DATABASES = { "default": { "ENGINE": 'django.db.backends.mysql' "NAME": env("DATABASE_NAME"), "USER": env("DATABASE_USER"), "PASSWORD": env("DATABASE_PASSWORD"), "HOST": env("DATABASE_HOST"), "PORT": env.int("DATABASE_PORT"), "CONN_MAX_AGE": env.int("DATABASE_CONN_MAX_AGE", default=0), }, "OPTIONS": { "timeout": env.int("DATABASE_CONN_TIMEOUT", default=60), "ssl": { "ca": CA_ROOT_PATH }, } } and when I execute this Django command line : python3 manage.py dbshell (which used to work with the pre-migration DB), I receive the error message : ERROR 2026 (HY000): SSL connection error: unknown error number subprocess.CalledProcessError: Command '['mysql', '--user=user', '--password=password', '--host=host', '--port=3306', 'db']' returned non-zero exit status 1. As you can see, the executed mysql command does not contain anything related to SSL connection. I tried also to modify the OPTIONS in settings.py with these values : "OPTIONS": { "timeout": env.int("DATABASE_CONN_TIMEOUT", default=60), "ssl": { "ssl-ca": CA_ROOT_PATH, "ca": CA_ROOT_PATH }, "ssl-ca" : CA_ROOT_PATH, } Still the same output. It does not seem to use the SSL options in any way... Any idea what I should look for ? -
Django Heatmap showing name once
Am trying to make a Heatmap but am getting this result where similar name with different value is presented once on the Heatmap. The printing down is to show me the results . The heatmap should look like squares EXAMPLE: My code is, <script> ... data = [{% for Bindll in tarname %} {group: '{{ Bindll.targetnameassignedbycuratorordatasource }}', variable:'{{ Bindll.zincidofligand}}', value: {{Bindll.ki_nm}} }, {% endfor %}]; var myGroups = [{% for Bindll in tarname %} "{{ Bindll.targetnameassignedbycuratorordatasource }}", {% endfor %}] var myVars = [{% for Bindll in tarname %} "{{ Bindll.zincidofligand}}", {% endfor %}] // Build X scales and axis: var x = d3.scaleBand() .range([0, width]) .domain(myGroups) .padding(0.01); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) .selectAll("text") .attr("y", 0) .attr("x", 9) .attr("dy", ".35em") .attr("transform", "rotate(60)") .style("text-anchor", "start"); // Build Y scales and axis: var y = d3.scaleBand() .range([height, 0]) .domain(myVars) .padding(0.01); svg.append("g") .call(d3.axisLeft(y)); // Build color scale var myColor = d3.scaleLinear() .range(["#ffffff", "#c60606"]) .domain([d3.min(data, function(d) { return d.value}), d3.max(data, function(d) { return d.value})]) //Read the data and add squares svg.selectAll() .data(data, function(d) { return d.group + ':' + d.variable; }) .enter() .append("rect") .attr("x", function(d) { return x(d.group) }) .attr("y", function(d) { return y(d.variable) }) .attr("width", x.bandwidth()) .attr("height", y.bandwidth()) .style("fill", function(d) … -
TypeError: academic() missing 1 required positional argument: 'request'
I can not pass request to views.py to serializers.py. Views.py def academic(request): is_superuser = request.user.is_superuser getdata = is_superuser return getdata serializers.py class SohanSerializer(serializers.ModelSerializer): is_name = True is_academic = views.academic //Here I call the academic fuction from views if is_academic: academic = Academic(many=True,read_only=True) else: academic = serializers.HiddenField(default=None) if is_name: pass else: name = serializers.HiddenField(default=None) class Meta: model = Student fields = ['name','studentID','email','image','phone','blood','address','academic'] is_academic = views.academic //Here I call the academic fuction from views Server is running but I can't get exact result. When I pass is_academic = views.academic() It's returned TypeError: academic() missing 1 required positional argument: 'request' I think I need to pass request inside the function as like is_academic = views.academic(request) but this not working. Please help me to pass the request inside the is_academic = views.academic(request) Or tell me any way to pass the request. -
Github Actions running 0 tests
I have three tests in my Django project which get executed running "python manage.py test appname" locally. However, Github Actions runs zero tests, returning no errors. How can I fix this? I would prefer not to use any more libraries if possible. I am using the default Django workflow. name: Django CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test appname I tried using "python manage.py test" both with and without the appname, neither work. -
django.template.exceptions.TemplateDoesNotExist: documents/project_confirm_delete.html
I used Django 3.2.9 and used a class in order to delete a project. Here is my code. from django.views.generic.edit import CreateView, DeleteView, UpdateView class ProjectDeleteView(DeleteView): http_method_names = ['get'] model = Project pk_url_kwarg = "pk" def get_success_url(self): return reverse("documents:draftdocumentview") When I called it said like this; django.template.exceptions.TemplateDoesNotExist: documents/project_confirm_delete.html I am not sure about the project_confirm_delete.html. Should I make the html file? Or it is supported from Django Template?