Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Try and except for Query set
I want to do something similar to try and except for single object .. in my situation I got a Query set and I want to do something like : try: qs = model.objects.filter(id=1) except qs.DoesNotExist: raise Http_404() How can I do that ? -
Send an email if to a user registering in django when admin changes their account to is_active=True status
I am creating a register and login system in a project whereby on registering a users default is is_active=False. The admin then receives an email on user registering to approve or leave it inactive. on changing users status to is_active=True, the user should receive an email informing them they can now login.But i am not receiving any emails..or emails being sent, is there an error in my codes am failing to see?? Here is my signals.py from .models import AuthUser from django.db.models import signals from django.db import models from django.dispatch import receiver from django.db.models.signals import pre_save, post_save from django.conf import settings from django.core.mail import send_mail #signal used for is_active=False to is_active=True @receiver(pre_save, sender=AuthUser, dispatch_uid='active') def active(sender, instance, **kwargs): if instance.is_active and AuthUser.objects.filter(pk=instance.pk, is_active=False).exists(): subject = 'Active account' message = '%s your account is now active' %(instance.username) from_email = settings.EMAIL_HOST_USER send_mail(subject, message, from_email, [instance.email], fail_silently=False) #signal to send an email to the admin when a user creates a new account @receiver(post_save, sender=AuthUser, dispatch_uid='register') def register(sender, instance, **kwargs): if kwargs.get('created', False): subject = 'Verificatión of the %s account' %(instance.username) message = 'here goes your message to the admin' from_email = settings.EMAIL_HOST_USER send_mail(subject, message, from_email, [from_email], fail_silently=False) -
How do I get my Django AllAuth Templates to work?
I have put them in what I believe is the correct folder and followed all steps from the tutorial (https://www.youtube.com/watch?v=Rpi0Ne1nMdk&list=PLPSM8rIid1a3TkwEmHyDALNuHhqiUiU5A&index=2) but the templates do not appear to be being picked up. Could anyone help? My repository is https://github.com/Westsi/thynkr_python. I am using allauth. -
same user Sending multiple post api request at same time and we are trying to add new data with old data in database
But some how the there is no consistency in output. some time you will see in console there is two consecutive "inside post" and some time some time you will see one time two time consecutive "after save method" printed in console. Data also saved in database there no consistency. One solution I can think of before same user was sending many post request at same time by clicking single button now I am thinking after clicking button first request should go and after frontend got respond second request should send post request and so on. If you have better approach please suggest @csrf_exempt def product_rest(request,pk): product=Product.objects.get(pk=pk) if request.method == "POST": status = True code = 200 message = "" data = [] print("inside post") parsed_data=json.loads(request.body) print("parsing data == ", parsed_data) try: db_time = json.loads(product.time) print("old data ==",db_time) db_time.append(parsed_data) db_time_tostring=json.dumps(db_time) print("after adding data == ", db_time_tostring) product.time=db_time_tostring doctor.save() print(" after save method == ", product.time) message = "Order status created" except: status = False code = 500 message = "Internal server error" return JsonResponse({ "status": status, "code": code, "message": message, "data": data }) -
Can't access UpdateView in Django
My idea is to have Teachers and Students and I want my Teachers to have the ability to edit quizzes for the students for some reason when I try to acces the QuizUpdateView via other ListView it gives me 404 Not Found [screenshot][1] So I want to edit my quiz with this view: class QuizUpdateView(views.UpdateView): model = Quiz fields = ('name', 'subject', ) context_object_name = 'quiz' template_name = 'classroom/quiz_update.html' def get_context_data(self, **kwargs): kwargs['questions'] = self.get_object().questions.annotate(answers_count=Count('answers')) return super().get_context_data(**kwargs) def get_queryset(self): return self.request.user.quizzes.all() def get_success_url(self): return reverse_lazy('quizzes') I have int:pk in my urls.py urlpatterns = ( path('register', RegisterView.as_view(), name='register'), path('register/student', StudentRegisterView.as_view(), name='register student'), path('register/register', TeacherRegisterView.as_view(), name='register teacher'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), path('quizzes', QuizListView.as_view(), name='quizzes'), path('quiz/create', QuizCreateView.as_view(), name='create quiz'), path('quiz/update/<int:pk>', QuizUpdateView.as_view(), name='update quiz'), ) I have the quiz.pk in templates as well(I tried with quiz.id, same result) {% extends 'base.html' %} {% block page_content %} {% include 'classroom/student_header.html' with active='new' %} <div class="card"> <table class="table mb-0"> <thead> <tr> <th>Quiz</th> <th>Subject</th> <th>Length</th> <th></th> </tr> </thead> <tbody> {% for quiz in quizzes %} <tr> <td class="align-middle">{{ quiz.name }}</td> <td class="align-middle">{{ quiz.subject.get_html_badge }}</td> <td class="align-middle"> questions</td> <td class="text-right"> {% if request.user.type == 'Student' %} <a href="" class="btn btn-primary">Start quiz</a> {% elif request.user.type == 'Teacher' … -
Django app returning 404 error even if urls seem to be correct according to tutorials
I am starting my first django application. I constantly keep getting 404 error after turning on server locally in my computer. I don't see any reason for such return because urls seem to be correct when compared to tutorials and guides on the internet. This is my urls file inside app (app name is reservations) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] This is urls file in project folder (project name is website) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('reservations/', include('reservations.urls')) ] and this is index function which is supposed to show basic html def index(request): response = """<html><body><p>This is home page</p></body></html>""" return HttpResponse(response) I thought that my urls are written incorrectly so i tried writing them in different way but it never worked. Thanks for any help. -
How can I convert inMemoryUploadedFile into string to pass it over an api?
I want to pass user uploaded images into an api form my view How can I convert the inMemoryUploaded file into a string and pass it over an api and convert it back to image? -
How to restrict records to a specific seller in django admin backend
class Order(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.IntegerField() address = models.CharField (max_length=50, default='', blank=True) phone = models.CharField (max_length=50, default='', blank=True) date = models.DateField (default=datetime.datetime.today) status = models.BooleanField (default=False) seller = models.CharField(max_length=100, default='', blank=True) How to restrict backend to a specific seller records like 'A Seller Example' -
Pluralize Django message
I have the following code to display a message when a custom action is executed in the Admin site: messages.info(request, '%s posts marked as Draft' % queryset.count()) What is the best way to pluralize that message for when the count is 1 and more than 1? 1 post marked as Draft 3 posts marked as Draft if statement based on queryset.count()? -
Why is the error showing 5 positional arguments while registering the model
I am trying to make a chat application on Django. I have created a model to input into a database of the format room_no, user, message. Additionally, I have included the init function to extract the data from the database in the form of a string so I can display it on the HTML page. Apart from my method, is there another way to do this? If not, could you please explain my error? Models: class chatbox(models.Model): name = models.CharField(max_length=100, blank=False,default='Anonymous') room = models.CharField(max_length=100,blank=True) message = models.CharField(max_length=500000,blank=True) def __init__(self,name,message): self.name = name self.message = message ADMIN admin.site.register(models.chatbox) Error: TypeError at /admin/DjangoChat/chatbox/ chatbox.__init__() takes 3 positional arguments but 5 were given -
dependencies reference nonexistent child node
I tried to dockerize my Wagtail Web Application and this error Occurred. I tried docker-compose build there was no errors. after that i tried docker-compose up then this error occurred I really need help on this error. Error- 49a28e66a331_wagtail_landing_web_1 | django.db.migrations.exceptions.NodeNotFoundError: Migration home.0002_create_homepage dependencies reference nonexistent child node ('wagtailcore', '0053_locale_model') 49a28e66a331_wagtail_landing_web_1 exited with code 1 This is the Dockerfile this is the dockerfile of my wagtail site.I'm very new to wagtail and docker .Please guide me if there is an Error FROM python:3.8.1-slim-buster RUN useradd wagtail EXPOSE 80 ENV PYTHONUNBUFFERED=1 \ PORT=80 ENV PYTHONDONTWRITEBYTECODE 1 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt COPY ./compose/local/web/entrypoint /entrypoint RUN sed -i 's/\r$//g' /entrypoint RUN chmod +x /entrypoint COPY ./compose/local/web/start /start RUN sed -i 's/\r$//g' /start RUN chmod +x /start WORKDIR /app ENTRYPOINT ["/entrypoint"] This is the YAML file This is the yaml file of the System version: "3.7" services: web: build: context: . dockerfile: ./compose/local/web/Dockerfile image: wagtail_bootstrap_blog_web command: /start volumes: - .:/app ports: - 8000:8000 env_file: - ./.env/.dev-sample depends_on: - … -
Update Profile Picture, when profile_photo is a FK at the user model and I want to update the photo from the user's model
In a task I have using DRF, I need to update a user's profile picture and cover picture. Here's a part of my models/users: profile_photo = models.ForeignKey(to=Photo, related_name='profile_photo',on_delete=models.CASCADE, blank=True) cover_photo = models.ForeignKey(to=Photo, related_name='cover_photo', on_delete=models.CASCADE, blank=True) Meanwhile the Photo db table looks something like this: url_path = models.FileField(max_length=300) photo_type = models.ForeignKey(to=PhotoType,on_delete=models.CASCADE) I built the serializer classes like this but cannot seem to figure out how to write the update method to update the profile_picture from the user aspect or create it if the photo instance doesn't exist. class PhotoSerializer(serializers.ModelSerializer): photo_type = serializers.PrimaryKeyRelatedField(queryset=PhotoType.objects.all(), many=False) class Meta: model = Photo fields = ['id', 'url_path', 'photo_type'] class UserPhotoSerializer(serializers.ModelSerializer): profile_photo = PhotoSerializer(many=False) class Meta: model = User fields = ['id','profile_photo'] -
DJANGO JSON filtering complicate key
I am trying to perform a DJANGO filtering logic on this JSON "data": { "process":{ "9123fd-b01-4a00-9arwefg":{ "name":"PROCESS-1", } } Here is currently what I can do: object.filter(data__process={"9123fd-b01-4a00-9arwefg":{"name":"PROCESS-1"}} But in reality, I can only input PROCESS-1 in my filtering input, so I want to do something like this object.filter(data__process__9123fd-b01-4a00-9arwefg__name="PROCESS-1") However, this is obviously not working because of the dash (-) in the key, is there anyway I can do the filtering with this complicate key? -
How use django ORM with Serverless Application Model using AWS ToolKit
I am using AWS Toolkit to create a Serverless Application using SAM. It contains API Gateway over AWS Lambda. I want the Lambda function to be able to access data in Postgres database. In pass I have done this using Django REST Framework. But I don't want the overhead of using the entire DRF as API Gateway is taking care of the need of the REST layer. Our team is pretty well versed with Django ORM and we want to leverage on that knowledge base. Trying to combine AWS Serverless plus Django leads all the google searches to Zappa, but that's not an option for us (let's leave it to that :) ). We want to use the AWS Toolkit + SAM way. Any help would be greatly appreciated. -
django-ckeditor how to add markdown to toolbar
i have download the markdown plugin and add it to the plugin folder, this is my CKEDITOR_CONFIGS: # 富文本编辑器ckeditor配置 CKEDITOR_CONFIGS = { #(1)默认配置 # 'default': { # 'toolbar': 'full', # 工具条功能 # 'height': 300, # 编辑器高度 # 'width': 800, # 编辑器宽 # }, #(3)自定义配置带代码块显示 'default': { 'toolbar': ( ['div', 'Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'], ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker', 'Scayt'], ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], ['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], ['Styles', 'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'], ['Maximize', 'ShowBlocks', '-', 'About', 'pbckcode'], ['Blockquote', 'CodeSnippet'], ), 'width': 'auto', # 添加按钮在这里 'toolbar_Custom': [ ['NumberedList', 'BulletedList'], ['Blockquote', 'CodeSnippet', 'markdown'], ], # 插件 'extraPlugins': ','.join(['codesnippet', 'widget', 'lineutils','markdown']), }, } but it doesn't seems to work: enter image description here anybody konws how? -
Customize django-allauth / django-rest-auth Password Reset Confirm
In follow up on this question: rest-auth password reset, I now want to customize the following Password Reset Confirm page But to be honest, there is a lot of magic going on in the background so I have no idea where to start. Tried finding a template in all-auth and rest-auth but could not find the proper one to override. How would one implement such a custom Password Reset Confirm view? -
ModuleNotFoundError : no module found named <module_name>django
I am trying to make a web application using django. so in the website folder, I made another app named U0. I made sure to add it in the settings section of the website. but when I try to migrate the manage.py file it throws an error saying, No Module found named U0django -
Pycharm debugger "waiting for connection" but running still working
I am trying to debug django project with docker-compse interpreter in pycharm. Here is my configurations https://i.stack.imgur.com/4kogs.png -
ERROR: Could not find a version that satisfies the requirement pywin32==303 (from versions: none)
I tried to deploy my Django application on Heroku. But it shows an error. Then I install pywin32 by command- "pip install pypiwin32". It did not work. Please help me to solve this problem. ERROR: Could not find a version that satisfies the requirement pywin32==303 (from versions: none) ERROR: No matching distribution found for pywin32==303 ! Push rejected, failed to compile Python app. ! Push failed -
After searching on a name from db how I can get the searched name listed using python Django
I do search for user name from DB, now I want when I select any name and click on add button it shows in the list under the search box. for search code in HTML <form id="location_form" class="form" method="post">{% csrf_token %} <label id="name-label">User Name</label> <div id="item"> <input type="text" name="user" id="user_id" oninput="get_user()" /> <input type="hidden" name="user_h_id" id="user_h_id" /> <input type="hidden" name="h_id" id="h_id"/> <button type="button" id="add_user" class="btn btn-secondary"> Add User</button> </div> </form> in view.py def get_location_details(request): user_id = request.user.id if request.method == 'GET': search_string = request.GET.get('q') charge_to_list = search_string.split(' ') q = (Q(username__icontains=charge_to_list[0]) | Q(fullname__icontains=charge_to_list[0])) for term in charge_to_list[1:]: if term != '': q.add((Q(username__icontains=term) | Q(fullname__icontains=term)), Q.AND) data_list = [] qs = CustomUser.objects.filter(q, )[:10] for i in qs: data_dict = {} data_dict['id'] = i.id data_dict['username'] = i.username data_dict['fullname'] = i.fullname data_dict['show_label'] = str(i.username) data_list.append(data_dict) return JsonResponse(data_list, safe=False) -
Is there something wrong in the manner which I am trying to pass multiple parameters in django url
def index(request): if request.method == 'POST': global room_name room_name = request.POST['room_name'] if models.chat.objects.filter(room_name=room_name).exists(): username = request.POST['user_name'] return redirect('/'+room_name+'username?='+username) else: messages.info(request,'Room does not exist') return redirect(index) else: return render(request,'home2.html') urlpatterns = [ path('',views.index), path('/<str:room>/<str:username>/',views.join_room) ] I am trying to build a chatbox, and hence if this executes perfectly it should redirect the URL as 12....// where room is the chatroom and username is the username of the person logging in. But the following error comes: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/Familyusername?=Afif -
How to model this field/relation using Django
I'm creating an API using the django rest framework want to store an array of pictures inside my user model. For each picture I should have an URL and boolean flag indicating whether it is the display picture or not. There should be atleast 2 and maximum 6 pictures. One and only one of those pictures should have the display_picture_flag set as true. What would be a good way to model this. My approach (Might not be best) - I'm thinking of creating another model class with user id from user class as the foreign key. It will have an URL field and a boolean field aswell. My doubts with this are, How will I validate number of objects as lying in [2,6]. Validating that only one flag is true. Creating [2,6] objects at the same time (single Create API call). Using JSON field. probably store as dictionary with URL mapped to flag. Again, confused with validations. Please suggest better approaches, or expand upon my approaches. Thanks! -
How to manage and save nested arrays to django models
I'm receiving the data from the frontend app in the form of Arrays, or say List of objects. I want to create and save the data using Django models and views. I'm a little confused about how can make a structure of tables to save this type of data That's how would be I receiving data: [ { question: 'Screen Works Properly', parentId: 1, child: [] }, { question: 'Theres issue of Hardware', parentId: 2, child: [ { id: 15, sub_question: 'Broken Speakers' }, { id: 18, sub_question: 'Battery Damaged' } ] } ] There could an unlimited number of objects in the list and every object has a child array which can have an unlimited number of objects as well. I can see there I can make a model Data and then can link the objects with ForeignKey, But how will I manage the child Array/list in the object. Can anybody give me an idea of how can I create models to save this type of data? -
How to submit form using jquery submit
Here is my jquery code $(document).ready(function () { $('.bar_dropdown').on('change', function() { console.log("dropdown changed") $('#bar_graph_form_id').submit(function(event) { event.preventDefault(); var data = new FormData($('#bar_graph_form').get(0)); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: function (data) { console.log('form submitted successfully') console.log(data) } }) }) }) }) Here is my HTML <form id="bar_graph_form_id" method="post" action="display_bar_graph" name="bar_graph_form"> {% csrf_token %} <select class="form-select bar_dropdown" aria-label="Default select example" name="bar_graph_dropdown"> <option selected>Select data to visualise</option> <option value="1">By category</option> <option value="2">By language</option> </select> </form> <div class="bar_graph_container"> </div> When the dropdown value changes, I want the form to submit and a django view triggered. This is my view def display_bar_graph(request): if request.method == 'POST': user_select = request.POST['bar_graph_dropdown'] if int(user_select) == 1: graph = open('./graphs/bar1.html', 'r').read() if int(user_select) == 2: graph = open('./graphs/bar2.html', 'r').read() context = {'html_data': graph} print('the form was submitted using ajax') return JsonResponse(context) The idea is that a plotly graph be displayed in bar_graph_container div when the dropdown value changes. But I notice that this code $('#bar_graph_form_id').submit(function(event) { does not work. I removed the function from the submit as follows $('#bar_graph_form_id').submit() and this works fine. I wonder what I am doing wrong. -
How to get json data from django views using ajax
I have a form as follows <form id="bar_graph_form" method="post" action="display_bar_graph" name="bar_graph_form"> {% csrf_token %} <select class="form-select bar_dropdown" aria-label="Default select example" name="bar_graph_dropdown"> <option selected>Select data to visualise</option> <option value="1">By category</option> <option value="2">By language</option> </select> </form> <div class="bar_graph_container"> </div> The idea is that when the dropdown value is changed, the form has to submit via ajax and trigger the django view My JS code is as follows function dropdown_change_function(event) { event.preventDefault(); var data = new FormData($('#bar_graph_form').get(0)); console.log('this is happening') $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: function (data) { console.log('form submitted successfully') console.log(data) } }) } $(document).ready(function() { $('.bar_dropdown').on('change', function() { document.forms['bar_graph_form'].submit(dropdown_change_function); }) }) Using this code, I am able to successfully submit the form on dropdown change, but the ajax function is not called. Here is my django view def display_bar_graph(request): if request.method == 'POST': user_select = request.POST['bar_graph_dropdown'] if int(user_select) == 1: graph = open('./graphs/bar1.html', 'r').read() if int(user_select) == 2: graph = open('./graphs/bar2.html', 'r').read() context = {'html_data': graph} print('the form was submitted using ajax') return JsonResponse(context) What I am trying to do is to display a particular plotly based graph in the template. I already have the graphs saved as HTML files and would …