Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest-framework with mongodb not creating auto field primary key id
I am saving record in mongodb using django rest framework. Migration is as below - # Generated by Django 3.0.5 on 2021-01-17 10:39 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Demo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(default='', max_length=1000)), ('user_id', models.IntegerField()), ('published', models.BooleanField(default=False)), ], ), ] But the records in mongodb doesn't have auto created id in it { "_id" : ObjectId("6004354240e7097e5b392e5c"), "description" : "sdf asdaaaaaaaaaaaaaaaaaaaaaaaaaaa ass d", "user_id" : 11, "published" : false } Inserting records using serializer.save() -
How do I get pass "Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name" in Django
I have tried many of the suggested solutions show in previous questions but no success. I am trying a password reset but the error pop up each time the email form for the password reset is submitted. My files urls.py path( 'reset-password/', auth_views.PasswordResetView.as_view( template_name='account/reset_password.html', html_email_template_name='account/reset_password_email.html', success_url=settings.LOGIN_URL, token_generator=user_tokenizer), name='reset_password'), path( 'reset-password-confirmation/<str:uidb64>/<str:token>/', auth_views.PasswordResetConfirmView.as_view( template_name='account/reset_password_update.html', post_reset_login=True, post_reset_login_backend='django.contrib.auth.backends.ModelBackend', token_generator=user_tokenizer, success_url=settings.LOGIN_REDIRECT_URL), name='password_reset_confirm' ), reset_password_email.html {% autoescape off %} To initiate the password reset process for your Account {{ user.email }}, click the link below: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. {% endautoescape %} -
Media path not read in Django
I'm having a problem on how can I retrieve my images through using media file in Django. Currently I just want to display images based on their path in Database. Based on the console image below the {{MEDIA-URL}} does not recognize/read, it only read this tag {{img_photos.photos}}. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance I followed this documentation link but it seems it's not working. view_gallery.html {% for img_photos in photos %} <div class="card-body px-0"> <img src="{{MEDIA_URL}}{{img_photos.photos}}"/> #it seems {{media-url}} didn't read/recognize <h4 class="card-title">{{img_photos.photos}}</h4> <p class="card-text">This is a longer card with supporting text below.</p> </div> {% endfor %} App - urls.py urlpatterns = [ path('view_gallery/<int:pk>/',views.view_gallery, name='view_gallery'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def view_gallery(request,pk): path = settings.MEDIA_ROOT #I didn't use this don't know yet how to implement image = gallery_photos.objects.filter(gallery_info_id = pk) data = {'photos':image} #the output is like this PHotos/image.jpg return render(request, 'view_gallery.html', data) -
What kind of password does django-allauth put when registering through a social network?
When I register via social network, a new account is successfully created (with some kind of password). But if I want to enter the data of the created account through the forms, then because of the password, the account is not recognized. Django passwords: pbkdf2_sha256$216000$UHmkhzS870QX$FN7HfQDdbUvJ4GXJCIe2sPDGQTMuJjlPfUpiRxxGBc8= Django-Allauth passwords: !1ceV9EGvYkdbyAWNJZJ3n5KXLZ1K776oII6WJNhk -
Use Vue components in application at runtime
I am developing a small application using Vue which will have list of downloadable components available to the user. Downloadable components will be hosted somewhere on the webserver(compiled version of SFC's) seperately. List of components can be increased or decreased based on users permissions. This application will be shared with the user to download the components of their choice and add them to the list. Problem is am not getting any examples in the internet where compiled components are used inside compiled Vue apps at runtime. All the available examples need compiled components to be registered or to be imported in the applications in order to use it. The only way right now is to chuck the idea of using ES6 or (.vue) Single file Components luxury and use ES5 version which i don't want to. Can anyone help me out? Backend used is Django -
Django: How to realize App structure for specific program (picture)
I'm new to Python/Django and I would like to rewrite an old program as a web application The picture is a screenshot of the program. As you can see there are multiple tabs on the left and two on the top (marked red) so the programm ist kind of nested(?). All of the Tabs work together to calculate the end result. Im kind of overwhelmed so my first question is how to structure the Programm in Django using apps. Is each Tab one app and I link them all together? Also is there a template for tab-style menue? Thank you very much, hope ich can get it realized :D Programm_Image -
Design pattern of coupling/decoupling two apps in Django
I have two apps: app1 and app2. =>app1 has model A gets data with timestamps. =>app2 has model B with some computations that have to be made on the data that model A gets Usecase:. Every time we create model B, it has to check if we have enough data in model A => do an update. This same update is triggered every time we add data to model A. => My design is: since updates are having a place in model B then I import my model A in it and check if I have enough data while creating model B. on the other way around, if I add data to model A I prefer not importing model B in model A to avoid app circular dependencies and coupling. So my idea here is to send a signal from model A to model B and proceeds to the update, is it the best way to do it or you would think of some different design patterns? => I also read on some blogs that using signals is not always suggested, what's your take on this? -
How to delete a record only if the user posted is the logged in user
I have multiple users in my project my models.py file is class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Teacher(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,related_name='Teacher') name = models.CharField(max_length=250) subject_name = models.CharField(max_length=250) email = models.EmailField(max_length=254) phone = models.IntegerField() teacher_profile_pic = models.ImageField(upload_to="classroom/teacher_profile_pic",blank=True) def __str__(self): return self.name class Announcement(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def __str__(self): return self.title If the logged in user is a teacher it is allowed to create an announcement Now i want that only the teacher who posted the announcement should be able to see the delete button My html file is {% extends "classroom/base.html" %} {% block content %} <h1>Announcements</h1> {% for announcement in announcements %} <!-- starting loop (posts is keyword from view) --> <div style="border-style: solid;"> {% if object.teacher.id == request.teacher %} <div> <a href="{% url 'classroom:opt' %}">Delete</a> </div> {% endif %} <a class="mr-2">Posted by: {{ announcement.teacher }}</a> <h2><a class="article-title">{{ announcement.title }}</a></h2> <p class="article-content">{{ announcement.content}}</p> </div> {% endfor %} {% endblock content %} the if statement is supposed to be true if logged in teacher is the teacher who originally posted it. However the delete button is visible for every announcement my views.py has class AnnouncementListView(ListView): context = { … -
What is the Best way to get only 10 rows in django ORM
I have Grid-view it only show 10 records on time . What is the best way to get from database only 10 rows? Is MyModel.objects.all()[10:20] approprate . -
Django unit test remove Files created inside the tests
I'm using DRF view tests. Inside my tests I create files which I want to remove after the tests were running. I'm using addCleanup inside my setUp method to remove the directories. It basically works, but when I run my complete set of unit tests one dir won't be deleted (I think it's the first one created). Here is the relevant code: class BaseViewTest(APITestCase): client = APIClient() base_media_root = settings.MEDIA_ROOT def setUp(self): settings.MEDIA_ROOT = tempfile.mkdtemp(dir=self.base_media_root) # add test data self.addCleanup(shutil.rmtree, settings.MEDIA_ROOT) -
Django {% if object.foreignkey %} returns the opposite of the value
So I have two models. First one is Collection Title and second one is Title Status. In Title Status I have a foreignkey named collection_title_status that points to CollectionTitle. I have rendered the form TitleStatusForm inside my collection_title_detail.html with a DetailView and a FormMixin. The form is in a modal. Globally, this part works, meaning that I can fill the form, and it saves the data and creates a link between the Collection Title and the Foreign Key of Title Status (for example, if CollectionTitle id is 61, my collection_title_status value will be 61 as well). What I want to do : If Collection Title is not linked to a Title Status (meaning the user as not initiate the Status monitoring yet), then I want to display the button called 'Initiate' that opens the modal containing TitleStatusForm to initiate the Title Status model If Collection Title is already linked to a Title Status (which should be done after fulfilling the first step above), then I don't want to display the above mentionned button and modal. Instead, I want to display the values previously entered by the user for each field. So here is how I tried to do it : … -
Google blocks confirmation email sent from my blog
I'm creating a blog with django, and when I try to send the registration email to a user, Google blocks the sending. Here, the screenshot of the message: https://i.stack.imgur.com/faqV6.png acc_active_email.html: {% autoescape off %} Hi {{ user.username }}, Click here to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} Email configuration in settings.py: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_PORT = 587 I've tried with different emails, but the problem persists. Thanks in advance for the help. -
Why does docker-compose.local.yml can not run django app?
I am using docker-compose -f docker-compose.local.yml run django black apps common tests individual_service It is giving: python: can't open file '/app/manage.py': [Errno 2] No such file or directory -
How to send mail when new blog post is published to subscribed users in django?
How to send mail when new post is published to subscribed users in django -
Is there a way to use the requirements.txt file when deploying a Django App with Azure CLI?
It seems that the requirements.txt file is automatically recognized and executed when using the github continous integration. Would it be possible to do this with Azure CLI? -
current path didn't match in django
I am a beginner for django. I tried to make my 1st project helloworld, with the help of tutorials I installed and followed their instructions. When I run my project in server it shows an error 404, the current path didn't match any of these. myproj/urls.py from django.contrib import admin from django.urls import path from helworld.views import hello urlpatterns = [ path('admin/', admin.site.urls), path('index/', hello), ] helworld/views.py from django.shortcuts import render from django.http import HttpResponse def hello(request): return HttpResponse(request, "hello world!") This is my code when I run it. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/helworld Using the URLconf defined in myproj.urls, Django tried these URL patterns, in this order: admin/ index/ The current path, helworld, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I searched for solution but being a beginner its bit tough for me to solve this error. so kindly help me with an easy clarification. Thank you in advance. -
Refresh table data every 5 seconds with ajax based on toggle button status
I am creating a web page using Django and Ajax. I want to refresh my page every 5 seconds depending on the status of a bootstrap toggle switch. i.e. On - Auto refresh table data every 5 seconds Off - Do not refresh I have the below written with ajax call. $(document).ready(function () { $('#auto_switch').hide(); $('#loading').show(); var broker = '{{ broker }}'; $.ajax({ type: "GET", cache: true, url: '{% url 'broker:load_data' %}', data: { 'broker': broker, }, data_type: 'html', success: function (data) { $('#loading').hide() $('#auto_switch').show(); $('#stock_holdings').html(data.rendered_table); } }); $("#auto_switch").change(function () { if ($(this).prop("checked") == true) { setInterval(function () { $.ajax({ type: "GET", cache: true, url: '{% url 'broker:load_data' %}', data: { 'broker': broker, }, data_type: 'html', success: function (data) { $('#loading').hide() $('#auto_switch').show(); $('#stock_holdings').html(data.rendered_table); } }); }, 5000); else { $.ajax({ type: "GET", cache: true, url: '{% url 'broker:load_data' %}', data: { 'broker': broker, }, data_type: 'html', success: function (data) { $('#loading').hide() $('#auto_switch').show(); $('#stock_holdings').html(data.rendered_table); } }); } }); }); I am expecting that if (toggle button is enabled), the function will trigger and the table data will keep refreshing every 5 seconds and on any change in the toggle switch it will find its status as off and no auto refresh … -
Send Html as text/html in Django
I have an entry.html file which looks like this: {% extends 'encyclopedia/layout.html' $} {% block title %} {{ title_name }} {% endblock %} {% block body %} {{ content }} {% endblock %} There are some markdown files (.md) which I have to read, convert to HTML, and display it on the webpage. There is a util.py file which returns the content of the markdown file by using the util.get_entry(title) function. Here is my views.py file: from django.shortcuts import render from django.http import HttpResponse from . import util from markdown2 import markdown ... def entry_page(request, title): md_text = util.get_entry(title) if md_text is not None: html = markdown(md_text) return render(request, 'encyclopedia/entry.html', { 'title_name': title, 'content': html }) else: return HttpResponse('<h1>404 Page Not Found!</h1>') The problem here is that the output is in plain text, like this: I want to send the text as html and not a plain text. How do I achieve this? -
Add row Id in Django data table
I am using django datatable the data that come from server has the following format: [ ['id_value','data col1','data col2',...] . . .] I am try to make id to every row as follow: 'rowId': 1, but it doesn't work my html code: <table id="mainDataTable" class="table table-responsive-md table-{{ documentvals.table_type }}"> <thead> <tr> {% for field in list_fields %} <th> {{ field }}</th> {% endfor %} </tr> </thead> <tbody> </tbody> <tfoot> <tr> {% for field in list_fields %} <th> {{ field }}</th> {% endfor %} </tr> </tfoot> </table> Also, my js code is: let _columns= [ {% for field in list_fields %} { "data": '{{ field }}' }, {% endfor %} ] $('#mainDataTable').DataTable({ "paging": true, "lengthChange": true, "searching": true, "ordering": true, "info": true, "columns": _columns, "autoWidth": false, "responsive": true, "aaSorting": [], "pageLength": pag, "bProcessing": true, "bServerSide": true, "ajax": { "url": mainUrl, }, 'rowId': 2, "pagingType": "full_numbers", destroy: true, }); I did not want to edit django datatable library. -
get the id and description from database for dropdown in django
I am trying to create a dropdown in my django form. I am new to django framework. In ASP.NET MVC, we use LINQ or SQL Procedure to fetch data and also in model class we can do, /// model class [NotMapped] public string ddl_productdesc { get { return string.Format("{1} --- {2}", ProductID, I_NUMBER, ProductDESC); } } In my table, there are around 30 columns from them I need three fields (ProductID, I_NUMBER, ProductDESC, I_NUMBER) for my dropdown How can I do the same in django, the ID field used for data fetching and insertion and other two fields as dropdown? Thank You! -
What is the best way to prepopulate Groups table and permissions for it at application startup?
My goal is: to have created custom Groups and populated with permissions for specific models. All that immediately after or during application starts Question: What is the most appropriate way to achieve that? For example my custom group is MY_CUSTOM_GROUP and i want to add change and view permissions for Model Book to that group -
How to concatenate two dates into one string in Django?
I have two model fields. class Event(models.Model):] start_date = models.DateTimeField() end_date = models.DateTimeField() I would like to concatenate two dates into one string I would like to obtain result like this as new field: {'dates': '2020-12-1-2021-12-1'} concatenate start_date and end_date into one string What I tried to do: event = Event.objects.annotate(dates=Concat('start_date__date', 'end_date__date')) event.values('dates') Output: <QuerySet [{'dates': '2020-12-25 17:44:50+002021-01-16 17:44:52+00'}], Not output I would like to obtain I need output like this: {'dates': '2020-12-1-2021-12-1'} Concatenate two date time fields into one string (only dates, don't need time) -
Django local_settings.py Protection and Permission
I want deploy a Django project, I created a local_settings.py for local variables(secret_key, database ,etc). Are there any best practices or check lists for protecting local_settings.py file? for example what should be its permission (e.g is 700 ok?)? or where should be located (its path)? Thanks -
How to add HTML tags functionality inside of a post model in Django
I'm learning to build a blog post using django. The Blog post has a title, introduction and body. I want to be able to use HTML tags inside of the body field. I'm a newbie in programming and I don't know how to go about it. Please I need your help. -
I am getting this error while adding product from django admin panel
When i try to add product from django built admin panel i get this error message: /home/pihffall/virtualenv/gngmain/3.7/lib/python3.7/site-packages/PIL/../Pillow.libs/libjpeg-ba7bf5af.so.9.4.0: file too short Can someone tell me how can i solve this issue ?