Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to specify the fields in drf queryset using drf-yasg
class ABC(generics.ListCreateApiView): @swagger_auto_schema( operation_description="THIS API IS TO CREATE MESSAGES IN A LIST ", auto_schema=AcceptFormDataSchema, request_body=MessageGetSerializer ) def get_queryset(self): data =self.request.GET.get("code") ... @swagger_auto_schema( operation_description="THIS API IS TO CREATE MESSAGES IN A LIST ", request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=["data"], properties={ "code": openapi.Schema(type=openapi.TYPE_STRING), def post(self, request): brand_code = request.data.get("code") ..... #serializer.py class MessageSerializer(serializers.ModelSerializer): class Meta: model = Messages fields = ("message_id", "content", "description") My post method is working fine with the fields which I required using the same serializer but it's not working for the get_queryset method. Can anyone please suggest something on how I will get the fields using drf-yasg? -
Django Form doesn't update when using Jquery signature framework
I'm using Jquery's signature framework in my form page that I wrote with Django. When I use this, it does not update when I make changes in any field in the form. update.py def updateAmbulanceCaseForm(request,id): ambulanceCase = AmbulanceCase.objects.get(id=id) form = AmbulanceCaseForm(data=request.POST, instance=ambulanceCase) if form.is_valid(): form.save() messages.success(request,"Kayit Basarili...") print(form.data) context={'AmbulanceCase':AmbulanceCase.objects.all()} return render(request,"tables/ambulance_case.html", context) else: print("basarisiz") return render(request,"forms/update_forms/ambulance_case.html",{"AmbulanceCase": ambulanceCase}) update.html $(function() { if($('#sigtext')) { var sig = $('#get_sig').signature(); sig.signature('draw', $('#sigtext').val()); sig.signature('disable'); $('#get_sig').signature({disabled:true}); } else{ var sig = $('#get_sig').signature(); } }); <div class="mb-3 col"> <label for="doctor_username" class="form-label">DOKTOR/PARAMEDİK ADI SOYADI</label> <input type="text" class="form-control" id="doctor_username" name="doctor_username" value="{{AmbulanceCase.doctor_username}}"> <div class="container row mb-3 col" style="display: block;"> <label for="doctor_signature" class="form-label">İMZA</label> <div class="container border border-5" id="doctor_signature" > </div> <textarea name="doctor_signaturetext" id="doctor_signaturetext" cols="30" rows="10" style="display: none;">{{AmbulanceCase.doctor_signaturetext}}</textarea> </div> -
group the serialized data according to particular field value (Django rest framework)
models.py class InviteUser(models.Model): invite_id = models.AutoField(primary_key=True) invite_code = models.CharField(max_length=100, unique=True) invite_type = models.CharField(max_length=100) invited_user_role = models.CharField(max_length=100) invited_user = models.ForeignKey('users.User', on_delete=models.CASCADE, db_column='invited_user') number_of_invites = models.PositiveIntegerField(null=True, blank=True) invite_expiry_date = models.CharField(max_length=100, null=True, blank=True) remaining_invites = models.PositiveIntegerField(null=True, blank=True) phone_number = models.CharField(max_length=15, null=True, blank=True) veiws.py class GetAllInvitesCreatedByOneUser(generics.RetrieveAPIView): def get(self, request, *args, **kwargs): user_id = self.kwargs['user_id'] user_invite_instance = InviteUser.objects.filter(Q(invited_user=user_id) & (Q(invite_type='MEMBER') | Q(invite_type='SELLER'))) serializer = GetAllInvitesCreatedByOneUserSerializer(user_invite_instance, many=True) return Response({"message": "success", "invited_user": user_id, "data": serializer.data}, status=status.HTTP_200_OK) serializers.py class GetAllInvitesCreatedByOneUserSerializer(serializers.ModelSerializer): class Meta: model = InviteUser fields = ['invite_code', 'invite_type', 'phone_number'] Above code gives result: { "message": "success", "invited_user": 77, "data": [ { "invite_code": "M-ASWA-6721", "invite_type": "MEMBER", "phone_number": "9387907555" }, { "invite_code": "M-ASWA-3289", "invite_type": "MEMBER", "phone_number": "9999907772" }, { "invite_code": "S-ASWA-6411", "invite_type": "SELLER", "phone_number": "8099907772" } ] } I want this to be grouped by invite_type field: "message": "success", "invited_user": 77, "data": [ { "MEMBER": [ { "invite_code": "M-ASWA-6721", "invite_type": "MEMBER", "phone_number": "9387907997" }, { "invite_code": "M-ASWA-3289", "invite_type": "MEMBER", "phone_number": "9999907772" } ], "SELLER": [ { "invite_code": "S-ASWA-6411", "invite_type": "SELLER", "phone_number": "8099907772" } ] } ] } -
Make django app aware of local network IP camera
I have a django app running in a server, it can access the users usb and integrated cameras and show the live feed in the html, but now I need to access the users local IP cameras (connected directly to the Ethernet port in the PC), if possible I would like to achieve this without installing 3rd party software but any solution is valid, is this possible at all? I can access the cameras locally using python but I can't find a way to make the Django app aware of the users local IP cameras. The cameras are type GigE and I am using pylon to access them locally -
i want send emails by filtering datas from django table to multiple reciepent
i am just creating a recruitment app in django.So i want send scheduled mails to companies Hr after they adding vacancies.The datas are the student skill,email,name, from student table. Total 3 models student , vacancy, company. -
Django interaction between two projects deployed in azure in two different ports
In django I am having two projects project1 will take care of user registration, login, authentication(token based authentication) and project 2 have one application running in it. Now my problem is for project2 I am unable to provid security if someone know the url anyone can use for free. In project1 by using some code i am sending request to project2 and returning response Now i need an approach to protect project2 from unauthorised usage(for security reasons) Note: I can't club both as a single project(for some reason) -
Pandas read_csv function to handle both utf-8 and utf-16 issue
User can upload both UTF-8 and UTF-16 CSV file which is the attendance file of Microsoft teams that they download from there. To handle the case I have written the following code but there is some strange issue that I am not able to fix. excel_file = request.FILES['excel-file'] try: print('try case') df = pd.read_csv(excel_file) csv_type = 'a' print(df) except UnicodeDecodeError: print('except case') from io import BytesIO df = pd.read_csv(BytesIO(excel_file.read().decode('UTF-16').encode('UTF-8')), sep='\\') csv_type = 'b' print(df) except Exception as e: print("Incorrect CSV file format", e) Here first 'try case' handle the UTF-8 and 'except case' handle the UTF-16 CSV file. Both case work fine if I run them separately, But when I put them in try except block then the code fails. Here in the above code UTF-8 case works but UTF-16 gives No columns to parse from file error. Now if I move the except code to try then UTF-16 will work but it will also run for UTF-8 giving wrong data. So how can I handle this case haven't found any way to get file encoding also. -
Docker Django services not communicating
I am trying to get my listener service to POST at an API in the app service. The app service is running at 0.0.0.0:8000 and the listener service is trying to post at this address but the data isn't getting added to the db. I am not sure if I have configured this correctly, help would be much appreciated. docker-compose.yml services: db: image: postgres:13.4 env_file: - ./docker/env.db ports: - 5432:5432 volumes: - db_data:/var/lib/postgresql/data app: build: context: . dockerfile: ./docker/Dockerfile env_file: - ./docker/env.db - ./.env volumes: - .:/opt/code ports: - 8000:8000 - 3000:3000 depends_on: - db command: bash ./scripts/runserver.sh listener: image: scooprank_app env_file: - ./.env container_name: listener command: npm run listen depends_on: - app restart: always -
Django with Aws Application load balancer
What is the deployment flow to achieve load balancing using multiple Ec-2 instances? do I have to configure my project with both ec2 manually first and then use them with the App Load balancer? -
Key Error while trying to register user Django
Imm getting a key error "password" on serializer.py while validating the data. Imm using Django's built in User model and Token Authentication to register a user. here's how my serializer.py looks like. from django.contrib.auth.models import User from rest_framework import serializers class RegistrationSerializer(serializers.Serializer): password2 = serializers.CharField(style={"input_type" : "password"}, write_only=True) class Meta: model = User fields = ["username", "email", "password", "password2"] extra_kwarg = { "password": { "write_only": True, } } def validate(self, data): if data["password"] != data["password2"]: return serializers.ValidationError("Your password must be same!") if data.objects.filter(email=data["email"]).exists(): return serializers.ValidationError("This Email is already registered!") return data views.py from rest_framework.response import Response from user_app.api.serializer import RegistrationSerializer from rest_framework.decorators import api_view @api_view(["POST",]) def register_user(request): if request.method == "POST": serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return serializer.error_messages()``` Errors serializer.py", line 22, in validate if data["password"] != data["password2"]: KeyError: 'password' -
Can't import models in Python shell
I'm doing the Django official tutorial (documentation). I've created two database models (Question, Choice). I'm trying to import them by first entering the python shell by using python manage.py shell Then I run from polls.models import Question,Choice and nothing happens, it just enters an empty line. In the documentation, it's showed that I'm supposed to see some information regarding the database. I've done the migration and also put the app config in settings.py -
why it is not displaying slug field on the address bar?
I am new to Django. I encountered an error while practicing on the slug field adding to the model. it is not working after I run the program. The browser is not displaying any error. I have written the code below please have a look and anybody help me out? feel free to ask me if you have any questions. Thank you for your help. models.py from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify import string,random from temp1.util import unique_slug_generator STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) class Post(models.Model): title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, null = True, blank = True) text = models.TextField() published_at = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft') class Meta: ordering = ('-published_at', ) def __str__(self): return self.title @receiver(pre_save, sender=Post) def pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) urls.py from django.urls import path from .views import detail urlpatterns = [ path("posts/",detail,name="home") ] util.py import string, random from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits): return … -
home.html isn't displaying tags
The tags aren't showing in the home page. but it appears in post_detail.html. Its not working as I want it to work. Can anyone fill me up with mistakes here and solutions? blog/views.py: def home(request, tag_slug=None): posts = Post.objects.all() # tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) context={ 'posts': posts, #introduces the content added in Post Class 'tag':tag, } return render(request, 'blog/home.html', context) class PostListView(ListView): model=Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name= 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model=Post blog/urls.py: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('tag/<slug:tag_slug>/',views.home, name='post_tag'), templates/blog/base.html <div class="col-md-4"> <div class="content-section"> <h3>Sidebar</h3> <p class='text-muted'>Informations <ul class="list-group"> <li class="list-group-item list-group-item-light" style="text-align:center"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}">{{tag.name}}</a> {% endfor %} </div> </div> </li> </ul> -
Django Class Based View (FormView)
class ReviewView(FormView): form_class = ReviewForm template_name = "review/review.html" success_url = "/thank-you" def form_valid(self, form): form.save() return super().form_valid(form) this is the error how can I fix it AttributeError at / 'ReviewForm' object has no attribute 'save' -
Dynamic Dropdown values django
I want to create a dropdown Course of Trainee where only options of values in CourseName of Course model would be shown. Currently I have tried some soulutions after browsing. But its not working. My course dropdown disappeared after editing in forms.py. If i remove this line Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}), choices=course_obj.get_course_name(), label='Course :') Then the dropdown would show but with no options model.py class Course(models.Model): CourseID = models.AutoField(primary_key=True) CourseName = models.CharField(max_length=20) class Meta(): db_table = "Courses" def get_course_name(self): return self.CourseName class Trainee(models.Model): Name = models.CharField(max_length=50) Course = models.CharField(max_length=40) class Meta(): db_table = "Trainee" forms.py class TraineeForm(forms.ModelForm): course_obj = Course() Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :') Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}), choices=course_obj.get_course_name(), label='Course :') ........................ edit.html <form method="post" class="form-group" type="multipart/form-data"> {%csrf_token%} {% for Name in form.Name %} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Name.label }}</label> {{ Name }} </div> {% endfor %} {% for Course in form.Course %} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Course.label }}</label> {{ form.Course }} </div> {% endfor %} The Page appears like this -
django summernote how to limit the number of images or total image size
I'm touching a Django summernote. But there's a problem. I can limit the size of one image, but how do I set the total number of images per post or the total image size? plaese help me -
How to avoid 'callback' error page in django-allauth( GoogleAuth)?
I am developing some django app and implemented authentication via Google. Everything works fine, but if user logins via Google, goes back to Google-login page with browser`s 'previous page' button, hi might login again and see this error page: Page I don`t want users to see that. How can I avoid this 'error' page? -
How can I serve staticfiles in Django in Railway app when Debug is False
When I set DEBUG to False on Railway's variables my images from uploads are not loading. How can I fix that? my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / "uploads" MEDIA_URL = "/uploads/" my urls.py has + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and I used python manage.py collectstatic -
The terminal gives me as error a path that I don't have in my code with Django
I'm working on Django, developing a site This gives me an error: Not Found: /plans/investment_per_plan_chart Not Found: /plans/active_running_plans I have searched with VSC but I can't find anything in my code that looks like this error. Please help me I'm lost -
Why is my Django FormModel is not submitted when I click submit button?
I am working on simple login and signup pages on Django. This is how they work: You create an account in the signup page. After the process is complete, it redirects you to the login page. However, when you click a button to submit information on the signup page, it is not submitted. Here are the codes: urls.py from django.urls import path, include from . import views urlpatterns = [ path('account/login', views.login_page, name='login'), path('account/signup', views.signup_page, name='signup') ] models.py from django.db import models class User(models.Model): username = models.CharField(max_length=30,) password = models.CharField(max_length=255) firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) emailAddress = models.EmailField(max_length=255) def __str__(self): return self.username forms.py from .models import User from django.forms import ModelForm, TextInput, PasswordInput, EmailInput class UserForm(ModelForm): class Meta: model = User fields = ['username', 'password', 'firstName', 'lastName', 'emailAddress'] widgets = { 'username': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'Username' }), 'password': PasswordInput(attrs={ 'class': 'signup_input', 'placeholder': 'Password' }), 'firstName': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'First Name' }), 'lastName': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'Last Name' }), 'emailAddress': EmailInput(attrs={ 'class': 'signup_input', 'placeholder': 'Email Address' }) } labels = { 'username': '', 'password': '', 'firstName': '', 'lastName': '', 'emailAddress': '' } views.py from django.shortcuts import render, redirect from .forms import UserForm def login_page(request): return render(request, 'Account/login_page.html') … -
Firebase Cloud Messaging not working for programmatically sent messages using Python
If I go into my firebase console and setup a campaign my end devices receive the notification just fine, but for messages to specific devices using the device's registration token, sent from django/python, I get no notification on my mobile devices. Not sure if this matters but my app is still in development, it is not in production, so if this matters please let me know. My frontend is flutter, here is the flutter code I am using to get the registration token and send it to the backend: Future<StreamedResponse> AddProductPut(context, pk, name, quantity, cost, selling, XFile? chosenImage) async { String id_token = await FirebaseAuth.instance.currentUser!.getIdToken(); late String? fcm_token; await FirebaseMessaging.instance.getToken().then((token) async { fcm_token = token!; }).catchError((e) { print(e); }); print(fcm_token); var url = backend + "/pm/createproduct/" + pk.toString() + "/"; var request = http.MultipartRequest('PUT', Uri.parse(url)); print("FCM TOKEN"); print(fcm_token); request.headers["Authorization"] = "Token " + id_token; request.fields["name"] = name; request.fields["quantity"] = quantity.toString(); request.fields["cost_price"] = cost.toString(); request.fields["selling_price"] = selling.toString(); request.fields["barcode"] = "11111"; request.fields["token"] = fcm_token!; request.files.add( await http.MultipartFile.fromPath( 'image', chosenImage!.path ) ); return await request.send(); } Here is the python code in my django serializer to send the notification message: registration_token = self.context['request'].data["token"], print(registration_token[0]) print(type(registration_token[0])) # See documentation on defining a message payload. … -
change text content (like, unlike) Django Like Button
I'm asked to work on a networking website that is like Twitter. I work with HTML,CSS, Javascript for the client-side and Django for the server-side. I created a model that saves the likes by saving the liked post and the user that liked the post. I want to make a like button in the HTML page that has its inner text(like) if the user hasn't liked the post and unlike if the user liked the button by using arrays in models.py: class likes(models.Model): liked_post = models.ForeignKey("posts", on_delete=models.CASCADE) like_user = models.ForeignKey("User", on_delete=models.CASCADE) in views.py: def index(request): allposts = posts.objects.all() m = ['empty'] aa = [0] for post in allposts: postid = post.id print(postid) aa.append(int(postid)) liked__post = posts.objects.get(id = postid).id if likes.objects.filter(like_user = request.user, liked_post = liked__post).exists(): f = 'unlike' m.append(f) c = 'liked__btn' else: t = 'like' m.append(t) c = 'like__btn' print('like') print(m[0]) print(aa) return render(request, "network/index.html",{"allposts": allposts, 'm':m, 'c':c, 'aa':aa}) @csrf_exempt def like(request, post_id): liked__post = posts.objects.get(id = post_id) if request.method == 'PUT': print('we\'ve hit put') data = json.loads(request.body) if data.get('like') is not None: print('in like') # Note: [User Obj Itself] # follower = request.user (is: <User Obj>) # following = x (is: <User Obj>) likes.objects.create(liked_post=liked__post, like_user=request.user) elif data.get('unlike') is … -
Django block user from modifying a form input
I have a instance Form that is showing the user his Profile Data, the user can update some of his profile settings by modifying the input and clicking the update button. But I don't want the user to be allowed to change all the profile data, such as the subscriptions Charfields. How can I do that? models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) telegramusername = models.CharField(max_length=50, default=None) subscription = models.CharField(max_length=50, default=None) numberofaccount = models.CharField(max_length=50, default=None) def __str__(self): return self.telegramusername forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile labels = { "telegramusername": "Telegram Username", "subscription": "Subscription Plan", "numberofaccount": "Number of MT5 Account" } fields = ["telegramusername", "subscription", "numberofaccount"] views.py def dashboard(request): profile_data = Profile.objects.get(user=request.user) profile_form = ProfileForm(request.POST or None, instance=profile_data) if profile_form.is_valid(): print("worked") profile_form.save() context = { 'profile_form': profile_form } return render(request, "main/dashboard.html", context) -
Choice_set and id members are unknown
I'm getting started with django, I've been following the official tutorial and I've run into an issue. I have this block of code: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST["choice"]) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render( request, "polls/detail.html", { "question": question, "error_message": "You didn't select a choice.", }, ) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) The code works perfectly fine, however, for some reason VS Code highlights the ID and CHOICE_SET attributes. Here's my models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def __str__(self) -> str: return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self) -> str: return self.choice_text I suppose that there's an issue with VS Code because as I said the code works just fine and I can run it. I just really wanna remove the red highlighting and fix it. -
Debugger does not start in VSCode for Django
I'm trying to debug my Django project, but whenever I hit the play button on the run and debug window in VSCode, it thinks for a second, and then completely stops. My project runs completely fine when I run it with the "runserver" command. I've tried restarting VSCode, and restarting my computer. here is my launch.json file { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver", "9000" ], "django": true } ] }