Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serialize Django Model and return GET Response
I am trying to serialize the queryset objects I created when retrieving all jobs from my model. Basically I want an endpoint that lists all jobs that are currently created in the database. Anyone has permissions to view the jobs. However you need to be authenticated to POST, DELETE, or EDIT new jobs. My problems is just making the jobs viewable at the endpoint i created using APIView. I was getting an error before that says the object is not in JSON format. views.py class RetrieveJobsView(APIView): """Retrieves all job postings""" serializer_class = serializers.JobSerializer def get(self, request, format=None): """ Return a list of all jobs""" queryset = Job.objects.all() queryset = serializers.JobSerializer(queryset) return Response(queryset) serializers.py class JobSerializer(serializers.ModelSerializer): """Serializer for tag objects""" class Meta: model = Job fields = ('id', 'description', 'job_type', 'city', 'state', 'salary', 'position', 'employer', 'created_date', 'is_active') read_only_fields = ('id',) def create(self, validated_data): """Create a job posting with user and return it""" user = self.context['request'].user print(self.context['request']) if not user: msg = _('Unable to POST job request. A valid user must be logged in.') raise serializers.NotAuthenticated(msg, code=None) validated_data[user] = user return validated_data models.py class Job(models.Model): """A Job used to create a job posting""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) description = models.TextField() … -
Django API responding slow and not returning Images on Heroku
I'm trying to host my Django Rest API to heroku for free so that my flutter mobile app can communicate with it. But the server response is extremely slow. Besides, it doesn’t returns images for user profile. Moreover, I'm using Image recognition at API to check image objects and return the checked image to client end. But the API fails to return the result. What could be the possible solution. I've applied migrations to server's end. N.B: it’s my University final project which needs to be hosted, so that I can show it for getting jobs. -
Foreign key of models should refer to a particular filed in db - Django
class UserModel(AbstractUser): USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'password'] email = models.EmailField(unique=True) profile_image = models.ImageField(upload_to='user/profile_image', null=True, blank=True) phone = models.CharField(max_length=12, unique=True, blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) emp_id = models.CharField(max_length=20, unique=True, blank=True, null=True) class IndividualWorkAnalysis(models.Model): user_id = models.ForeignKey(UserModel, to_field="emp_id", on_delete=models.CASCADE, null=True, related_name="user_id") Here above I need to access 'emp_id' from 'UserModel'. All my migrations went correct, but not able to fetch the 'emp_id' on the admin panel of Django. There it just lists the usernames. -
How to write data to a Django temp file?
Hello Community! I have a small application that allows you to download certain multimedia content from an HTML template. To save resources, I want this file to be stored only on the PC of the users who visit the eventual website, which is why I will use a temporary file NamedTemporaryFile that the FrameWork Django provides. Part of the code consists of: HTML TEMPLATE: ... <input type = "button" value = "Download" onclick = "window.open('download')"> ... urls.py: from django.urls import path from ProjectApp import views urlpatterns = [ ... path('download', views.download), ... ] views.py: import os from django.http import StreamingHttpResponse from wsgiref.util import FileWrapper from django.http import HttpResponse from django.core.files.temp import NamedTemporaryFile def download(request): newfile = NamedTemporaryFile (suffix='.txt', mode='w+b') file_path = os.path.join(MEDIA_ROOT, 'test.txt') # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') filename = os.path.basename('archive_test.txt') chunk_size = 8192 response = StreamingHttpResponse( FileWrapper(newfile, chunk_size), content_type="application/octet-stream") response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = f'attachment; filename={filename}' return response It should be noted that as I show it, it works as I wish, since a download dialog appears in the browser with the archive_test.txt file in a "starting" state. What I want is that from that moment on, the information that it will contain begins to be written to said … -
Heroku app successfully deploying, but receiving application error when loading site. But I can seem to find an error
When loading my site it displays the error message; Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail With an application log of; 2021-01-21T10:56:36.186139+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=afternoon-retreat-21879.herokuapp.com request_id=b50977ff-d8c6-4b2f-b633-34965f253af3 fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https 2021-01-21T10:56:36.841645+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=afternoon-retreat-21879.herokuapp.com request_id=b1224d5b-75d2-4aa3-8411-b5875124475e fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https 2021-01-21T11:06:56.778335+00:00 app[api]: Starting process with command `python manage.py migrate` by user juniornkiangmatiah@gmail.com 2021-01-21T11:07:05.370028+00:00 heroku[run.9335]: State changed from starting to up 2021-01-21T11:07:05.735946+00:00 heroku[run.9335]: Awaiting client 2021-01-21T11:07:05.789615+00:00 heroku[run.9335]: Starting process with command `python manage.py migrate` 2021-01-21T11:07:29.264945+00:00 heroku[run.9335]: Process exited with status 0 2021-01-21T11:07:29.316386+00:00 heroku[run.9335]: State changed from up to complete 2021-01-21T11:11:12.413411+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=afternoon-retreat-21879.herokuapp.com request_id=eea06fd9-83d9-49c9-93ae-80c64af88963 fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https 2021-01-21T11:11:13.160682+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=afternoon-retreat-21879.herokuapp.com request_id=839aa9c7-f433-4e82-9fa3-a65fec8530d0 fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect... Connection to log stream failed. Please try again later. And below we … -
Where do i need to locate .well-known/pki-validation/xxxxxxx.txt/ file in Django project?
I using sslforfree to create a free SSL cert online and now i in the mid of verifying my host. How it works is: After creating , it need to verify my domain ownership before installing my certificates Verification method : HTTP File Upload First , i have download Auth file(xxxxxxyyyyzzzz.txt) Second , i have to upload my Auth file to my Http server under /.well-known/pki-validation/xxxyyyzzz.txt I just put a path in my urls.py in Django_Project as below: from core.views import read_file urlpatterns = [ path('.well-known/pki-validation/xxxyyyzzz.txt', read_file), ] Then my read_file function in djangoapp(core/view.py) just simply return the file with def read_file(request): f = open('.well-known/pki-validation/xxxyyyzzz.txt', 'r') file_content = f.read() f.close() return HttpResponse(file_content, content_type="text/plain") I have no idea where should i locate .well-known/pki-validation/xxxyyyzzz.txt in my django project in order to locate the file . when i runserver <domain.name>/.well-known/pki-validation/84F3E6FA7EADE957CBDBA27A78C8BAF0.txt it say filenot found (no such file or directory ) Please help . i really appreciate your help . -
Heroku Django app deployment fails after trying to install python requirement
I installed django-user-visit with pip install django-user-visit , tested it in my local environment and everything seems to work fine, but when i try to deploy my app to production with Heroku i get the following error : remote: Collecting django-cors-headers==3.6.0 remote: Downloading django_cors_headers-3.6.0-py3-none-any.whl (12 kB) remote: ERROR: Could not find a version that satisfies the requirement django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4)) (from versions: none) remote: ERROR: _No matching distribution_ found for django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed Does anyone know why Heroku can't find the package and if i can fix this ? My packages are being installed by running the libraries indicated in my requirements.txt file: asgiref==3.3.1 Django==3.1.5 django-cors-headers==3.6.0 django-user-visit==0.4.1 djangorestframework==3.12.2 gunicorn==20.0.4 psycopg2==2.8.6 pytz==2020.5 sqlparse==0.4.1 ua-parser==0.10.0 user-agents==2.2.0 whitenoise==5.2.0 What i've tried so far is to change the version to 0.4 and to not specify a version at all -
How can I use regex in django's Replace function
I'm trying to update all urls in my query by using django's update and Replace function using regex. Here's what I've tried so far but it seems like django's Value expression did not recognize my regex. from django.db.models import Value from django.db.models.functions import Replace Foo.objects.filter( some_url__iregex=r'^\/some-link\/\d+\/').update( some_url=Replace( 'some_url', Value(r'^\/some-link\/\d+\/'), Value('/some-link/'))) My goal is to remove all numbers after /some-link/ (e.g. /some-link/55/test to just /some-link/test) -
Django - Cannot get console.log to output in VSCode Terminal
I'm new to using Javascript with django and am trying to use console log to test my Javascript code but am having trouble getting it to work. I check the terminal, outpout, problems, and Debug console but none show the output of console.log. I know my javascript is working because the ui dropdown menu is populated when I use the ajax code below and it displays nothing if I remove it. However, I cannot tell if the event listener is working.. here is my html: <div class="ui selection dropdown" id = "cars"> <input type="hidden" name="car"> <i class="dropdown icon"></i> <div class="default text">Choose a car</div> <div class="menu" id = 'cars-data-box'> </div> </div> Here is my Javascript const carsDataBox = document.getElementById('cars-data-box') const carInput = document.getElementById('cars') $.ajax({ type: 'GET', url: '/cars-json/', success: function(response){ console.log(response) const carsData = response.data carsData.map(item=>{ const option = document.createElement('div') option.textContent = item.name option.setAttribute('class', 'item') option.setAttribute('data-value', item.name) carsDataBox.appendChild(option) }) }, error: function(error){ console.log(error) } }) carInput.addEventListener('change', e=>{ const selectedCar = e.target.value console.log(response) }) urls.py urlpatterns = [ path('', page), path('cars-json/', get_json_car_data), ] views.py def page(request): qs = Car.objects.all() return render(request, 'testenv/home.html', {'qs' : qs}) def get_json_car_data(request): qs_val = list(Car.objects.values()) return JsonResponse({'data' : qs_val}) -
heroku[router]: at=error code=H14 desc="No web processes running" (Deploying Docker Image)
So trying to deploy a docker image, these are my setting, and these are the errors i keep getting. I keep getting the error heroku[router]: at=error code=H14 desc="No web processes running". I've installed posgres plugin on heroku and also have a dynos active. docker-compose.yml: version: "3" services: {redacted}: build: context: . ports: - "8000:8000" volumes: - .:/{redacted} command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST={redacted} - DB_NAME={redacted} - DB_USER={redacted} - DB_PASS={redacted} depends_on: - db db: image: postgres:12-alpine environment: - POSTGRES_DB={redacted} - POSTGRES_USER={redacted} - POSTGRES_PASSWORD={redacted} Dockerfile: FROM python:3.8-alpine MAINTAINER {redacted} ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /{redacted} WORKDIR /{redacted} COPY . /{redacted} RUN adduser -D user USER user requirements.txt: asgiref==3.2.10 beautifulsoup4==4.9.1 bootstrap4==0.1.0 certifi==2020.6.20 chardet==3.0.4 dj-database-url==0.5.0 djangify==1.0.0 Django==3.1 django-bootstrap4==2.2.0 django-crispy==1.8.1 django-filter==2.4.0 django-heroku==0.3.1 django-i18n==1.0.4 djangorestframework==3.12.1 djangorestframework-simplejwt==4.6.0 flake8==3.8.4 gunicorn==20.0.4 heroku==0.1.4 idna==2.10 mccabe==0.6.1 psycopg2==2.8.5 psycopg2-binary==2.8.6 pyclean==2.0.0 pycodestyle==2.6.0 pyflakes==2.2.0 PyJWT==2.0.1 python-dateutil==1.5 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 slugify==0.0.1 soupsieve==2.0.1 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==5.2.0 settings.py: from pathlib import Path from datetime import timedelta import django_heroku import os # Build paths inside … -
Django saving the registration extends AbstractBaseUser
Good day SO. I am new to Django and having troubles with something basic. When I click on sumbit, the template returns my Account(the OneToOneField) This field is required. Though my methods might be not aligned with good practice, but I hope that you can help me with this. I have been trying to check with other resources for two days but I can't seem to find the solution to my concern. Here is my forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import Account, CompanyAccount class AccountCreationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text="Required") class Meta: model = Account fields = ("email", "username", "password1", "password2", "account_type") class CompanyAccountForm(forms.ModelForm): class Meta: model = CompanyAccount fields = "__all__" my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, account_type, password): if not email: raise ValueError("Users must have an Email Address") if not username: raise ValueError("Users must have an Username") if not account_type: raise ValueError("Users must have an Account Type") user = self.model( email=self.normalize_email(email), username=username, password=password, account_type=account_type, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, account_type, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, account_type=account_type, ) user.is_admin = True user.is_staff … -
Flask or Django Framework Livestream
how can i get livestream on yt etc. with API with on flask or django to my website i want to add livestream for example tv stream, i researched but i didnt find anything on google. how can i get this can u help me ? For example I reserved a certain area for live broadcast on my website, I add live broadcast stream to that area, but I want to broadcast live broadcast on my site, for example youtube or twitch api on the internet, not webcam broadcast. #!/usr/bin/env python from flask import Flask, render_template, Response from camera import Camera app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) This is not what I want. -
composite key not displaying orrecyl on django admin
I have an intermediary model betwen "estados" e "listaflor", the flora2estado uses a composite key- and a primary key to trick django not to throw errors at me-. When i click in one object at django admin i get this error: MultipleObjectsReturned at /admin/accounts/flora2estado/99/change/ get() returned more than one Flora2Estado -- it returned 5! my models.py class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'estados' class Familia(models.Model): familia_id = models.AutoField(primary_key=True) familia_nome = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'familia' class Flora2Estado(models.Model): estado = models.OneToOneField(Estados, models.DO_NOTHING, ) especie_id = models.IntegerField() flora2estado_id = models.AutoField( primary_key=True) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie_id'),) admin.py admin.site.register(Flora2Estado) -
How to make a variable number of fields in django models?
I want to make a model of Grades of students and this model has a variable number of fields that I can change from the admin page. -
django: FileField model - 404
This is my first Django project and I have one problem. file1 is saved to media folder\files however when I try to download the file I'm getting 404. Any help is appreciated! 127.0.0.1:8000/about/files/2021/01/22/pyqt_tutorial_EB2ZapN.pdf models.py class Links(models.Model): file1 = models.FileField(upload_to = 'files/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) html {% for link in links %} <div class="links1"> <h3><a href = "{{ link.file1 }}">Download Link</a></h3> <p>{{ link.publish_date }}</p> </div> {% endfor %} urls.py> urlpatterns = [ path('admin/', admin.site.urls), path('about/', about, name = 'about') ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py> # Media Folder Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Update: from the admin panel if I click on the link I can see it. Maybe In the {{ link.file1 }} url something need to be changed? -
How do I import a model from another app in Django?
So in my project book_letter, I have an app named contents. Inside it, I have a model named Book. As below. class Book(models.Model): objects = models.Manager() title = models.CharField(max_length = 30) author = models.CharField(max_length = 20) def __str__(self): return self.title And I have another app named recommendation, with a model named Recommendation. As below. from book_letter.contents.models import Book class Recommendation(models.Model): objects = models.Manager() source = models.ForeignKey("Book", related_name='book', on_delete=models.CASCADE) However, when I run python manage.py runserver, I get an error saying ModuleNotFoundError: No module named 'book_letter.contents' I don't see what I've done wrong. Any ideas? Thanks :) -
Django: Group by foreign key then get max id from group
I'm looking to grab the latest message in a conversation. My conversation model has attributes id (primary key) and user1 and user2, which are both foreign keys to a User model. My message model consists of a conversation(foreign key) and message primary key. These both just return only the very latest message. Message.objects.values('conversation').latest('id') Message.objects.order_by('conversation').latest('id') Any recommendations for getting this query? -
Django access pk id in class
I have this site, and I want to be able to have views. When you go to url /post/int:pk it shows the post in more detail. When the user goes here, I want to add one to an field in models.py. Here is models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.IntegerField(default=0) people_read = models.IntegerField(default=0) # Add one to this data user_liked = models.ManyToManyField(User, related_name='user_liked') user_disliked = models.ManyToManyField(User, related_name='user_disliked') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) And views.py: class PostDetailView(DetailView): model = Post post = get_object_or_404(Post, pk=pk) post.people_read = post.people_read + 1 post.save() The problem with this is that it won't get the pk id. So how do I get the posts pk in an class, or is there another way to add to a models field when going to a url? Thanks. -
Add additional fields to form after click - the node before which the new node is to be inserted is not a child of this node
I have a form in which I need to add a button that will allow the user to add a new field. I'm trying to do it with javascript, but since I don't know much this language I'm lost with some concepts. The form I use is one where the data is completed in steps, and the fields I want to add are the following <div class="job-form row mb-3"> {% for form in add_trabajo %} <div class="col-md-6"> <label for="ref" class="">Nombre</label> {% render_field form.trabajo class="form-control" type="text" placeholder="Ej: Reparación de envolvente delantero" %} </div> <div class="col-md-2"> <label for="ref" class="">Descuento</label> {% render_field form.descuento class="form-control" type="text" %} </div> <div class=" col-md-2"> <label for="ref" class="">Precio</label> {% render_field form.precio class="form-control" type="text" %} </div> <div class="col-md-2 d-flex align-items-end"> <button id="addButton" type="button" class="btn-icon btn-icon-only btn btn-success p-2"><i class="pe-7s-plus btn-icon-wrapper"> </i></button> </div> {% endfor %} </div> I'm trying to add these fields after existing ones that are identical I already have the button and some code in javascript but it indicates the following error Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. at HTMLButtonElement.addForm This is my javascript code let jobForm … -
Django File upload in model
Considering that we`ve got the model below: class Project(models.Model): file1 = models.FileField(upload_to='projects/', blank =True) file2 = models.FileField(upload_to='projects/', blank =True) file3 = models.FileField(upload_to='projects/', blank =True) file4 = models.FileField(upload_to='projects/', blank =True) file5 = models.FileField(upload_to='projects/', blank =True) How many file1 can we create? If I want to create severals files, I usually write my code this way: class File1(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) file = models.FileField(upload_to='projects/', blank =True) Instead to create severals models File1, File2, File 3, Is there a way to upload several file1 in Django using only the model Project? I mean to not have to create a model for each file1, file2, file3 if we need to upload several of them. Many Thanks, -
django project not working with apache2, working ok with inbuilt web server
I have a django project and working with the in-built webserver. I am trying to move it to apahce and having trouble.Would anyone please be able to help. My project structure is: home/p/prjct |-- setest | `-- wsgi.py | |-- manage.py |-- penve | |-- hello | |-- tsts penve is the virtual environment hello and tsts are apps. I have made changes in my apache2.conf and it looks like: WSGIScriptAlias / /home/p/prjct/setest/wsgi.py WSGIPythonHome /home/p/prjct/penve WSGIPythonPath /home/p/prjct <Directory /home/p/prjct/setest> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> DocumentRoot /home/p/prjct Listen 80 AccessFileName .htaccess <FilesMatch "^\.ht"> Require all denied </FilesMatch> LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent Am I missing something. Thanks in advance for help. sp -
Django Email Token Sending Blocked
For a user registration, I try and send a url that the user has to click in order to register. This url contains a uid, and token. However, gmail seems to block emails from the specified email in settings.py when I try and send them. I think it's because my local address is used as the website for now and which is seen as 'less secure' but I am not exactly sure why. I know it has to do with the token because when I send an email with just text in the body, it does not pose an error. The error is shown as below: Here is the email body (note that when I simply change this to text, the email is sent): email_body = render_to_string('mainapp/acc_activate_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) -
how do you add an avatar profile to django inbuilt forms?
How can you add a field to add images on a inbuilt Django form? Here is the code of my form.py: class CreateUserForm(UserCreationForm): password1 = forms.CharField( label="Password", widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Password'}), ) password2 = forms.CharField( label="Confirm password", widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Confirm Password'}), ) class Meta(UserCreationForm.Meta): model = get_user_model() widgets = { 'username': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Username'}), 'first_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'First Name'}), 'last_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Last Name'}), 'email': EmailInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Email Address'}), } fields = ['username', 'first_name', 'last_name', 'email'] -
VSCode pytest test discovery fails when debugging Django tests
I'm trying to debug my first django test, but VSCode is returning: Ran 0 tests in 0.000s. On the other hand, when I use an integrated git bash (I'm using a windows OS) in VSCode terminals or externally, it returns: Ran 1 test in 0.0014s. It also echoes FAILED and a traceback for a valid error within the test. My vscode launch.json: { ... "configurations": [ ... { "name": "Django Tests", "type": "python", "request": "launch", "program": "${workspaceFolder}\\testprojectname\\manage.py", "args": [ "test" ], "django": true, } ] } My vscode settings.json: { "python.pythonPath": "C:\\Users\\user\\.virtualenvs\\backend-Vg-KBKTA\\Scripts\\python.exe", "python.testing.pytestEnabled": true, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": false, "python.testing.pytestArgs": [ "testprojectname" ] } Note that C:\Users\user\.virtualenvs\backend-Vg-KBKTA\Scripts\python.exe is a valid path to the pipenv shell [(1) it is echoed when I type in the bash: pipenv --venv (2) it works when I launch the django debugger] So far, I've tried: Updating my pytest according to VSCode pytest test discovery fails Changing around the name of my tests.py file to test_example.py according to Pytest - no tests ran Changing the class of the tests to prefix with Test_ according to the same link in (2) This is what the test currently looks like class Test_Contacts(unittest.TestCase): def test_create_contact_message(self): """Create a new contact message.""" … -
Postgres - can't acces database, no acces
I am trying to acces my postgres database but I am having permission denied error. I created database + table(was created in python but it is there): sudo -u postgres psql postgres=# create user lukasz1 with encrypted password '<password>'; postgres=# create database mydatabase owner lukasz1; So far so good: List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ------------+----------+----------+-------------+-------------+----------------------- mydatabase | lukasz1 | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =Tc/lukasz1 + | | | | | lukasz1=CTc/lukasz1 postgres | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | template0 | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) and lukasz1 is an owner of mydatabase. But when I try to connect it I am having permission denied. I can't even select from my table to view it as permission is denied: mydatabase=> select article_id from articles; ERROR: permission denied for table articles I checked multiple anwers to simmilar questions and tried checking user valid_until and got an empty values in that column: mydatabase=> select usename, valuntil from …