Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use the free domain given by ngrok?
In their release of ngrok https://ngrok.com/blog-post/new-ngrok-domains, they now provide free domains to free users as of April 2023. I can see my one free domain at https://dashboard.ngrok.com/cloud-edge/domains. However, I don't know how to use it. I have tried ngrok http -subdomain=xxx.ngrok-free.app 80 and ngrok http -subdomain=xxx 80 But it will give me an error Custom subdomains are a feature on ngrok's paid plans. Failed to bind the custom subdomain 'xxx.ngrok-free.app' for the account 'James Arnold'. This account is on the 'Free' plan. Is there a documentation on how to use this free domain by ngrok? -
How to Create different user/Member types in Python Django?
I need to create a paid memebership website with django.There are three types of members to be registered. these registration form/model will have different form fields appart from common authentication fields. In the admin panel these member/users should be listed separately from the super user/ admin/staff users. how can I achive this? models.py from datetime import timedelta, date, datetime from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.conf import settings from .constants import GENDER_CHOICES, RADIO_CHOICES, INDIAN_STATES,COUNTRIES, DISTRICTS_IN_KERALA class MemberType(models.Model): title = models.CharField(max_length=100, blank=True,null=True) slug = models.SlugField(blank=True, null=True) description = models.CharField(max_length=250, blank=True,null=True) price = models.FloatField() def __str__(self): return self.title class NurseMemberManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class NurseMember(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) # Add other fields as needed is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) date_of_birth = models.DateField(null=True) mobile_no = models.CharField(max_length=15) whatsapp_no = models.CharField(max_length=15) address_lene_1 = models.CharField(max_length=150) address_lene_2 = models.CharField(max_length=150) pin_code = models.CharField(max_length=10) nursing_reg_no = models.CharField(max_length=50) employed = models.BooleanField(choices=RADIO_CHOICES,default=True,) country = models.CharField(max_length=100, choices=COUNTRIES, blank=True, null=True) … -
How can I query my API in React in a way that has dynamically defined queries?
I'm using Django Rest Framework and React, but this is more of a conceptual question. I've noticed that when querying data from an API, especially on a React-esque frontend, I always run into the same issues. API responses are not intrinsically typed I cannot specific exactly what fields I'd like to get back from the API I can't specify dynamic type-safe filtering and sorting. In an ideal world, I'd like to be able to do something like this: // Using a user model as an example. export function UserComponent(props: ...){ // `data` is inferred to be of type Pick<User, "email", "lastActive"> const data = myCustomAPIFetch<User>({ model: User fields: [User.email, User.lastActive], filters: { [User.firstName]: "Linus" } // Similar syntax for sorting }) return (...) } This solves all three issues - it returns the proper type object, filtering/sorting is type-safe, and the exact fields that I want back can be specified. The solutions that I've researched here solve some of the problems, but not all. Graphql - solves #2 and can solve #1, but from what I understand I have to make a new query/resolver for each filter or sort I want to do. Not ideal. Protobuf - types are cross-language … -
Django App fails to upload file to quickbooks
Hello all I am encountering a problem while trying to upload a file to quickbooks using the api. Below is the code, I get a success but the file is not sent or cannot be found in the bill itself. Any help would be appreciated. Inside my app views.py def handle_file_uploads(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT, access_token=request.session.get('access_token', None), refresh_token=request.session.get('refresh_token', None), realm_id=request.session.get('realm_id', None), ) if auth_client.access_token is None: return JsonResponse({'status': 'failure', 'message': 'Access token not available.'}) if auth_client.realm_id is None: raise ValueError('Realm id not specified.') if request.method == 'POST': # Get the file input names for each bill ID bill_ids = [key.replace('bill_', '') for key in request.FILES.keys()] for bill_id in bill_ids: uploaded_file = request.FILES.get(f'bill_{bill_id}') if uploaded_file: # Prepare the API endpoint URL to upload the attachment url = f"https://sandbox-quickbooks.api.intuit.com/v3/company/{auth_client.realm_id}/upload" # Prepare the request headers headers = { 'Authorization': f'Bearer {auth_client.access_token}', } # Prepare the file data to be sent as multipart form data files = { 'file_content': (uploaded_file.name, uploaded_file.read(), uploaded_file.content_type), } # Make the API call to upload the attachment response = requests.post(url, files=files, headers=headers) print(response.json) # Check the response status and handle the error case if necessary if response.status_code != 200: error_message = 'API call failed with status … -
ValueError at /store/place_order/ Cannot assign "<SimpleLazyObject: <User: user>>": "Order.user" must be a "User" instance
I am very new with django, i am trying to build a e-commerce store in django in my django project i have two applications accounts and store i my accounts application my form.py looks like this:- from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): mobile_number = forms.CharField(max_length=15, required=True) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) gender = forms.ChoiceField(choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')], required=True) class Meta(): fields = ('username', 'email', 'date_of_birth', 'gender', 'mobile_number', 'password1', 'password2',) model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' self.fields['mobile_number'].label = 'Mobile Number' self.fields['date_of_birth'].label = 'Date of Birth' self.fields['gender'].label = 'Gender' in accounts/views.py:- from django.shortcuts import render, get_object_or_404 from django.urls import reverse_lazy from . import forms from django.views.generic import CreateView from .forms import UserCreateForm from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.views.generic import TemplateView class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('index') template_name = 'accounts/signup.html' def profile(request): return render(request,'accounts/profile.html',{'username':request.user, 'email':request.user.email, 'first_name':request.user.first_name, 'last_name':request.user.last_name}) class UserCreateView(CreateView): form_class = UserCreateForm success_url = reverse_lazy('index') template_name = 'accounts/signup.html' def form_valid(self, form): response = super().form_valid(form) self.success_url = reverse_lazy('profile', args=[self.object.pk]) return response in my store application models.py looks like this: - from django.db import models import datetime from accounts.models import User import … -
How to implement reuse of a discount code used for a canceled order?
I have a Django project to implement discount codes. The models are as follows: class CouponCode(models.Model): max_usage = models.PositiveSmallIntegerField() max_usage_per_user = models.PositiveSmallIntegerField(default=1) code = CharField(max_length=10, unique=True) discount_percent = models.PositiveSmallIntegerField(default=0, validators=MaxValueValidator(100)]) max_discount_amount = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) minimum_price = models.PositiveBigIntegerField(default=0) class UsedCode(models.Model): customer = models.PositiveBigIntegerField(verbose_name='customer id') coupon = models.ForeignKey(CouponCode, on_delete=models.PROTECT) order_id = models.PositiveIntegerField() @classmethod def has_reached_max_usage_for_user(cls, coupon, user): usages = cls.objects.filter(coupon=coupon, customer=user).count() if usages < coupon.max_usage_per_user: return False return True @classmethod def has_reached_max_usage(cls, coupon): usages = cls.objects.filter(coupon=coupon).count() if usages < coupon.max_usage: return False return True Every time an order is created with a coupon code, a UsedCode object is created. I want to implement a feature where the coupon code can be reused if the order is cancelled. I prefer not to delete the objects so I can track the data. -
Save file (not in MEDIA_ROOT) to Django FileField from fastapi UploadFile
I need to save a fastapi UploadFile object directly to a Django model defined below: class MyFile(models): file = models.FileField(upload_to="files/") In the API, I managed to obtain file object from the SpooledTemporaryFile using the read and write methods like in the block below: async def file_upload(file: UploadFile = File(...)): async with aiofiles.open(f"path/{file.filename}", "wb") as media: cont = await file.read() await media.write(cont) Then I try to convert the new file to FieldFile type in Django to be able to save it in the MyFile.file field but it kept returning a TypeError with the description: write() argument must be str, not generator from django.core.files import File as DjangoFile async def file_upload(file: UploadFile = File(...)): ... async with aiofiles.open(f"path/{file.filename}") as media: d_file = DjangoFile(media) file_model = MyFile() file_model.file.save(file.filename, d_file) file_model.save() return {"ok": True} The stack trace revealed file_model.file.save(file.filename, d_file) as the offending line. >>> type(file.filename) str >>> type(d_file) <class 'django.core.files.base.File'> Could you point me in the right direction? Thanks. -
Running django test, migrations with django.conf import settings are not using DJANGO_SETTINGS_MODULE or --settings override settings
I have a migration which does a check on settings.DEBUG, I've imported settings using from django.conf import settings and if it's False I'm expecting that this is a production(or production-ish) environment so I'm importing a secrets manager secret to use in a createsuperuser migration function, otherwise it's local hosting or local dev and I'm just using a hard coded string. My problem is that in my settings.py I've set DEBUG to false as a safe default, similar to how I set my SECRET_KEY to None so that if for some reason the settings override fails I get an error not the generated SECRET_KEY. Anyway, back from that aside, I'm trying to run ./manage.py test --settings=myproject.test (I have also tried using an export of DJANGO_SETTINGS_MODULE='myproject.test') to load my test.py settings file, at the top of which it does a from .settings import * import and then further down the page I overwrite the setting with DEBUG = True. So in my migration I from django.conf import settings and I'm expecting that to load my DJANGO_SETTINGS_MODULE settings, when I run my tests and it runs my migrations, I'm expecting that from django.conf import settings is going to use my DJANGO_SETTINGS_MODULE settings I … -
"WebSocket connection to 'ws://localhost:8000/ws/chat/cujncvifd/' failed"
I am getting a "WebSocket connection to 'ws://localhost:8000/ws/chat/cujncvifd/' failed" error in my django application. I am also getting a "Not Found: /ws/chat/cujncvifd/" statement in the terminal. The following are the relevant pieces of code from the mentioned files: settings.py: INSTALLED_APPS = [ 'channels', 'common_anime_chat.apps.CommonAnimeChatConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ASGI_APPLICATION = 'anime_chat_app.routing.application' CHANNEL_LAYERS = { 'default':{ "BACKEND":"channels.layers.InMemoryChannelLayer" } } asgi.py: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter import common_anime_chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'anime_chat_app.settings') #the new code about the application you told me to write routing.py (main project directory): from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.security.websocket import AllowedHostsOriginValidator import common_anime_chat.routing application = ProtocolTypeRouter({ 'websocket':AuthMiddlewareStack( URLRouter( common_anime_chat.routing.websocket_urlpatterns ) ), "http":get_asgi_application(), }) routings.py (from common_anime_chat which is an app): from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()) ] consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type':'tester_message', 'tester':'hello world' } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data=json.dumps({ 'tester':tester, })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) common_anime_chat/urls.py: … -
How to get uncleaned CharField data from a form in a django formset?
I would like to get a charField from a form in a django formset without cleaning the data first. Cleaning the data removes the white space and for a particular Charfield I would like to keep the exact input. I have a form inside a formset and get most of the data fields by for form in formset: cd = form.cleaned_data name = cd.get('name') however I do not want to get the CharField by cleaning the data for a particular field. I was attempting to get the field like this for form in formset: name = form['name_of_field'] but it does not work -
How to use pop-up notifications in Django with Bulma?
I am making an app using Django, and I want to implement Bulma alerts, like this: But, I can't figure out how. I need them to inform the user if they filled out a form correctly. Does anyone know how to implement this? -
Cannot display a comment on a blog page - django
I have been trying to create a comment section for a blog site. Comments should only be made by the site's users. I am able to make comments and display them in the comment section from the admin panel, but when the users submit comments they don't display in the webpage. Here are my models.py: class Sight(models.Model): CATEGORY_MAX_LEN = 25 NAME_MAX_LEN = 30 LOCATION_MAX_LEN = 100 IMAGE_UPLOAD_TO_DIR = 'destinations/' name_of_sight = models.CharField( verbose_name='Name of Sight', max_length=NAME_MAX_LEN, unique=True, ) location = models.CharField( verbose_name='Location', max_length=LOCATION_MAX_LEN, ) category = models.ForeignKey( Category, on_delete=models.CASCADE, # choices=CATEGORIES ) description = models.TextField( verbose_name='Description', ) post_date = models.DateTimeField( auto_now_add=True, ) pros = models.TextField( verbose_name='Pros', null=True, blank=True, ) cons = models.TextField( verbose_name='Cons', null=True, blank=True, ) image = models.ImageField( upload_to=IMAGE_UPLOAD_TO_DIR, verbose_name='Image', ) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def __str__(self): return '%s - %s' % (self.name_of_sight, self.user) class SightComment(models.Model): MAX_BODY_LENGTH = 500 sight = models.ForeignKey( Sight, related_name='sight_comments', on_delete=models.CASCADE, blank=True, null=False, ) body = models.TextField() publication_date_and_time = models.DateTimeField( auto_now_add=True, blank=True, null=False, ) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def __str__(self): return '%s - %s' % (self.sight.name_of_sight, self.user) My form.py: class SightCommentForm(forms.ModelForm): class Meta: model = SightComment fields = ('body',) widgets = {'body': forms.Textarea(attrs={'class': 'form-control', 'cols': 30, 'rows': 4})} labels = { … -
ImportError: cannot import name 'Ingredient' from 'inventory.models' (C:\Users\mcarl\OneDrive\Desktop\VirtualEnvs\djangodelights\inventory\models.py)
So I am at a point in my project where I need to create instances of my models inside of the python shell. The problem is when I go to import my Ingredient model (which I've checked probably a hundred times now to find out if it was correct), I get this message - ImportError: cannot import name 'Ingredient' from 'inventory.models' (C:\Users\mcarl\OneDrive\Desktop\VirtualEnvs\djangodelights\inventory\models.py) The file structure is correct and everything.. How are they saying there is no Ingredient when there is a model called Ingredient inside the file..? Any idea how to fix.? Thanks My models.py file: from django.db import models import datetime class Ingredient(models.Model): name = models.CharField(max_length=100) available_quantity = models.DecimalField(max_digits=10, decimal_places=2) price_per_unit = models.DecimalField(max_digits=10, decimal_place=2) class MenuItem(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) class RecipeRequirement(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity_required = models.DecimalField(max_digits=10, decimal_places=2) class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) purchase_date = models.DateTimeField(auto_now_add=True) quantity_purchased = models.DecimalField(max_digits=10, decimal_places=2) total_cost = models.DecimalField(max_digits=10, decimal_place=2) File structure, fixing typos, clearing python cache.. -
Connect django-server which are hosted by railway.app to react-server, also hosted by railway.app
I'm trying to connect my running Django-server to my running react-"server", but I don't know how... I have done the task with my apache-server, but can't manage to do it in railways.app. Any helpful minds out there who can guide me to my goal? -
Using JS to update profile photo
I'm trying to write a Django application where there is a button to change the profile photo and when clicked, a file selection screen appears. After selecting the file, I see the upload successful message, but the new image I selected is not written to the database. I can't pass this step for days. template js code: <script> // JavaScript document.addEventListener("DOMContentLoaded", function () { const uploadButton = document.getElementById("uploadButton"); const fileInput = document.getElementById("fileInput"); uploadButton.addEventListener("click", function () { fileInput.click(); }); fileInput.addEventListener("change", function () { const formData = new FormData(document.getElementById("profileForm")); fetch("{% url 'update_profil_photo' %}", { method: "POST", body: formData, headers: { "X-CSRFToken": '{{ csrf_token }}' } }) .then(response => response.json()) .then(data => { if (data.success) { alert("Sucessfully updated!"); } else { alert("An error occured, please try again."); } }) .catch(error => { alert("an error occured, please try again."); }); }); }); </script> template html: <form method="post" enctype="multipart/form-data" action='{% url "update" %}' id="profileForm"> {% csrf_token %} <button class="btn btn-info" type="button" id="uploadButton"> <i class="fa fa-fw fa-camera"></i> <span>Change Photo</span> </button><input id="fileInput" type="file" style="display: none;"> </div> </div> view: @login_required def update_profil_photo(request): user_profile = get_object_or_404(UserProfile, user=request.user) user = request.user if request.method == 'POST': profile_form = UserProfilePictureUpdateForm(request.POST, request.FILES, instance=user_profile) if profile_form.is_valid(): profile_form.save() messages.success(request, 'Update is successful') return JsonResponse({'success': True}) … -
NGINX not serving django static files after ssl certificate was installed
After building my django app, I got it to work over http. The issue started after installing ssl certificate using certbot. Now, static files are no longer being served. This is my nginx configuration server { server_name pythonyard.com www.pythonyard.com *.pythonyard.com; location /static/ { alias /home/kenechukwu_webapp/allpython/backend/; } location / { proxy_pass http://localhost:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/pythonyard.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/pythonyard.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name pythonyard.com www.pythonyard.com *.pythonyard.com; return 404; # managed by Certbot } I have read through lots of similar problems here on stackoverflow but none has worked for me. Please what could be wrong? This is my first time using it -
how to Filter two models values in query sets
hi I'm Django rest framework in my I want to search filter 2 models at once class SearchViewSet(generics.ListAPIView): queryset = Profile.objects.all() serializer_class = SearchSerializer authentication_classes = [TokenAuthentication] filter_backends = [SearchFilter] search_fields = ["user__username", "caption", "post_text"] def get_queryset(self): search_query = self.request.GET.get("search") queryset = super().get_queryset() if search_query: # Filter the queryset based on the search query queryset = queryset.filter(user__username__icontains=search_query) # Get the related Post objects that match the search query post_queryset = Post.objects.filter( caption__icontains=search_query) | Post.objects.filter( post_text__icontains=search_query) # Get the distinct Profile objects that have related matching Post objects queryset = queryset.filter(posts__in=post_queryset).distinct() return queryset this is my serilizers. py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = "__all__" depth = 1 class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" class SearchSerializer(serializers.Serializer): profile = ProfileSerializer() posts = PostSerializer(many=True) I want to filter results by username as well as post description and post caption but the username belongs to ProfileSerilizers and the post description and post caption belongs to Post Sterilizers how can I achieve this I'm getting this error raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'posts' into field. Choices are: bio, id, id_user, location, profileimg, user, user_id -
S3 image URL to a python string and swap the backslashes
In my Django web app I use a function that takes the web request and goes to get the image URL from an S3 bucket and stores it into a variable. So I have a 2 part question I need to take that variable (which is holding the string) and turn forward slashes into back slashes Ultimately I am trying to verify that AWS has a path that exists, because right now it keeps telling me its false. def testPage(request, pk): photo = Photo.objects.get(id=pk) photo_url = str(photo.image.url) photo_path = str(request.build_absolute_uri()) print(photo_url) # "https://myBucketname.s3.amazonaws.com/Profile_pic_-_Copy.jpg" path_exists = os.path.exists(photo_url) # FALSE print(photo_path) # http://localhost:8000/prediction/68/ path_exists = os.path.exists(photo_path) # FALSE I have tried getting the raw string of the variable. I have tried to apply os.path.normpath() but it removes the double slash from the beginning of the URL. Any help on this would be great -
Django rest_framework serializer throwing an error
in the serializers.py from rest_framework import serializers from .models import Book ,MenuItem class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id','title','author','price'] class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = MenuItem fields = ['id','title','price','inventory'] extra_kwargs = { 'price': {'min_value': 2}, 'inventory':{'min_value':0} } my model class MenuItem(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=6,decimal_places=2) inventory = models.SmallIntegerField Tried to send get request to my view , im facing the issue . Applying littlelemonapi.0002_menuitem... OK (API) rustemaisariyev@MacBook-Pro-Rustem littlelemon % python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 28, 2023 - 16:20:24 Django version 4.2.3, using settings 'littlelemon.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /api/menu-items Traceback (most recent call last): File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() ^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content ^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/renderers.py", line 723, in render context = self.get_context(data, accepted_media_type, renderer_context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/renderers.py", line 654, in get_context raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rustemaisariyev/.local/share/virtualenvs/API-BdtIIPdy/lib/python3.11/site-packages/rest_framework/renderers.py", line 562, in get_raw_data_form data = serializer.data.copy() ^^^^^^^^^^^^^^^ … -
Uncaught ReferenceError: Swal is not defined
Iam using swwetify on Djnago so I set all the parameter on settings , but send me this error Uncaught ReferenceError: Swal is not defined enter image description here Well I set the css and Js on Main Page. have to send me the message -
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 …