Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to display search term on results page?
I’ve made a successful form and it’s working accordingly displaying the search results when a user makes a form submission. However, I’m stuck with one new addition to this search functionality. How do I get to display the search term with my current code? I’m trying to display the current search term in search_results.html but can’t get the term to display work. The only thing that appears is a blank space. I'm guessing I'm doing something wrong in views.py but don't know what exactly. Any help is gladly appreciated. Thanks! search_results.html <h1>Results for "search term here {{ title_contains_query }}”</h1> base.html (Where the search bar is located) <div class="search-container"> <form method="get" action="{% url 'search_results' %}"> <div class="input-group"> <input type="text" name="q" class="form-control gs-search-bar" placeholder="Search GameStation Games..." value=""> <span class="search-clear">x</span> <button type="submit" class="btn btn-primary search-button"> <span class="input-group-addon"> <i class="zmdi zmdi-search"></i> </span> </button> </div> </form> </div> views.py def is_valid_queryparam(param): return param != '' and param is not None def BootstrapFilterView(request): user_profile = User_Info.objects.all() user_profile_games_filter = Game_Info.objects.all() title_contains_query = request.GET.get('q') if is_valid_queryparam(title_contains_query): user_profile_games_filter = user_profile_games_filter.filter(game_title__icontains=title_contains_query) if request.user.is_authenticated: user_profile = User_Info.objects.filter(user=request.user) context = { 'user_profile': user_profile, 'user_profile_games_filter': user_profile_games_filter } else: context = { 'user_profile': user_profile, 'user_profile_games_filter': user_profile_games_filter } return render(request, "search_results.html", context) -
Django SQL Dealing
I'm working in a Django app and want to query one of my models to perform data dealing. I tried to perform from django.db import connections cursor = connections['default'].cursor() cursor.execute("select * from Collections") print(cursor.fetchall()) Got the following message: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Could not understand the problem since I am already querying models in my views with QuerySet. Any solutions? -
How to make transactions based on the frequency of transaction in Django
I'm new to Django, but I'm working on a project that allows users to create transactions. I would like to be able to create transactions that are recurring, based on a frequency. For example, a user could create a recurring transaction that is paid out every month. I'm not sure how to best implement this functionality. I've been looking at the django-scheduler library, but I'm not sure if that's the best way to go. Does anyone have any ideas on how to implement this functionality? Here is the transaction model that I'm using: class Type(models.TextChoices): """Class for transaction types.""" DEPOSIT = 'Deposit' PAYMENT = 'Payment' class Frequency(models.TextChoices): """Class for tansactin frequency""" ONETIME = 'One-time' DAILY = 'Daily' EVERY_WEEK = 'Every week' EVERY_TWO_WEEKS = 'Every two weeks' EVERY_THREE_WEEKS = 'Every three weeks' EVERY_MONTH = 'Every month' EVERY_TWO_MONTHS = 'Every two months' EVERY_QUARTER = 'Every quarter' EVERY_SIX_MONTHS = 'Every six months' EVERY_YEAR = 'Every year' EVERY_TWO_YEARS = 'Every two years' class Transaction(models.Model): """Transaction model.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) transaction_type = models.CharField( max_length=30, choices=Type.choices, default=Type.PAYMENT, ) transaction_date = models.DateField() frequency = models.CharField( max_length=30, choices=Frequency.choices, default=Frequency.ONETIME, ) category = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, blank=True, related_name='transactions', ) subcategory = models.ForeignKey( SubCategory, on_delete=models.CASCADE, null=True, … -
I get a 403 forbidden in my django project after submiting a form. I know there's a problem with CSRF token
I think the problem is in part due to the fact im not using the HTML template tag since, I'm creating a project using the JS generating the HTML from there. For addressing this in the HTML i added this script(before the js script I use): <script> var csrfToken = '{{ csrf_token }}'; </script> Im using the following script after the form code to send the information to my django project: const apiSendDataUser = (event) => { event.preventDefault(); const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value; const formData = new FormData (event.target); fetch('https://127.0.0.1:8000/myProject/post_user',{ method: 'POST', body: formData, headers: { 'X-CSRFToken': csrfToken } }) .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Error: ' + response.status); } }) .then(data => { // Handle the response data console.log(data); }) .catch(error => { // Handle any errors console.error(error); }); }; And finally, the post_user function on the views.py is: @require_POST def post_user(request): try: email = request.POST['email'] if not User.objects.filter(email).exists() : username = request.POST['username'] password = request.POST['password'] User.objects.create_user(username=username, password=password, email=email) return JsonResponse( { "success":True, "message": "Usuario añadido." } ) except Exception as e: return JsonResponse({ "success": False, "message": e.args[0] }, status=404) I think is all, I dont know how to handle things with … -
django, the form is always wrong
I have a django application and I am writing two-factor authentication by email for it (a code should be sent to the mail). But the problem arises at the stage of checking the current email and password. as I understand it, the if form.is_valid() check does not work and constantly returns a form error. Please enter a correct %(username)s and password. Note that both fields may be case-sensitive. and This account is inactive. Although I am sure that I am entering the correct user data and there is is_active : True in the database table. My user model is redefined like this: class User(AbstractUser): email = models.EmailField(_("email_address"), unique=True) class RoleChoise(models.TextChoices): standard = "ST", "standart" admin = "AD", "admin" worker = "WK", "worker" inactive = "IA", "banned" role = models.CharField(choices=RoleChoise.choices, default=RoleChoise.standard, max_length=2) #another my fields my custom authorization function looks like this: class LoginOrSendCodeView(FormView): template_name = 'accounts/login.html' form_class = UserLoginForm success_url = reverse_lazy('login') def post(self, request, *args, **kwargs): if "OTP_code" in request.POST: ... #my other form handler, it works else: form = UserLoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, email=email, password=password) if user: if user.role != "IA": if user.two_factor_authentication: otp_model_object = OtpModel(user=user) otp_model_object.save() otp_model_object.send_otp_in_mail() return render(request, … -
KeyError: 'receiver' in self.scope[]
I am trying to retrieve data through self.scope[] in Django channels but I keep getting KeyError. How can I get the receiver part through self.receiver_username without the error? See the code details below: consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.receiver_username = self.scope['url_route']['kwargs']['receiver'] self.accept() routing.py websocket_urlpatterns = [ re_path(r'ws/socket-server/(?P<receiver>\w+)/$', consumers.ChatConsumer.as_asgi()), ] chat.html <div id="chat-messages"></div> <form id="form"> <input type="text" name="message" placeholder="Type a message..."> <input type="text" name="receiver" value="test"> <button id="send-button">Send</button> </form> <div id="messages"></div> <script> var receiver = 'test'; let url = `ws://${window.location.host}/ws/socket-server/` + receiver + '/' const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) if(data.type === 'chat'){ let messages = document.getElementById('messages') messages.insertAdjacentHTML('beforeend', `<div> <p>${data.message}</p> </div>`) } } let form = document.getElementById('form') form.addEventListener('submit', (e)=> { e.preventDefault() let message = e.target.message.value chatSocket.send(JSON.stringify({ 'message': message })) form.reset() }) </script> When I try to retrieve the var receiver through self.receiver_username, I got the following error: KeyError: 'receiver' WebSocket DISCONNECT /ws/socket-server/test/ [127.0.0.1:51206] -
How to check if user is logged in using class based custom middleware?
I want to redirect not logged in users to login page every request they do. I have a custom class based middleware. I found on stackoverflow a solution to the problem using function based middleware. When I try to use this function inside my class, it doesn't work. But if I remove class and leave the function, it works fine. How can I fix this problem? # class based class CustomMidd: def __init__ (self, get_response): self.get_response = get_response def __call__(self, request): self.check_user(request) self.process_request(request) response = self.get_response(request) return response # def process_request(self, request): # allowed_ips = ['127.0.0.1'] # my ip # ip = request.META.get('REMOTE_ADDR') # if ip not in allowed_ips: # raise Http404 # return None def check_user(self,request): if request.user.is_authenticated or request.path == '/login/': response = self.get_response(request) return response return redirect('/login/') # function based def require_login(get_response): def middleware(request): if request.user.is_authenticated or request.path == '/login/': response = get_response(request) return response return redirect('/login/') return middleware It should also raise 404 error if ip is not allowed. So if I leave only function, it works, but I can't check ip now. When I try to enter main page, it returns an error Field 'id' expected a number but got.... This is because at the … -
Django form.is_valid() doesnt let anything go through. (False)
The program doesnt have any typos. when i try to write to the database via forms and press submit, the request will come back, but wont be inserted into database. # views.py from django.shortcuts import render from django.http import HttpResponse from .models import Book from .forms import BookForm # Create your views here. def homepage_welcome(request): return render(request, 'homepage.html') def addbook(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): form.save() return render(request, 'bookadded.html') return render(request, 'addbook.html') else: return render(request, 'addbook.html') def borrowbook(request): books = Book.objects.all() return render(request, 'borrowbook.html', {'booklist': books}) def book(request, pk): book = Book.objects.get(id=pk) context = {'book':book} return render(request, 'book.html', context) def bookadded(request): return render(request, 'bookadded.html') # forms.py from django.forms import ModelForm from .models import Book class BookForm(ModelForm): class Meta: model = Book fields = '__all__' # urls.py from django.urls import path from . import views urlpatterns = [ path('', views.homepage_welcome), path('addbook/', views.addbook, name='addbook'), path('borrowbook/', views.borrowbook), path('book/<str:pk>/', views.book, name = 'book'), path('bookadded/', views.bookadded), ] # models.py from django.db import models from django.utils import timezone # Create your models here. class Book(models.Model): booktitle = models.CharField(max_length=100) content = models.TextField() date_created = models.DateTimeField(default=timezone.now) I tried running the code without the if form.is_valid(): line, but that resoulted in "ValueError at /homepage/addbook/". then … -
Has superset functionality changed?
I've been using Django and superset in docker containers. I had these two lines of codes <div class="container"> <a target="_blank" href="http://localhost:8088/login?username={{ username }}&redirect=/superset/dashboard/services/?standalone=0&expand_filters=0">Explore Dataset</a> </div> <div> <iframe src="http://localhost:8088/login?username={{ username }}&redirect=/superset/dashboard/services/?standalone=&show_filters=1" style="position:absolute;top:220px;bottom:0px;width:100%;height:100%"></iframe> </div> Up until last week they have both worked. The first one to function as a link to the actual superset page and the iframe to show a specific dashboard on the page. I rebuilt my containers last week and now my iframe doesn't work. It shows 'localhost refused to connect.' The other link, however, does work still. Is anyone aware of a change in superset (or Django) and a possible fix or workaround to get this working again? -
django docker, how to copy local db data to the docker db?
I have dockerized a existing django app and an existing postgres database.the tables are created in the docker container. But the tables are empty . There is no data in it. if I connect to the docker container. And I do a \d+ | Schema | Name | Type | Owner | Persistence | Size | Description | --------+------------------------------------------+----------+---------------+-------------+------------+------------- | public | hotelWelzijnAdmin_animal | table | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_animal_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_category | table | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_category_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_groups | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_groups_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account_user_permissions | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_user_permissions_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | … -
Can I use Prisma as the ORM inside of Django instead of Django's ORM?
I'd like to use Django + Django Rest Framework as my backend for a bunch of reasons (maturity, great tooling, security, etc.). I'm curious about using Prisma as the ORM layer instead of Django's ORM. Is there anything technically infeasible with this setup, or are there any major gotchas that may not be obvious that would make this a terrible idea? -
Make endpoint that returns a list of strings using Django Rest Framework
I have this Artist model: class Artist(models.Model): name = models.CharField(max_length=100) #songs = models.ManyToManyField('Song', related_name='artists') def __str__(self): return self.name class Meta: ordering = ('name',) I want to make a api endpoint that returns all the Artists row names as a list of string like for example: ["50 Cent", "Eminem", "Snoop Dogg", ...] . i have created this artists/names/ url in my urls.py: path('artists/names/', views.artist_names, name='artist_names'), I have tried two ways already: Using a python list: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) artist_names_list = list(artists) return Response(artist_names_list) Using ListSerializer in my serializers.py: class ArtistNameSerializer(serializers.Serializer): name = serializers.ListSerializer(child=serializers.CharField()) and in my views.py i created the artist_names method: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) serializer = ArtistNameSerializer(artists, many=True) return Response(serializer.data) From both of them when i go to the endpoint i get: GET /api/artists/names/ HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Can someone help? What am i doing wrong? -
Chart.Js - Chart-geo map is too small
I'm using the module Chart-Geo to make a choropleth map using Chart.Js It actually displays, but for some reason it's too small. I'm not trying to make a zoom option (using scroll) but just make it proper for visualization. I couldn't find a solution since Chart-Geo documentation doesn't enter in zoom topics. Seems like it's rendering the entire world size, but as it lacks data from other countries, it's just rendering Brazil. Observations: I'm using the framework Django. I'm using datamaps's data to get topoJson. Here is my code: home.html {% extends "base.html" %} {% block body %} {% load static %} <link rel="stylesheet" href="{% static 'css/home/home.css' %}"> <body> <div class="banner2Div"> <p>Cadastro por região</p> <canvas id="chart4" width="400" height="400"></canvas> </div> </body> <script src="{% static 'javascript/chart.umd.js' %}"></script> <script src="{% static 'javascript/index.umd.min.js' %}"></script> <script src="{% static 'javascript/d3.js' %}"></script> <script src="{% static 'javascript/bra.topo.json' %}"></script> <script type="module" src="{% static 'javascript/home.js' %}"></script> {% endblock%} Javascript const chart4 = document.getElementById('chart4') import brJSON from './bra.topo.json' assert {type: 'json'} const canvas_width = chart4.width const canvas_height = chart4.height const trlte_shift = [canvas_width / 71, canvas_width / 28.8]; const states = ChartGeo.topojson.feature(brJSON, brJSON.objects.bra).features; const chart = new Chart(chart4, { type: 'choropleth', data: { labels: states.map(d => d.properties.name), datasets: [{ label: 'States', … -
I'm using Django and Postgres on Docker, but I can't connect to the database after reinitialising
IMPORTANT NOTE: Django can't RECONNECT to the database. It works, then I try reinitialising it, and it stops working due to what's described below. I can get it to work if I reboot my PC, though. I'm running Django and PostgreSQL with Docker Compose (one container for Django and the other for PostgreSQL) I was using the container perfectly with no problems. After typing sudo docker compose down -vand sudo docker compose up -d, Firefox won't connect, and will show the message: The connection was reset So I run sudo docker compose logs -f to check the logs and Django says it can't connect to the Postgres database with the following messages: [...]port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? -
Can't write in input field, I'm using django and generating HTML from JS
I'll show you both my HTML and my JS code. Its simple by now, but this problem might be a challenge to all my project since I have several things that will work like this form. Apologies console.log message is in spanish, but it runs all the script. The problem is when i reach to the form itself i cant write anything, well you can write if you hold de click. Havent used any CSS, rather than the style thing on z i. const fillSection = (option = "user-registration", e ) => { console.log("you are filling section"); console.log(e); const content = document.querySelector('#user-registration') switch (option) { case "user-registration": content.innerHTML = `<form id="user-registration-form" method="post" style="z-index: 1000 !important;"> <div class="input-texts"> <div class="form-field"> <label for="name-user">Nombre</label> <input id="name-user" type="text" name="username" placeholder="Enter your name"> </div> <div class="form-field"> <label for="password-user">Password</label> <input id="password-user" type="text" name="password" placeholder="Enter your password"> </div> <div class="form-field"> <label for="email-user">Email</label> <input id="email-user" type="text" name="email" placeholder="Enter your email"> </div> </div> <button id="submit-button" class="form-btn" type="submit">Register</button> </form>`; const sendDataForm = document.getElementById("submit-button"); console.log("seleccionado el submit"); sendDataForm.addEventListener('submit', (e) => {apiSendDataUser(e)}); break; } }; const apiSendDataUser = (event) => { event.preventDefault(); const formData = new FormData (event.target); fetch('https://127.0.0.1:8000/videoHub/post_user',{ method: 'POST', data: formData }) .then(response => response.json()); } ; const registerSectionButton = … -
TemplateSyntaxError, Could not parse the remainder:
template.html {% with category2Choices=form.category2.field.choices.queryset.values_list("value", "display_name", "parent_id")|list %} <script> var category2Choices = JSON.parse('{{ category2Choices|json_script:"category2Choices" }}'); </script> {% endwith %} I am getting this issue: TemplateSyntaxError at /pages/add_product/ Could not parse the remainder: '("value",' from 'form.category2.field.choices.queryset.values_list("value",' I want to initially populate the main categories in a select field. When the user selects a main category, I want to dynamically fetch and display the subcategories related to that main category. To achieve this, I am using a small JavaScript code. Can you help me? -
How to maintain AnonymousUser session with Django test client
I have a Django TestCase where I would like to test an AnonymousUser visiting the same page twice. I would like to test that an action is only taken on the first visit, which is achieved by storing some data in the session upon the first visit. I can't use TestCase.client, because it uses a new AnonymousUser for each request and they have a new session. from django.test import TestCase class MyTestCase(TestCase): def test_my_test(self): self.client.get(url) response = self.client.get(url) self.assertTrue(...) -
Nginx authenticate iframe
I am running a django app on a server and i am running grafana on a different server with nginx as a reverse proxy (grafana and nginx are on the same server). I can manage to redirect an incoming URL and authenticate it via my backend, but I still get redirected to the grafana login screen, even when my django app sends a 200 response My setup: I am having a grafana server running under https with a nginx proxy. The nginx-setup server { server_name grafana.myserver.com; location / { proxy_set_header Host $host; proxy_pass http://localhost:3000/; proxy_set_header X-Real-IP $remote_addr; } location ~ ^/iframe(.*)$ { auth_request /iframe-auth; set $iframe_url http://localhost:3000$1$is_args$args; proxy_pass $iframe_url; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Authorization $http_authorization; } location = /iframe-auth { internal; proxy_pass https://blub.de/auth/check/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; } } In the above I am using the nginx auth module to redirect the incoming URL from the iframe the my django backend server. Here I do the authentication which works fine. I tested this by printing out the URL and I am authenticating the user and I am returning a 200 response if authenticated. Ok cool. I expected … -
CORES header issue in react django application
we are using django with react and in the settings.py file we have set the "CORS_ORIGIN_ALLOW_ALL" to True. we have also installed the coresheader app. but when the frontend is going to request for an api from 'http://localhost:3000/' but we still get the CORS policy error => Access to XMLHttpRequest at 'https://backend.com/api/v1/Category' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. here is the settings.py file configurations: INSTALLED_APPS = [ ..., 'corsheaders', ] MIDDLEWARE = [ ...., 'corsheaders.middleware.CorsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontEnd/build'), os.path.join(BASE_DIR, 'templates'), ], 'DIRS': [os.path.join(BASE_DIR, 'templates'), # os.path.join(BASE_DIR, 'venv/lib/site-packages/django/contrib/admin/templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'libraries': { 'staticfiles': 'django.templatetags.static', }, }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontEnd/build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' CKEDITOR_UPLOAD_PATH = 'ck/' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full' }, } CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True and blew is how the frontend makes the api call requests using axios: import axios from 'axios' import { readCookie } from 'utils/readCookie' const isProduction = process.env.NODE_ENV === 'production' const csrfToken = readCookie('csrftoken') … -
ORM does not bring all the fields of a custom model of users
I am trying to get a user that I have saved with a custom model as follows: TblUsers.objects.get(id=request.user.id) But this only brings up the "email" field of my record, however I have many more fields in my custom model What brings me: <QuerySet [<TblUsuarios: juan@juan.com>]> My custom model: class TblUsers(AbstractUser): email = models.EmailField("email address", unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) phone= models.CharField(max_length=11, blank=True, null=True) photo= models.ImageField(upload_to=upload_image, default = '/') USERNAME_FIELD = 'email' REQUIRED_FIELDS=(['username']) objects = UserManager() class Meta: managed=True db_table = 'tbl_users' The manager class of my custom user: class UserManager(UserManager): def create_user(self, email, password, **extra_fields): """ Create a user """ if not email: raise ValueError(_("The email must have info")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create a super user """ extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("The superuser should have is_staff=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("The superuser should have is_superuser=True.")) return self.create_user(email, password, **extra_fields) I have tried to get all the information from the table with: TblUsers.objects.all() But this has had the same result, it only fetches the "email" field from all the records -
ImportError: cannot import name 'Employees' from 'EmployeeApp.models'
I am pretty new to Building an application with Django Framework, Python and Flask. I tried to import reference some module and i receive this error. Can someone help? My code is below from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from EmployeeApp.models import Departments,Employees from EmployeeApp.serializers import DepartmentSerializer,EmployeeSerializer The error that i saw ImportError: cannot import name 'Employees' from 'EmployeeApp.models'(/path/to/the/file.py) rest_framework.parsers could not be resolved. Also, it seem that the line of the Employees in line 6 & EmployeeSerializer in line 7 are not able to be imported. Please let me know if you need further information. I expected running python manage.py runserver to pass successfully but with the failed error above, it gives me worries. -
Sending email to a particular user email address in Admin Django
Need help on how to implement send mail to a particular user email address in Admin when logged in. For example, I have multiple registered users with email address in Admin, so if USER alukas logged in then an email will be sent to his email address albertlukasrodriquez@g..com... I attached images to my question based on what I have tried. -
Any recommendations for an smtp or email provider I could use for my Django project. I've tried several none work well with it
I have tried several email providers for my project but they don't seem to work so if you know or use anything not very common and it works well, I'd like to know as well and also I can't stress this point enough it must be free or have a free plan I have tried the popular ones like mailjet,sendgrid,MailChimp,brevo,Gmail outlook and Yahoo didn't even work even after using less secure app settings in Gmail -
Displaying an image saved in a variable in Vue 3
I have an application based on Vue 3 and Django REST. The application displays songs in a database, and is also supposed to display the cover images of the songs' respective albums. I have the cover images in the file system of the server and can access them via Django, and hand them out via a FileResponse when an API request comes in. I receive them in the Frontend and save the image to a variable. However, when I want to then display the image in an tag, it just looks like this: I want the gray boxes to display the album cover art instead. What's weird is that my browser receives the images from the API and displays them correctly: (I know that the cover art is incorrect for the songs, that's not the point here). The API (Django REST): @api_view(['GET']) def img_api(request): if request.method == "GET": if request.GET['id'] == 'undefined': return HttpResponse( HttpResponse(serializers.serialize('json', Song.objects.none()), content_type='application/json')) if 'id' in request.GET: query = request.GET['id'] song = Song.objects.filter(song_id=query).first() try: img = open(os.path.join(SONG_PATH, song.song_image_file), 'rb') if song.song_image_file.endswith(".png"): return FileResponse(img, content_type='image/png') return FileResponse(img, content_type='image/jpeg') # file is closed automatically except FileNotFoundError: return HttpResponse(HttpResponse(serializers.serialize('json', Song.objects.none()), content_type='application/json')) except PermissionError: return HttpResponse(HttpResponse(serializers.serialize('json', Song.objects.none()), content_type='application/json')) return HttpResponse(HttpResponse(serializers.serialize('json', … -
How can i add a message in the screen when receiving a 500 to explain you cannot add duplicates values using django and JS
Hi guys i have a little API created in django and i set some constraints in order to avoid duplicated values, so when you want to add a duplicated value it returns this message in the console is there a way i can add a message in the screen saying something like "this user already exists" right after the POST was denied?