Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST method of request returns the name whose value has been truncated after spaces
I am trying to create a calories app in which the user will select from a list of values (dropdown list) and then total calories consumed will be returned. Now I have a form in which there are certain food items and the user can select them and they will be added to food items consumed by the user in the database. The index.html file responsible for this action is as under: <div class="container"> <form method="POST"> {% csrf_token %} <select class="form-control" id="food_consumed" name="food_consumed"> {% for item in items %} <option value={{item.item_name}}> {{item.item_name}} </option> {% endfor %} </select> <button type="submit" class="btn btn-success m-3"> Add </button> </form> </div> The following view processes the data and stores it in the database: def index(request): if request.method == "POST": food_item_name = request.POST.get('food_consumed') food_item = FoodModel.objects.filter(item_name = food_item_name) food_consumer = request.user food_item_consumed = Consumer(food_consumer = food_consumer, food_consumed = food_item) food_item_consumed.save() food_items = FoodModel.objects.all() return render(request, 'CaloriesApp/index.html', context={'items':food_items}) However, I am encountering a weird error. The value of the food_item_name gets truncated after spaces, that is to say that for instance I have a food item called Egg, raw (147g), the name returned will be: "Egg,". However, when there are no spaces in food items names, there … -
Use django auth with WordPress
I want to make a website with Django as backend for most of the task, but for the frontend I want to use WordPress for page management and also to use Elementor as GUI page builder. But problem is that I want to make a single login system for both WordPress and Django with of course Django default user table. I have read a lot of articles about it they all somehow revolve wp-api but I don't require this in my case. I just want to sign-in into WordPress with Django table. And also if user is logged in into Django it must be logged into WordPress with same session (I am using same domain). -
Limit field permissions on Graphene Django
Lets say I got a user Type class UserType(DjangoObjectType): class Meta: model = User fields = [ "fieldA", "fieldB", "relationshipA", "relationshipB" ] And I want fieldB and relationshipB to be visible only to the owner (user). What is the best strategy to do this? Initially Ive created a PublicUserType excluding private fields, but quickly I realized that it might not be scalable because not only I'll have to create private representation for UserType I'll might also create private representation for any relationship (relationshipA etc), and proper resolvers, and duplicate fragments etc. Is there a best practice here? -
How to have a page/view have a different session duration in django?
I have a django project for which I must set the SESSION_COOKIE_AGE setting to 15 minutes, and I can not change that. In this project there also is a JS editor on a page: users can use the editor to make modification to something, and then hit the "save" button to save the result. The page is handled by a view. The editing can be time-consuming, so often happens that when the user clicks save, his session is already ended. How can I make that page and only that page have an unlimited session duration? Will a <script> making like a request each 5 min refresh the session successfully and keep it alive? -
Unable to create websockets with django
I have a django server that at the moment i am running on my local machine, the django server handles WSGI requests at the moment via http but i would also like to connect with websockets.i have tried many guides online but they all result with the websocket connection returning a 404. Any help would be appreciated. Project Structure: myProject myApp myProject.urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("server/", include("myApp.urls")), ] myProject.asgi import os import django from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter, get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings") django.setup() application = get_default_application() myProject.routing from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from myApp.consumers import PracticeConsumer from django.urls import path application = ProtocolTypeRouter( { "websocket": AllowedHostsOriginValidator( URLRouter([path("five/", PracticeConsumer())]) ) } ) myProject.settings (relevant parts) ASGI_APPLICATION = "myProject.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } WSGI_APPLICATION = "myProject.wsgi.application" INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "storages", "channels", "myApp", ] ALLOWED_HOSTS = ["*"] myApp.consumers import asyncio from channels.generic.websocket import AsyncWebsocketConsumer class PracticeConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): # Handle received WebSocket message here await self.send(text_data=text_data) let me know if there is anything … -
How to serialize the many-to-many fields in DRF?
I have three tables in models.py: class literature_info(models.Model): pmid = models.CharField(primary_key=True,max_length=25) publication = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.pmid class dataset_info(models.Model): dataset_id = models.CharField(primary_key=True,max_length=25) literature = models.ManyToManyField(literature_info, through='literature_dataset', blank=True) def __str__(self): return self.dataset_id class literature_dataset(models.Model): literature_info = models.ForeignKey(literature_info, on_delete=models.CASCADE) dataset_info = models.ForeignKey(dataset_info, on_delete=models.CASCADE) When I try to access the literature id from dataset_info table, I serialize the fields like this: class literature_info_serializer(serializers.ModelSerializer): class Meta: model = literature_info fields = "__all__" class dataset_literature_serializer(serializers.ModelSerializer): literature = literature_info_serializer(many=True) class Meta: model = dataset_info fields = ('dataset_id','literature',) It works well, and i get the literature info via dataset. Now I want to get the literature's datatset from literature_info table, i try to serialize the filed like this: class dataset_info_serializer(serializers.ModelSerializer): class Meta: model = dataset_info fields = ('dataset_id',) class literature_dataset_serializer(serializers.ModelSerializer): dataset_info = dataset_info_serializer(many=True) class Meta: model = literature_info fields = ('pmid', 'dataset_info',) However, it doesn't work this time. So how can i solve this problem? -
Django POSTing from react app issue, CSFR issue
I am creating a simple Django backend, react frontend app, and am trying to get login working, however I get a couple of errors. My views function is: # @csrf_exempt def login_user(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) print(data, type(data)) print('username' in data) # return JsonResponse({'status':'success'}, safe=False) if 'username' not in data or 'password' not in data: return JsonResponse({'status':'error'}, safe=False) # print(data.username) username = data['username'] password = data['password'] print(username, password) user=authenticate(request, username=username, password=password) if user is not None: login(request, user) print('yay') return JsonResponse({'status':'success'}) My settings are: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS=True # CSRF_COOKIE_SECURE = False # CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] # CSRF_TRUSTED_ORIGINS = ['http://localhost:3000'] The frontend: const login_link = 'http://127.0.0.1:8000/logint' const login_link2 = 'http://127.0.0.1:8000' const handleSubmit = async (event) => { event.preventDefault(); // console.log(event) // console.log(event.nativeEvent.target) const data = await axios.post(login_link, {username:username, password:password}); // var csrf = document.querySelector('meta[name="csrf-token"]').content; // // var csrftoken = getCookie('csrftoken'); // var headers = new Headers(); // var payload = {username:username, password:password} // headers.append('X-CSRFToken', csrf); // const data = await fetch('/api/upload', { // method: 'POST', // body: payload, // headers: headers, // credentials: 'include' // }) console.log(data) } The current error is: Forbidden (Origin checking failed - http://localhost:3000 … -
The script launched by the apscheduler does not update the sqlite3 database on the server, but everything works ok on the localhost
I have a django application in which apschaduler periodically runs scripts that receive data from several emails and insert it into the sqlite3 database. When I run the project on localhost, everything is OK, but when I run it on the server, only the update_db_html function works. The scheduler runs update_db_sbd and update_db_gonets scripts, mail is read, but the database is not updated. What could be the problem? Sorry if this is a dumb question. Functions that update the database import csv import requests from bs4 import BeautifulSoup from .models import * from .parse_email import * def update_db_sbd(): imap_data = iridium_sbd_email("imap.mail.ru", "test.marlin-yug@mail.ru", "...") msg_list_bin = imap_data[0] IMEI_list = imap_data[1] data_list = zip(msg_list_bin, IMEI_list) for data in data_list: if data[1] in ('300234069704440', '300234069704480', '300234069705500'): data_format = 'IceBTC' Table = TableIceBTC elif data[1] == '300234069701970': data_format = 'IceBTC11' Table = TableIceBTC11 elif data[1] == '300234069704960': data_format = 'IceST' Table = TableIceST else: data_format = 'permafrost-32T' Table = TablePermafrost table_data = {} with open(f"tables/formats/{data_format}.csv") as f: reader = csv.reader(f) for row in reader: if 'GNSS' in row[0]: row[0] = row[0][4:] table_data[row[0]] = parse2float(data[0], int(row[1]), int(row[2]), float(row[3]), float(row[4])) try: table_data['mdatetime'] = datetime.strptime(f'{int(table_data["Year"])} {int(table_data["Month"])} ' f'{int(table_data["Day"])} {int(table_data["Hour"])} ' f'{int(table_data["Minute"])} {int(table_data["Second"])}', '%Y %m %d %H %M … -
ReactDOM not rendering in Django template
I am trying to integrate a React frontend into my Django project. I'm using Babel (ver 7.22) and webpack to bundle everything into index-bundle.js Currently, the index-bundle.js file is being fetched (according to the GET requests in terminal), but nothing is being loaded into the actual Django template. When I inspect the page, there is nothing from the js file being loaded. Everything was working until I tried adding in react components, but now nothing is working at all. File structure: -myproject --frontend ---index.js ---App.js --static ---css ---js ---index-bundle.js --templates my idex.js is literally just ReactDOM.render(<h1>help</h1>, document.getElementById("root")) I've already ensured that the template is loading the index-bundle.js file and has <div id="root"></div> -
Django unable to load css and icons from nextjs project
The problem: django is unable to load css, svgs and other files from nextjs project here is the error: Not Found: /_next/static/css/app/layout.css Not Found: /vercel.svg [28/Jul/2023 16:31:55] "GET /_next/static/css/app/layout.css?v=1690542114858 HTTP/1.1" 404 2541 Not Found: /_next/static/css/app/page.css [28/Jul/2023 16:31:55] "GET /vercel.svg HTTP/1.1" 404 2462 [28/Jul/2023 16:31:55] "GET /_next/static/css/app/page.css?v=1690542114859 HTTP/1.1" 404 2535 Not Found: /_next/static/chunks/main-app.js [28/Jul/2023 16:31:55] "GET /_next/static/chunks/main-app.js HTTP/1.1" 404 2525 Not Found: /next.svg Not Found: /_next/static/chunks/webpack.js [28/Jul/2023 16:31:55] "GET /next.svg HTTP/1.1" 404 2456 [28/Jul/2023 16:31:55] "GET /_next/static/chunks/webpack.js HTTP/1.1" 404 2522 Not Found: /_next/static/chunks/webpack.js [28/Jul/2023 16:32:21] "GET /_next/static/chunks/webpack.js HTTP/1.1" 404 2522 So, i was trying to integrate django with nextjs, and after trying everything i could, there is one problem remaining. django being unable to load css, svgs and other files from nextjs project. here's the code: project.urls.py """ URL configuration for django_with_nextjs project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a … -
Where is my blocking code? I do not receive WebSocket message - Django Channels
So I have setup a simple web app with Django Channels, that handles some WebSocket connections. It works almost perfect, however it does not receive messages, after I send messages initiated by another connection. This is my consumers: class CPConsumer(AsyncWebsocketConsumer): async def connect(self): self.cp_id = self.scope["url_route"]["kwargs"]["cp_id"] self.cp = charge_point(self.cp_id, self) await self.channel_layer.group_add(self.cp_id, self.channel_name) await self.accept() async def disconnect(self, _): await self.channel_layer.group_discard(self.cp_id, self.channel_name) async def receive(self, text_data): print(f"CP {self.cp_id} sent: {text_data}") await self.cp.route_message(text_data) async def get_config(self, _): print(f"CP {self.cp_id} updates firmware") await self.cp.call(call.GetConfigurationPayload()) print(f"CP {self.cp_id} sent response") class CPUserConsumer(AsyncWebsocketConsumer): async def connect(self): self.cp_id = self.scope["url_route"]["kwargs"]["cp_id"] await self.accept() async def disconnect(self, _): pass async def receive(self, text_data): print(f"User {self.cp_id} sent: {text_data}") await self.channel_layer.group_send(self.cp_id, {"type": "get.config"}) The CPConsumer isolated works perfect. It receives the messages, and routes them through the charge_point class. The charge_point object returns a message (it calls the consumers send method), and it is received by the client. So far so good. Now I want the CPUserConsumer to initiate a message to the connection in the CPConsumer. The charge_point object needs to handle sending that messages. So when the CPUserConsumer client sends a message, I can se that it is forward to the get_config method in the CPConsumer. The first … -
FullResultSet error during migration with mssql (sql server)
I am trying to connect a SQL Server database with Django. But when I do "migration", I have this error : File "...\Python311\Lib\site-packages\django\db\models\sql\where.py", line 174, in as_sql raise FullResultSet django.core.exceptions.FullResultSet My tables are created in database but when I want to do another migration or make migration, I have this error. I am using pyodbc and mssql-django packages settings.py : DATABASES = { 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_HEALTH_CHECKS': False, 'CONN_MAX_AGE': 0, 'ENGINE': 'sql_server.pyodbc', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '***', 'PORT': '***', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', "setdecoding": [ {"sqltype": pyodbc.SQL_CHAR, "encoding": 'utf-8'}, {"sqltype": pyodbc.SQL_WCHAR, "encoding": 'utf-8'}], "setencoding": [ {"encoding": "utf-8"}], }, 'TIME_ZONE': None, } When I drop django.migrations table in the database, I no longer have the error for 'makemigration' but there is the "table already exists" error. This recreates the 'django.migrations' table and the error appears again. -
TemplateDoesNotExist at /post/3
I have a template that should show the details of a post when you request it, but when you request it, there is a TemplateDoesNotExist error in /post/3. It shows me, but the rest of the templates are working correctly except for this one I feel that somewhere I should have used ., but instead I used / or vice versa models.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField(Category) title = models.CharField(max_length=100) body = models.TextField() img = models.ImageField(upload_to='img/post') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.title} - {self.body[:30]}..." urls.py: from django.urls import path from . import views urlpatterns = [ path('post/<int:pk>', views.detalis, name='post') ] urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('home_app.urls')), path('',include('account.urls')), path('',include('blog.urls')), ] urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_URL) views.py: from django.shortcuts import render from .models import Post def detalis(request, pk): post = Post.objects.get(id=pk) return render(request, 'blog/post-detalis.html', {'post': post}) setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / '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', ], … -
Django: GET request is working correctly, but sending the data in the POST request is not working
I sent a POST to this url http://127.0.0.1:8000/user_ques_management/add_favorite_question/ again with this JSON body: { "idname": "aallen", "question_id": 201 } Got response: { "error": "User not found." } And also got this in the terminal: Received POST data: <QueryDict: {}> Received idname: None Not Found: /user_ques_management/add_favorite_question/ But when I sent a GET request with the same users user id to this url http://127.0.0.1:8000/user_ques_management/favorite_read_questions/3486/: I got successful response: { "user_id": 3486, "display_name": "Dustin Rodriguez", "favorite_questions": [], "read_questions": [] } I see the user information is there in the Database too. Here is my model for UserProfile: class UserProfile(models.Model): idname = models.CharField(max_length=250, unique=True) display_name = models.CharField(max_length=250) email = models.EmailField() phone = models.CharField(max_length=20) def __str__(self): return self.display_name Views.py for both of the urls: View to Insert Favorite Question for a User @csrf_exempt def add_favorite_question(request): if request.method == 'POST': print("Received POST data:", request.POST) idname = request.POST.get('idname') # Use 'idname' instead of 'user_id' question_id = request.POST.get('question_id') print("Received idname:", idname) # Print the received idname try: user = UserProfile.objects.get(idname=idname) question = Question.objects.get(id=question_id) FavoriteQuestion.objects.create(user_id=user, question_id=question) return JsonResponse({'message': 'Favorite question added successfully.'}) except UserProfile.DoesNotExist: return JsonResponse({'error': 'User not found.'}, status=404) except Question.DoesNotExist: return JsonResponse({'error': 'Question not found.'}, status=404) View to Retrieve Favorite and Read Questions for a User def … -
How add to ajax request additional GET params in django-ajax-select?
I need sent parametr region with ajax request in select. Select sending ajax without additional parameter `@register('address') class TagsLookup(LookupChannel): model = Address def get_query(self, q, request): **region = request.GET.get('region')** region_null = '__'.join([region, 'isnull']) return list(self.model.objects .filter(**{region_null: False}) .exclude(**{f'{region}': ''}) .exclude(**{f'{region}': ' '}) .order_by(f'{region}') .values_list(f'{region}', flat=True).distinct()) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.city` Send region GET parametw with django-ajax-select request. Their documentation says the following: django-ajax-select documentation -
Django GraphQL subscription returns 400 Bad Request
I have a django v4.2.3 backend. Since graphene doesn't natively support subscriptions, I am using DjangoChannelsGraphqlWs (1.0.0rc6 pre-release version, since I need it to support my version of graphene). I have copy-pasted the default subscription given in the tutorial: class MySubscription(channels_graphql_ws.Subscription): notification_queue_limit = 64 event = graphene.String() class Arguments: arg1 = graphene.String() arg2 = graphene.String() @staticmethod def subscribe(root, info, arg1, arg2): return ["group42"] @staticmethod def publish(payload, info, arg1, arg2): """Called to notify the client.""" return MySubscription(event="Something has happened!") class Subscription(graphene.ObjectType): my_subscription = MySubscription.Field() defining the schema, like usual: schema = graphene.Schema(query=Queries, mutation=Mutations, subscription=Subscription) with a default consumer given in the tutorial class MyGraphqlWsConsumer(channels_graphql_ws.GraphqlWsConsumer): schema = schema async def on_connect(self, payload): print("New client connected!") This is the routing I used: urls.py urlpatterns = [ path("graphql/", csrf_exempt(GraphQLView.as_view(schema=schema, pretty=True, graphiql=True))) ] asgi.py application = channels.routing.ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": channels.routing.URLRouter([ django.urls.path("graphql/", MyGraphqlWsConsumer.as_asgi()), ]) }) I then tried to test my subscription using Apollo, Graphql Playground, etc. and always run into a similar error message: "Could not connect to websocket endpoint wss://paris2022.fr/graphql. Please check if the endpoint url is correct." Anyone has any idea what this can be? -
How to increase max redis channel layer load?
My websocket keeps disconnecting if I run a more resource heavy process. The websocket consumer processes a file and checks if it is in the correct format and returns and a status update, eg "Correct format", "Missing columns", etc. If I delete 20% of the rows from a file that caused the websocket to disconnect it works. I managed to narrow it down to around 500Kb is where the limit is. And also other consumers work too. CHANNELS: The issue occured when I changed from the dev InMemoryChannelLayer to RedisChannelLayer so thats why I think that the error is somewhere in that area and not with the specific consumer or process. The channel layers config is pretty simple, just the basic Redis example fromt the docs: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(os.environ.get("REDIS_HOST"), 6379)], }, }, } I tried setting stuff like capacity, expiry, group_expiry, channel_capacity but nothing worked.\ REDIS: The redis server is running, if i do redis-cli ping it returns PONG. Configs: maxmemory: 0 tcp-keepalive: 300 maxclients: 10000 timeout: 0 ERROR: There isn't too much information in the daphne logs. I get this message: Jul 28 07:31:29 googleds-server daphne[734093]: File "/home/atti/googleds/ds/lib/python3.8/site-packages/redis/asyncio/client.py", line 539, in … -
Packaged django apps installed from Pypi on new django project doesnt show the apps folders and files
In a former django project i have packaged an app for reusing it later in another django project. The app was packaged in both formats, source (tar.gz) and wheel and uploaded to Test Pypi. Then I have installed this app in a new project. Though the functionality of the app works... tested in the dev server, its files and folders are not shown in the VS Code editor, I would like to have them for editing purposes. Thanks in advance for help Everything is already explained -
in ajax get a value upon clicking a button but it is in a loop
$(document).ready(function() { $(".actdeact").on({ click: function() { var id = $('.getfromhere').text(); alert(id); {% for x in mylist %} <span class="getfromhere">{{x.id}}</span> <span class="btn btn-info actdeact">Deactivate</span> {% endfor %}` ` If I write .text() I get the whole series of values of id. If I write .html() I only get the first one I want that upon clicking the button, only the value that corresponds to the row clicked is sent to var id in the ajax code I want to get just the value that corresponds to the row clicked, not the whole of the values of the loop. -
The current path, **/POST, didn’t match any of these
I have a login page that has an auth form, 2 values, after validation, redirect it with these 2 parameters, but i get an error, what did i miss? The Views def LoginPage(request): if request.method == "POST": ordernr = request.POST.get('bestellnummer') email = request.POST.get('email') try: ...."validation shopify api" else: return redirect(f'login/{ordernr}/{email}/') the urls app urlpatterns = [ path('login/', views.LoginPage, name="login"), path('login/<str:pk>/<str:dk>/', views.OrderPage, name="order"), ] the from {% extends 'main.html' %} {% block content %} <div> <form action="POST" action="">{% csrf_token %} <div> <label for="bestellnummer">Ihre Bestellnummer</label> <input type="text" name="bestellnummer" id="bestellnummer" placeholder="Ihre Bestellnummer..."> </div> <div> <label for="email">Ihre Bestell E-Mail</label> <input type="email" name="email" id="email" placeholder="Ihre E-Mail..."> </div> <input type="submit" value="Login"> </form> </div> {% endblock content %} Page not found (404) your text Request Method: GET Request URL: http://127.0.0.1:8000/login/POST?csrfmiddlewaretoken=token123&bestellnummer=1337&email=somefiller@mail.com Using the URLconf defined in retourenportal.urls, Django tried these URL patterns, in this order: admin/ login/ [name='login'] login/str:pk/str:email/ [name='order'] The current path, login/POST, didn’t match any of these. -
Create HTTP response errors and timeouts for testing? [closed]
I suspect a counter outside scope could be used to do this. Does anyone know if there is a particular convention or interceptor to do the same? I’ll be using Flask or Django frameworks. -
Test a model property in django using Pytest
I want to test the output of a model property in django using pytest[pytest-django]. models.py: class TravelFriend(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="travel_friends") name = models.CharField(max_length=100) birthdate = models.DateField() def __str__(self): return self.name @property def age(self): days_in_year = 365.2425 age = int((date.today() - self.birthdate).days / days_in_year) if age >= 18: return "18+" else: return age basically the property return the age in years or the string '18+' if the age is more than 18 test_models.py: class TestTravelFriend: def test_travelfriend(self): """The family member is connected to a user and have valid attributes""" travel_friend = TravelFriendFactory() assert travel_friend is not None assert str(travel_friend) == travel_friend.name assert travel_friend.user is not None assert travel_friend.name is not None assert travel_friend.birthdate is not None assert travel_friend.age is not None factories.py: class TravelFriendFactory(factory.django.DjangoModelFactory): class Meta: model = "accounts.TravelFriend" user = factory.SubFactory("accounts.tests.factories.CustomUserFactory") birthdate = factory.Faker( "date_of_birth", maximum_age=25, ) I want to test that the output of the property is correct but if i put an if statement in the test like this year = -int(travel_friend.birthdate.year - date.today().year) if year < 18: assert travel_friend.age == year else: assert travel_friend.age == "18+" but in order to have 100% coverage I need to test this last part of code which I don't … -
how to create a server-side datatable that displays my data from by database
i need the views and the url and the js i tried alot but didnt work the data is displayed but the datatable stops working this is for my views def get_data_for_datatable(request): employees = Users.objects.all() data = [] for employee in employees: data.append({ "Name": employee.Name, "Gender": employee.Gender, "Email": employee.Email, "Department": employee.Department, "Salary": employee.Salary, }) return JsonResponse({ "data": data, }) this is for my js what s the problem $(document).ready(function() { $("#example").DataTable({ "ajax": "json/", "columns": [ {"data": "Name"}, {"data": "Gender"}, {"data": "Email"}, {"data": "Department"}, {"data": "Salary"}, ], processing: true, serverSide:true, paging: true, pageLength: 10, lengthChange: true, autoWidth: true, searching: true, bInfo: true, bSort: true, }) }) -
Adding fields to ModelForm programatically not showing in django admin
I have a usecase where I want to add fields to a modelform in django admin, but when trying to add them in the __init__function like this: class PackageFileInlineForm(forms.ModelForm): class Meta: model = File fields = '__all__' def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.fields['test'] = forms.CharField(max_length=100) Nothing shows up in the form. However if I do the form like this: class PackageFileInlineForm(forms.ModelForm): test = forms.CharField(max_length=100) class Meta: model = File fields = '__all__' Why does the init version not work? -
Django Multiple User's Authentication, SignUp Serializer and Views
I'm practicing creating multiple user types of authentication (in this scenario, Client and Driver like Uber) along with JWT. Currently, I am trying to write the SignUp Serializer for each corresponding user type (or if there is any more elegant way to do this), after signing up, I would love the user to have a Token. Please have a look at my code and teach me how or what could I do. This is my models from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(unique=True) # vars to check whether user is client or driver is_client = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Client(models.Model): is_staff = False user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username class Driver(models.Model): is_staff = False user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username My serializers.py (kinda messy) from rest_framework import serializers from base.models import User, Customer, Technician from rest_framework_simplejwt.tokens import RefreshToken # Serialize data from db class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin'] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def …