Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a separate comments app for a django ticket app
Trying to create a separate comments app using class-based views for a ticket project. I think the problem lies in my comments’ models.py or its urls.py file but I dont know how to proceed. Here is the error that I get and the code and traceback. Traceback Installed Applications: ['tickets.apps.TicketsConfig', 'users.apps.UsersConfig', 'comments.apps.CommentsConfig', 'demo.apps.DemoConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 174, in post return super().post(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 144, in post return self.form_valid(form) File "C:\Users\mikha\issuetracker\comments\views.py", line 41, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 128, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 59, in form_valid return HttpResponseRedirect(self.get_success_url()) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 118, in get_success_url url = self.object.get_absolute_url() File "C:\Users\mikha\issuetracker\comments\models.py", line 21, in get_absolute_url return reverse('tickets:ticket-detail', kwargs={'pk': self.ticket_id}) File "C:\Users\mikha\bug_env\lib\site-packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\urls\resolvers.py", line 729, … -
Knox logout error "authentication credentials not provided"
I was working on user register login and logout using Knox, the register returns the usern and the login returns the token and token expiry time . But when I try to logout it returns ‘authentication credentials not provided’. I sorry if I provided too many pictures. views serializers urls error -
Django application with ASGI Uvicorn increasing the latencies by 4x
We are using a Django application (https://github.com/saleor/saleor) to handle our e-commerce use-cases. We are using ASGI with Uvicorn in production with 4 workers. Infra setup - 4 instances of 4 core 16 GB machines for hosting the Django application (Saleor). The app is deployed using docker on all the instances. 2 instances of 4 core 16 GB for Celery. Hosted PostgresSQL solution with one primary and one replica. Saleor uses Django and Graphene to implement GraphQL APIs. One of the API is createCheckout which takes around 150ms to 250ms depending on the payload entities. While running load test with 1 user, the API consistently gives similar latencies. When number of concurrent users increase to 10, the latencies increase to 4 times (1sec - 1.3 secs). With 20 users, it reaches to more than 10 seconds. Average CPU usage doesn't exceed more than 60%. While tracing the latencies, we found out that the core APIs are not taking more than 150-250ms even with 20 users making concurrent requests. This means that all the latencies are being added at ASGI + Uvicorn layer. Not sure what are we missing out here. From the deployment perspective, we have followed standard Django + ASGI … -
InvalidProfileError using github actions to deploy on Elastic Bean
I am using github actions to deploy my Django app to Elastic bean. My .elasticbeanstalk/config.yml file is: branch-defaults: amazon-deploy: environment: platform-prod group_suffix: null global: application_name: platform branch: null default_ec2_keyname: aws-eb default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: eu-north-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: git workspace_type: Application I have the following code on my github actions (.github/workflows/github_actions.yml: name: EB deploy on: push: branches: [ master ] jobs: deploy: runs-on: ubuntu-latest env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} steps: - uses: actions/checkout@v2 - name: Install Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install EB CLI using pip run: | python -m pip install --upgrade pip pip install awsebcli - name: Deploy to Elastic Beanstalk run: | eb deploy platform-prod When I execute github action, I get the following error: ERROR: InvalidProfileError - The config profile (ecb-cli) could not be found Error: Process completed with exit code 4. I have changed the profile from ecb-cli to default but I still get the same error. Can anyone please help. Thank you. -
Authenticating users with django in external application
I am creating a project where I have a downloadable software on a clients computer in python. I want to create a login system where I use the users on my django server to authenticate the login on the downloadable software that runs on the clients computer. It is an inventory management system that does some other stuff as well which I am unable to elaborate on. I am unsure what python packages might help with this or where to start. Do I just make my project a webapp or am I able to go with my original idea. I have done quite a lot of searching around to find an answer but haven't found one. This is not a server to server communication that I am looking for but rather a client requesting from the server. This will be a subscription based software and I do not want users accessing the product if they have not paid for their usage. Is this possible? I would appreciate any feedback. -
Cant trigger a view's breakpoint in django tests
I want to debug a view that gets triggered inside a django tests.py Here's the view code: def test_view(request): if request.method == "POST": with open("a_path_to_the_file/aaa.txt", "w") as f: f.write("done!") Here's the test: class ViewsTests(TestCase): def test_add_address(self): self.client.post(reverse("address_book:test_view")) The view just doesn't run in that way. I want the file to be created after I run the test. The breakpoint is set on the if request.method == "POST": line. I use pycharm and run tests via pycharnm run config. -
Problems with a backend part of search line in Django
who can explain me why my SearchView doesn't work. I have some code like this: search.html <div class="justify-content-center mb-3"> <div class="row"> <div class="col-md-8 offset-2"> <form> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..." /> <div class="input-group-append"> <button class="btn btn-dark" type="submit" id="button-addon2">Search</button> </div> </div> </form> </div> </div> </div> search/urls.py path('search/', SearchView.as_view(), name='search') search/views.py class SearchView(ListView): model = Question template_name = 'forum/forum.html' def get_queryset(self): q = self.kwargs.get('q', '') object_list = self.model.objects.all() if q: object_list = object_list.filter(q__icontains=q) return object_list -
How do I create a LinkedIn ad campaign api using Django?
I am working on a project where I am trying to create an API of an ad campaign manager using LinkedIn oauth2 and Django. I have managed to get connected and authorized to LinkedIn with rw_ads permissions but I have absolutely no idea where to go from here. Any help would be much appreciated, thanks in advance! -
Django rest framework and React: TypeError: NetworkError when attempting to fetch resource
I am using Django rest framework for back-end and react for front-end of a website. Back-end is working fine in my Postman app and browser. However, when I fetch data using react it prints following error in my console TypeError: NetworkError when attempting to fetch resource. and nothing is shown in XHR tab of Networks. Here is my code export default function Contact() { const [contactData, setContactData]=useState({ 'name': '', 'email': '', 'phone': '', 'describe': '', 'status': '', }); const change=(event)=>{ setContactData({ ...contactData, [event.target.name]: event.target.value }); } const submitForm=()=>{ const contactFormData=new FormData(); contactFormData.append('name', contactData.name) contactFormData.append('email', contactData.email) contactFormData.append('phone', contactData.phone) contactFormData.append('describe', contactData.describe) fetch('http://127.0.0.1:8000/ask/', { mode: 'cors', method: 'POST', headers: { "Access-Control-Allow-Origin": "*", 'Content-Type': 'application/json', }, body: JSON.stringify({ // your expected POST request payload goes here name: contactData.name, email: contactData.email, phone:contactData.phone, describe: contactData.describe }) }) .then(res => res.json()) .then(data => { // enter you logic when the fetch is successful setContactData({ 'name': '', 'email': '', 'phone': '', 'describe': '', 'status': 'success', }) } ) .catch(error => { // enter your logic for when there is an error (ex. error toast) console.log(error) }) here is the part of settings.py file where I added cors headers INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', … -
Starting a login session once check_password verifies a password is correct
I have a user logi form i am using to authenticate users in django and this is the code that processes from django.contrib.auth.hashers import make_password from django.contrib.auth.hashers import check_password from django.contrib.auth import login def process_login(request): if request.method == 'POST': var = request.POST["email_or_telephone"] print(var) obj=AuthUsers.objects.create( email_address = "info@google.com", user_type = "inapp", telephone_number = "08002556155", user_password = make_password("logan2900"), account_status = "not_verified", full_names = "Michael Jackson", pronouns = "Hee/Hee", country = "UK", gps_location = "London", role_name = "user", profile_picture = "image.png", kyc_documents = "1.png,2.jpg" ) obj.save() if check_password("logan2900", "pbkdf2_sha256$320000$S8u10Fh1yz0NssYphC1qW1$LvnhBHACIqr6dGX7Bae19k8/yGf/omNLQcvl88QXodv="): print("Correct Password") else: print("Incorrect Password") I am using the the check_password method to check if a user password is correct and the function works as expected. How can i start session and actually login user after verifying the password is correct? Also after successfully logging the user, how can i verify a user is logged in in another function? -
Django: how to check if the users that are registered under me have new users registered under them in Django
I am writing a referral system logic in django. The referral system works fine now, but what i want to implement is this. When i refer a user "user 2" and "user 3", it is stored that i have refered two users, now how do i check if "user 2" or "user 3" which are refered by me: have gotten a new user refered by them ("user 2" or "user 3"). This is the code i have written to register users as referalls views.py def registerRef(request, *args, **kwargs): profile_id = request.session.get('ref_profile') print('profile_id', profile_id) code = str(kwargs.get('ref_code')) try: profile = Profile.objects.get(code=code) request.session['ref_profile'] = profile.id print('Referer Profile:', profile.id) except: pass print("Session Expiry Date:" + str(request.session.get_expiry_age())) form = UserRegisterForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) ref_earn = InvestmentPackageID.objects.get() instance = form.save() registered_user = User.objects.get(id=instance.id) registered_profile = Profile.objects.get(user=registered_user) registered_profile.recommended_by = recommended_by_profile.user registered_profile.save() else: instance = form.save() registered_user = User.objects.get(id=instance.id) profile = Profile.objects.get(user=registered_user) profile.save() username = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('core:index') context = {'form':form} return render(request, 'userauths/sign-up.html', context) in the profile model i have a field like this models.py class Profile(models.Model): ... code = models.CharField(max_lenght=100, ...) recommended_by = models.ForeignKey(User, ...) What is … -
Grouping entries from PostgreSQL database by their week or month based on timestamp value?
I have been trying to resolve a solution to this for a while now but due to my inexperience with both postgres(and SQL in general) and Django ORM I haven't been able to get a result that I can use. I have this model: class EventItem(models.Model): Id = models.CharField(max_length=200, primary_key=True) StartTime = models.DateTimeField(null=True) EndTime = models.DateTimeField(null=True) Duration = models.TimeField(null=True) Creator = models.CharField(max_length=50, null=True) and I want to get the EventItems and group the entries by their week and/or month. So for every week starting from the earliest entry group all of the events for that week into one group. Right now I am able to return the week number for each individual item by doing this: weeks = EventItem.objects.annotate(week=ExtractWeek('StartTime')).values('week') But this obviously doesn't group the results and I also need to keep the columns from the original table. -
Django authenticate() command returns None
I am doing a website which has Google sign in and I am trying to log in the user when they click the sign in with Google button. This is the code that doesn't work: def google_login(request): security_key = request.GET.get("security_key","") email = request.GET.get("email","") if security_key == "" or email == "": return redirect("/403/") timestamp_now = time.time() try: obj = GoogleSignupToLoginSecurityKey.objects.get(email=email,security_key=security_key) if (timestamp_now-float(obj.timestamp_created)) < 50: print(email) user = authenticate(email=email, password="GOOGLE USER") print(user) if user is not None: login(request, user) else: redirect_url = "/accounts/signup/" return redirect(redirect_url+"?error=google_unknown") return redirect("/accounts/signup/welcome/") else: return redirect("/accounts/signup?error=google_unknown") except: return redirect("/403/") return All the security and timestamp stuff is for security purposes but the bit that doesn't work is the authenticate() command. For this command the email is retrieved by a url parameter and I have checked and it is correct. For a Google Account I have made the password "GOOGLE USER" since I am lazy and haven't bothered taking out the password field for a Google Account, this means that every Google account has the same password but for this type of account it is completely unnessesary to have a password. The command returns "None". Hopefully you understand this and I haven't made it too confusing. -
TypeError at /password-reset/ filter_users_by_email() got an unexpected keyword argument 'is_active'
I am trying to use the password-reset api endpoint in dj_rest_auth. It requires that I enter the email address of the user but wehenever I do that, I get TypeError at /password-reset/ filter_users_by_email() got an unexpected keyword argument 'is_active' error. Please help me solve this. Thank you. models.py from django.conf import settings User = settings.AUTH_USER_MODEL from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth.models import UserManager from orders.models import Orders # Create your models here. class CustomUser(AbstractUser): phone_number = models.CharField(max_length=100) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) id = models.IntegerField(primary_key=True) username = models.CharField(max_length=100, default="") email = models.CharField(max_length=100, default="") def save(self, *args, **kwargs): self.id = self.user.id self.username = self.user.username self.email = self.user.email super().save(*args, **kwargs) def __str__(self): return f'{self.user.username} Profile' urls.py from django.contrib import admin from django.urls import path, include from orders import views from django.views.generic import TemplateView from dj_rest_auth.views import PasswordResetView, PasswordResetConfirmView urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), path(('users/'), include('users.urls')), path('orders-list/', views.OrdersList, name = "orders-list"), path('orders-detail/<str:pk>', views.OrdersDetail, name = "orders-detail"), path('orders-create/', views.OrdersCreate, name = "orders-create"), path('orders-update/<str:pk>', views.OrdersUpdate, name = "orders-update"), path('orders-delete/<str:pk>/', views.OrdersDelete, name = "orders-delete"), path('password-reset/', PasswordResetView.as_view()), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path("djangoflutterwave/", include("djangoflutterwave.urls", namespace="djangoflutterwave")) ] -
DJango project & app layout and Imports seem to be extremely repetative
I'm trying to layout my Django app, and I just cannot figure out what the appropriate way to do it is. I've read many questions and blog posts, but nothing seems obvious. Here's my app (I hate the repetition of these terms like buildhealth, but I guess it's idomatic in Django?) - the name of the project, created by django-admin startproject buildhealth and the name of the first app (a performance dashboard) created by django-admin startapp performance is performance): [ROOT] ├── ... ├── buildhealth │ ├── __init__.py │ ├── buildhealth │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── performance │ │ │ ├── __init__.py │ │ │ ├── ... │ │ │ ├── views.py │ │ │ └── ... │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── ... │ ├── manage.py │ └── staticfiles │ └── ... ├── poetry.lock ├── pyproject.toml └── ... This sort of works, but then i have files all over the place for doing imports which feels terrible. For example - in settings.py, i have to type this: ROOT_URLCONF = "buildhealth.buildhealth.urls" This feels super wrong to have two imports like this. Am I laying this out wrong? … -
Django Limit Choices in Admin
I need to filter categories that I can select in PostAdmin exact which was confirmed, how to do that? in models: class Category(models.Model): name = models.CharField(max_length=200) confirmed = models.BooleanField(default=False) .... def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') ... def __str__(self): return self.title in admin: class PostAdmin(models.ModelAdmin): list_display = ['title', 'category'] fields = ['title, 'category'] admin.site.register(Post, PostAdmin) -
Create django query that would give results like this [{"modelfield3_value": {"modelfield1": "value1", "modelfield2": "value2"} }]
How can I create django query that would give results like this [{"modelfield3_value": {"modelfield1": "value1", "modelfield2": "value2"} }]? Basically, the {"modelfield1": "value1", "modelfield2": "value2"} part is the dictionary that .values() method returns. Is such thing possible with django orm and postgres or I need to use the python for this? -
How to count the number of a nested array in django?
I am new to django and I'm still figuring out how use all the functions. This is the result of the query that I want to count { "id": 1, "user_id": 1, "encountersDaily": [ { "id": 1, "DateTime": "2022-08-01T01:22:00Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 1, "GenderID": 1 }, { "id": 10, "DateTime": "2022-08-01T01:42:46Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 1, "GenderID": 1 } ], }, { "id": 4, "user_id": 4, "encountersDaily": [ { "id": 6, "DateTime": "2022-08-01T01:42:09Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 2, "PromoterID": 4, "GenderID": 1 }, { "id": 8, "DateTime": "2022-08-01T01:42:29Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 4, "GenderID": 1 }, { "id": 9, "DateTime": "2022-08-01T01:42:38Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 4, "GenderID": 2 } ], } I have this data of 2 users and my goal is to loop through this array and find the sum of the encountersDaily. is it possible to just use filter function here? or loop is necessary . -
Trying to load static images from JS script in Django
I am using a 'select2' dropdown 'https://select2.org/dropdown' component in Django to display a dropdown menu that has a flag image next to each item. In development I was creating a string literal in my JS code to point to the static img folder , but now I've deployed the application to AWS and my static files are being served through an S3 bucket and now the image is not loading. select2 component js code: function formatState (state) { if (!state.id) { return state.text; } var baseUrl = "static/img/flags"; var $state = $( '<span><img src="' + baseUrl + '/' + state.element.value.slice(0,3).toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>' ); return $state; }; in my html inspector the image source produces: img src="static/img/flags/bsd.png" class="img-flag"> I can obviously see that the img src above is not pointing to my s3 bucket, so I've tried to create a string literal for a static img inside of the select2 js code to reproduce {% static '/img/flags/all.png' %} : '<span><img src="' + '{% static' + '"' + '/' + 'img' + '/' + 'flags' + '/' + state.element.value.slice(0,3).toLowerCase() + '.png' + '"' + ' %}' + 'class="img-flag" /> ' + state.text + '</span>' this … -
assert celery task runs or not runs
I am working on a django project as an Intern, I am developing the project not coding it from start, I added a feature to contact us section, the feature is about sending support's answer to user who sent the contact message via email after the support answered the message in admin panel, I start celery task for sending email in post_save receiver function based on some conditions, I would like to unit test this feature, what is matter to me is does celery receives task in some conditions or it doesn't I need something like this assertCeleryRecievesTask(task_name) or not, for now it is not important if the task itself works as expected just wanna know if the task starts or not, thanks for your help. -
redirect to detail view after authentication in django templates
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) With a simple GroupDetail template: <div>Leader: {{group.leader}}</div> <div>Name: {{group.name}}</div> <div>Description: {{group.description}}</div> {% if user.is_authenticated %} <form action="{% url 'join_group' group.pk %}" method="POST"> {% csrf_token %} <button type="submit" name="group_id" value="{{group.id}}">JOIN</button> </form> {% else %} <div><a href="{% url 'login' %}">Login</a> to join chaburah</div> {% endif %} The idea is that if a User is authenticated (signed in) they can join a group. My issue is that right now, when a User clicks login they're redirected to the login page, but after login they don't return to Group they were about to join. Is there a way to sort of stash the url they were at return to it after authentication? This is becoming more important as I add invite links and private groups, where a User is sent a link to join a private Group that isn't displayed on the home page (using {% if group.private != True %} so the User won't be able to return to the Group detail without having to reclick the link they were sent. -
trouble with testing advisory_lock with pytest
Im currently trying to test a function that will lock some string and will not allow to do anything under that locked string, using advisory_lock. so here is my code: import pytest from django_pglocks import advisory_lock from threading import Thread from time import sleep def function_that_should_lock(): with advisory_lock('secret_string', wait=True): sleep(10) @eager_db_test def test_archive_qualifications_from_project_resource_lock(): failed = False lock_project_resource_qa_action_thread = Thread( target=function_that_should_lock, ) lock_project_resource_qa_action_thread.start() with advisory_lock(f'secret_string', wait=False): failed = True assert not failed For some reason function_that_should_lock actually doesn't lock the string, and failed will be set to True. Please help me understand how it works =) -
cant get selenium to work i want to test my django channels application
im trying to test my app and even if i do the most basic things my selenium refuses to work all i get is a long error message and i cant figure out why im new to selenium and i cant understand these errors, would love some help, im working on static server in django idk if its important CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } tests.py import time from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): @classmethod def setUpClass(cls): try: super().setUpClass() cls.driver = webdriver.Chrome('C:\\Users\\David\\Desktop\\VSProjects\\LiveChat\\chromedriver.exe') cls.driver.implicitly_wait(10) except: cls.tearDownClass() @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_admin_login(self): self.driver.get(self.live_server_url) time.sleep(20) error code (livechat_env) PS C:\Users\David\Desktop\VSProjects\LiveChat\livechatapp> py manage.py test --keepdb Found 1 test(s). Using existing test database for alias 'default'... System check identified no issues (0 silenced). DevTools listening on ws://127.0.0.1:53585/devtools/browser/326e028a-0c32-4557-93a4-6c55304bae1d ETraceback (most recent call last): File "<string>", line 1, in <module> File "C:\Python310\lib\multiprocessing\spawn.py", line 107, in spawn_main new_handle = reduction.duplicate(pipe_handle, File "C:\Python310\lib\multiprocessing\reduction.py", line 79, in duplicate return _winapi.DuplicateHandle( OSError: [WinError 6] The handle is invalid ====================================================================== ERROR: test_admin_login (room.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\David\Desktop\VSProjects\LiveChat\livechat_env\lib\site-packages\django\test\testcases.py", line 287, in _setup_and_call self._pre_setup() File "C:\Users\David\Desktop\VSProjects\LiveChat\livechat_env\lib\site-packages\channels\testing\live.py", line 52, in … -
cannot show the field 'name' in REST API
When I try to retrieve all data from my REST API I get them correctly except from one field, that is the field 'name' from Skill class. Instead of the 'name' I get only its id. Can you help me to resolve this?---------------------------------------------- here is the output Here is the code: models.py from django.db import models from django.forms import ImageField from django.utils.text import slugify class Skill(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Project(models.Model): title = models.CharField(max_length=200) sub_title = models.CharField(max_length=200, null=True, blank=True) front_page = models.ImageField(null=True, blank=True, upload_to="images", default="broken-image.png") body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) skills = models.ManyToManyField(Skill, null=True) slug = models.SlugField(null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug == None: slug = slugify(self.title) has_slug = Project.objects.filter(slug=slug).exists() count = 1 while has_slug: count += 1 slug = slugify(self.title) + '-' + str(count) has_slug = Project.objects.filter(slug=slug).exists() self.slug = slug super().save(*args, **kwargs) serializers.py from rest_framework import serializers from project.models import Project, Skill class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' views.py from rest_framework.response import Response from rest_framework.decorators import api_view from project.models import Project, Skill from .serializers import ProjectSerializer from rest_framework import status from django.shortcuts import get_object_or_404 @api_view(['GET']) def getData(request): project = Project.objects.all() serializer = ProjectSerializer(project, … -
Django for APIs: Build web APIs with Python and Django
I am currently searching for Django for APIs: Build web APIs with Python and Django 4.0 PDF it would be very helpful if anyone provide me with this books pdf