Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to run Vue.js 3 along with django code
I'm unable to load Vue.js 3 in my django code. I used Vue from the CDN. Vue import: <script src="https://unpkg.com/vue@next"></script> Html: <div class="row"> <div class="col-md-24"> Here: [[ message ]] </div> </div> JS: console.log(`Vue code inserted`); const app = Vue.createApp({ delimiters: ["[[", "]]"], data() { return { message: "Hello Vue!", }; }, computed: {}, methods: {}, }); app.mount("#todaysappts"); JS console output: You are running a development build of Vue. Make sure to use the production build (*.prod.js) when deploying for production. Vue code inserted Html output: <div class="row"> <div class="col-md-24"> Here: [[ message ]] </div> </div> So, my variable message is not getting interpolated, and the variable name is being printed, with the brackets. How I do it solve this? Apparently vue is loaded, and there are no errors. -
Not recognizing the import module in Django application
File "C:\Users\User\projects\Datascience\Bee_Word_Project\spellbee\views.py", line 4, in from . import beewordpick File "C:\Users\User\projects\Datascience\Bee_Word_Project\spellbee\beewordpick.py", line 4, in import pyttsx3 ModuleNotFoundError: No module named 'pyttsx3' Actually the above pyttsx3 module is pip installed. Django not identifying env PATH in their search list. It searches the module in the local application path only. Can anyone recommend how to setup search for the import modules in Django. what has to be done at settings.py ?when I run the same module using FLASK application , I can able to run that application -
Adding ManyToMany field data between models
I know similar questions have been asked before, but I haven't been able to find a clear answer so any help will be greatly appreciated:) I want to add a predefined list of objects from one model to another using ManyToMany field. However, I am not sure the best practices or how exactly to accomplish this. For example: #models.py class Book(models.Model): BOOKS = ( ('b1','Secret Life of Bees'), ('b2','Pride and Prejudice') ) name = models.CharField(max_length=100, choices=BOOKS) def __str__(self): return self.name class Library(models.Model): librarian = models.OneToOneField(UserProfile, on_delete=models.CASCADE, primary_key=True) books = models.ManyToManyField(Book) #views.py def create_library(request): if request.method == 'POST': form = LibraryCreateForm(request.POST) if form.is_valid(): library = form.save(commit=False) listOfBooks = request.POST.getlist('books') library.save() return redirect('home') else: form = LibraryCreateForm() return render(request, 'create_library.html', {'form':form}) #forms.py class LibraryCreateForm(forms.ModelForm): class Meta: model = Library fields = ['books'] #create_library.html <form method="POST"> {% csrf_token %} <input type="checkbox" value="b1" name="books"> <input type="checkbox" value="b2" name="books"> </form> This isn't working for me, and I don't know how to fix it correctly. To be more specific, I would like to essentially do the equivalent of this in python but with DJango: class Person: def __init__(self, name): self.name = name self.skills = [] class Skill: def __init__(self, name): self.name = name programmingSkillOne = Skill("C++") … -
Django Views, I have a below scenario, I have one question model and Answer model
I have a below scenario, I have one question model and Answer model, in which question is a foreign key inside the answer model. Now i want to add an answer to a particular question. Here i have made the crud of the question using the generic views, But i am not able to add the Answer for a particular question, could you please suggest how should i add a answer to the question. class AnswerCreateView(CreateView): model = Answer fields = ["answer"] success_url = "/" i have written this but here how i will send the question id, because answer should be added to a particular question -
Django - Class Based View trouble
can anyone tell me how combine detailview with list view and show info in the same template, i'll explain you, i'm learning Django and i am trying to create a Questions and Answer web app, and i need to show the question with all its awnsers -
How to assign additional keys to a set of objects
I am using a Detail View generic and I am trying to add an attribute to each item for a group of Comments (The detail view is for a Post that has many comments). I am trying to loop through the group of comments and assign a boolean to a new attribute is_liked_by_user. When I try to print comment.is_liked_by_user it will show in the scope of it but when I try to find it in the context['post'] I get this error *** AttributeError: 'Comment' object has no attribute 'is_liked_by_user'. What is the correct way to assign this attribute so that it can be passed to my template? class DetailView(LoginRequiredMixin,generic.DetailView): model = Post template_name = 'posts/detail.html' form_class = CommentsForm def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super(DetailView, self).get_context_data(**kwargs) # Create any data and add it to the context context['form'] = self.form_class post = context['post'] comments = post.comment_set.all() for i, comment in enumerate(comments): comment.is_liked_by_user = check_existing_dictionary_in_list(comment.reactions.all(), "user", self.request.user) print("Was comment liked by user?", comment.is_liked_by_user, comment.comment_body) # comment.is_liked_by_user = check_existing_dictionary_in_list(comment.reactions.all(), "user", self.request.user) # context['is_liked_by_user'] = check_existing_dictionary_in_list(post.reactions.all(), "user", self.request.user) pdb.set_trace() return context -
Custo kwarg django rest framework
Today I have 2 urls router.register(r'question_type', QuestionTypeViewSet) router.register(r'question', QuestionViewSet) But I need something like this router.register(r'question_type', QuestionTypeViewSet) router.register(r'question_type/question_type_pk/question', QuestionViewSet) Someone can help me? How to get this kwarg? -
PasswordResetConfirmView's PASSWORD_RESET_TIMEOUT Message if expired
Good day SO. How to add message if PASSWORD_RESET_TIMEOUT is expired? I am using the django.contrib.auth PasswordResetView to get url link with token for Password Reset. Based on docs, I can add PASSWORD_RESET_TIMEOUT like this: PASSWORD_RESET_TIMEOUT = 10 10 seconds just to test. After 10 seconds pass, I tried to to refresh the page and user can still use the URL to access the PasswordResetConfirmView but can no longer change the password. Even using mismatched password, no response. How should I proceed with this? For reference, this is my URL: path('reset_password/', views.MyPasswordResetView.as_view( template_name="../templates/logauth/reset_password.html", subject_template_name='../templates/logauth/password_reset_subject.txt', email_template_name='../templates/logauth/password_reset_email.html', html_email_template_name='../templates/logauth/password_reset_email.html', from_email=settings.EMAIL_HOST_USER,), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="../templates/logauth/reset_password_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="../templates/logauth/reset_password_2.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="../templates/logauth/reset_password_complete.html"), name="password_reset_complete"), Form to alter my PasswordResetView: class MyPasswordResetForm(PasswordResetForm): username = forms.CharField(max_length=254) field_order = ['username', 'email'] def __init__(self, *args, **kwargs): super(MyPasswordResetForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'user-input-form'} View: class MyPasswordResetView(PasswordResetView): form_class = MyPasswordResetForm def form_valid(self, form): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email', '').lower() try: user = get_user_model().objects.get(username=username, email=email) except(get_user_model().DoesNotExist): user = None if user is None: return redirect('password_reset_done') return super().form_valid(form) -
What i'm missing for use Django with Ajax
i want to automatic update a string/field of a simple webpage. The field is the latest date, which i get from this function: def get_latest_date2(): now = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=20) now_string = now.isoformat() return str(now_string[:-14]) + '0Z' So, when i run my django project the time appears on the webpage, but it does not update itself (which is totally normal). So i tried to use ajax to automatic refresh the time, but i'm not getting it from myself. I still don't understand how to make the js script update the time field automatically without a manual update (F5). Here my codes, and something things that i tried. forms.py from .models import Book class TimeForm(forms.ModelForm): class Meta: model = ExactTime fields = ('time') models.py from django.db import models # Create your models here. class ExactTime(models.Model): time = models.CharField(max_length=255) views.py from django.http import HttpResponse from . import API_LOL_txt def updatetime(request): response_dic={} form_template='dashboard/dashboard-home.html' if request.method == 'POST': time = TimeForm(request.POST) response_dic['time'] = time return render(request,'dashboard/dashboard-home.html', response_dic) response_dic['time'] = API_LOL_txt.get_latest_date2() return render(request,'dashboard/dashboard-home.html', response_dic) base.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <title>API LOL</title> </head> <body> {% block content %} {% endblock %} … -
Get DB query result from Django Celery task
I have one django function that takes long time to get query result from db. So I need to run this function in background meanwhile server manage the other functions. After googling, I tried to use Celery, but I couldn't get the result from celery task. Is there any way to get the result from celery task? If not, what is the best answer for this question? -
Django user profile style auth with Djoser
I'm trying to implement authentication with djoser. Since I haven't extended my AbstractBaseUser from Django at start of my project I decided to use a one-to-one profile relation pattern. I have a seperated user app and Here are my related codes: # models.py (user and profile models) from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User as BaseUser class User(BaseUser): @property def mobile_number(self): return self.profile.mobile_number class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") mobile_number = models.CharField(max_length=11, unique=True) def __str__(self): return self.user.username # settings.py (djoser settings) ... DJOSER = { "SERIALIZERS":{ "user": "user.serializers.UserSerializer" "current_user": "user.serializers.UserSerializer" "user_create": "user.serializers.UserCreateSerializer" } ... } ... # user.serializers.py from rest_framework import serializers from .models import UserProfile from .models import User from djoser.serializers import UserCreateSerializer as BaseUserCreateSerializer from djoser.serializers import UserSerializer as BaseUserSerializer class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile exclude = ["user"] class UserSerializer(serializers.ModelSerializer): mobile_number = serializers.CharField(required=True, allow_blank=False) class Meta: model = User fields = ["username", "email", "first_name", "last_name", "mobile_number"] class UserCreateSerializer(BaseUserCreateSerializer): mobile_number = serializers.CharField(required=True, allow_blank=False) class Meta(BaseUserCreateSerializer.Meta): fields = ["username", "email", "first_name", "last_name", "mobile_number"] def create(self, validated_data): mobile_number = validated_data.pop("mobile_number") user = super.create(**validated_data) UserProfile.objects.create(user=user, mobile_number=mobile_number) return user What I'm trying to do here is Skip migrations with adding … -
is it possible to add method in views django ,to be used in a class views that returns the method return string in a httpresponse
def shutdown(device): s=device.shutdown() #bool return s class maintain(): def get(self,request): device=request.GET['device'] ok=shutdown(device) return Httpresponse(ok,content_type='text/plain') -
How to make the category itself in the Parent Category and not just the id
I'm using Django Rest Framework for API and I wrote the model Category in which I have parent and I'm using it like this: parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) In API it looks like this: { "id": 7, "name": "softwares", "img": "", "parent": 1 }, { "id": 8, "name": "databases", "img": "", "parent": 1 }, { "id": 9, "name": "appearance", "img": "", "parent": 2 }, { "id": 10, "name": "media", "img": "", "parent": 2 }, { "id": 11, "name": "system", "img": "", "parent": 2 }, How can I make the category itself and not just the id? -
Django REST api returning only 1st value
i was creating a react and django based ecomm site but there is some bug that i cant find out. this is my product dictionary product.py english is not my 1st language so sorry for bad English . view.py from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .products import products @api_view(['GET']) def getRoutes(request): routes = [ '/api/products', '/api/products/create/', '/api/products/upload/', '/api/products/<id>/reviews/', '/api/products/top/', '/api/products/<id>', '/api/products/delete/<id>/', '/api/products/<update>/<id>', ] return Response(routes) @api_view(['GET']) def getProducts(request): return Response(products) @api_view(['GET']) def getProduct(request, pk): product = None for i in products: if i['_id'] == pk: product = i break return Response(product) -
chatterbot.chatterbot.ChatBot.ChatBotException: Either a statement object or a "text" keyword argument is required. Neither was provided
so i've been stuck on this for 2 days and i still didn't figured it out, i'm implementing a chatterbot inside my Django project and since there's few documentations for this i didn't find any solution for this issue. To be able to integrate it inside my project i had to downgrade python's version to become 3.7. my views.py is the following: from django.shortcuts import render from . import chatbot from chatterbot.logic import LogicAdapter from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from chatterbot.conversation import Statement from chatterbot.trainers import ChatterBotCorpusTrainer def index(request): return render(request, "finalTest/index.html") def give_response(request): userText = request.POST.get('msg') print(userText) response = chatbot.get_response(userText) print(response) return response # Creating ChatBot Instance chatbot = ChatBot('Mason') # Training with Personal Ques & Ans conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." ] trainer = ListTrainer(chatbot) trainer.train(conversation) # Training with English Corpus Data trainer_corpus = ChatterBotCorpusTrainer(chatbot) trainer_corpus.train( 'chatterbot.corpus.english' ) The input inside my index.html is: <main class="msger-chat"> <div class="msg left-msg"> <div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/327/327779.svg)"></div> <div class="msg-bubble"> <div class="msg-info"> <div class="msg-info-name">CoronaBot</div> <div class="msg-info-time">12:45</div> </div> <div class="msg-text"> Hi, welcome my name is Mason. 😄 </div> </div> </div> </main> <form class="msger-inputarea"> <input … -
Lookup to Profile via username in Django
I currently have the setup below, which allows me to extract the profile details for a given pk in the Profile table. You will see that I have extracted the username from the User model in the serializer, to display in the view. I am trying to modify the code to extract the profile for a given username, but changing 'pk' to 'username' and using a lookup field doesn't work. I think this is because I'm trying to do it backwards. Should I therefore create a UserSerializer that accepts the username and then link it to the ProfileSerializer via the 'user' field (this is the one-to-one link to the pk of the User model)? I am not sure how to do that. urls.py urlpatterns = [ path(r'api/profile/<pk>/', views.ProfileView.as_view()), ] serializers.py class ProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username', read_only=True) class Meta: model = Profile fields = ('user', 'gender', 'dob', 'username') lookup_field = 'username' views.py class ProfileView(RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer -
Lookup entries that depend on ManyToMany Field w/ > 10 entries
I want to query all events that have more than 10 attendee entries. Do you have advice how to achieve that? events = Event.objects.filter(attendees__count > 10) class Attendance(HashidModel, TimeStampedModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="attendances" ) event = models.ForeignKey( Event, on_delete=models.CASCADE, related_name="attendances" ) [...] class Event(HashidModel, TimeStampedModel): attendees = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="events_attending", through="Attendance", ) [...] -
Django REST: Can't get url to work with APIView "detail": "Method \"GET\" not allowed."
I'm trying to add a function which deletes every course with a certain category id (cat_id). My usage would be as follows: http://....:8000/course-delete/?cat_id=9 This was my idea, but I'm getting the following error: "detail": "Method \"GET\" not allowed." url path('course-delete/', CourseDelete.as_view(), name='test') view class CourseDelete(APIView): queryset = Course.objects.all() def delete(self, request): cat_id = request.query_params['cat_id'] queryset = Course.objects.filter(category=cat_id) queryset.delete() return Response(serializer.data) -
Is Django Rest Framework Authentication Enough?
So I am very new to the topic authentication. I am using Python Django REST Framework to build my REST API and Python Django Channels for a chat. Now I have to build the login, sign in, and so on. Now I just searched, what kind of authentication is good but I have no clue, what I should do. I saw OAuth and JsonWebTokens but it is a big topic. Than I saw Django Rest Framework does have a authentication which I could use. Is it secure? What is OAuth? Can anbody help me? :) I want a sign in system where I enter my email, password, name, and so on and than get a email. Is there a difference if I want to implement this? It also should be secure like Facebook or Instagram EDIT It shouldn't be a complex sign in where I could Sign in Using Facebook or Google. Just a "simple" sign in/authentication system :) Thanks for your efforts -
Django. How to send data to request.POST via Ajax
i am new in JS and Ajax. I have page for administering football game. It has stopwatch and it is why i need to use Ajax for actions (new goal / new penalty / delete action), bcs standard POST processing will redirect to different page or refresh this page, and i will lose stopwatch. Adding a new actions happens in the same page. Request.POST will have info about clicked button (for +goal / +penalty / delete some action), period time and game numbers of players for action. (In examples simplified to the only 'A_goal_time_minute'). In views.py i print type of post: just post or post from ajax. In both variants of html nothing is displayed. If i paste method='post' in form, ajax will be bypassed (as I understand). If i remove onsubmit='doAjaxSubmit() nothing will change. What should i fix to make this work??? views.py class ZipView(TemplateView): template_name = "dev_zip.html" def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): print("POST") if request.is_ajax(): print('POST is_ajax') print(request.POST) """ Code for new goal or penalty. """ else: print('POST') print(request.POST) return HttpResponseRedirect(request.path) Var 1: This variant redirect to same page with ...?csrfmiddleware=...&A_goal_time_minute=1&A_goal_time_second=0& and others variables. And in console this displayed with tag GET: … -
How to add "FloatFilter" with django-filter
I have a float field in my model with Django 2.2. How can I add a filter with django-filter on this field? Or a float range filter would be even better. Would be also ok if I have to change the field to a Decimal. Thanks! -
javascript file not found in django template
I've added these two lines at the end of settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') BASE_DIR: BASE_DIR = Path(__file__).resolve().parent.parent I've added 'static/my_app/js.js' file to my app and added this code at the beginning of my template: {% load static %} ... <head> <script src={% static 'my_app/js.js' %}></script> </head> now when I run the server and check the console in my_template, here's the error: GET http://127.0.0.1:8000/static/my_app/js.js net::ERR_ABORTED 404 (Not Found) in some similar questions it was suggested to change 'load static' to 'load staticfiles' but in that case i'll get this error: TemplateSyntaxError 'staticfiles' is not a registered tag library. -
passwords are not saved in encrypted form in the database (in my case postgresql)
when I create a user by register form I can't login, but if I create a user from 'Django' admin panel it works properly -
Order infinite scroll posts in django
I experience hard time trying to implement infinite scrolling feature :(. The problem is that it orders posts in the wrong way. For example, if I have posts 1 2 3 4 it orders them in the following order: 1 3 4 2. It's very strange and I have no clue why it is so. Here's my view finction: class index(ListView): model = Post template_name = "index.html" context_object_name = 'posts' paginate_by = 2 ordering = ['pub_date'] Template: <div class="infinite-container"> <div class="infinite-item" style="height: 50vh;"> {{ post.author.first_name }} {{ post.description }} </div> </div> {% endfor %} {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}" class="infinite-more-link"></a> {% endif %} <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', }); </script> -
Dockerfile for .sqlite3 database
I currently have a Django application I want to deploy. The database being used is SQLite3 and I would like to run it in a separate container as the web application. I need to create a docker image of the Database and push it to my repo on AWS ECR. I already have an image of the application there but need a seperate image of the database so the data will persist. Any advice on creating a DockerFile or docker-compose file to do this would be great.