Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
DJANGO: I have been trying do calculation in Views and call function whenever i click on a button
Hello & Thank YOU For Helping ME. I have been trying to make calculations using django but i keep on hitting different errors. the latest one was Base 10 error in django. VIEWS.PY def subs(request, pk): sw = Swimmers.objects.filter(id=pk).values('sessions').first() sw_list = sw sw_lists = sw +1 return JsonResponse(sw_lists, safe=False) MODEL.PY class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.CharField(max_length=200, blank=False ) dateofpayment = models.CharField(max_length=200, blank=False) phone = models.CharField(max_length=30, blank=False, null=True) date_from = models.DateField(null=True) date_to = models.DateField(null=True) type_choice = ( ("basic", "Basic"), ("3x1 week", "3x1 Week"), ("1 session", "1 Session"), ("2x1", "2x1"), ) type = models.CharField(max_length=200, blank=False, null=True, choices=type_choice, default=type_choice) ammount = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=True) registration = models.DateField(default=timezone.now) keenphone = models.CharField(max_length=30, blank=False, null=True) def __str__(self): return self.name URLS.PY path('swimminglist/', views.SWGIndex.as_view(), name="swimminglist"), path('create/', views.SWGCreateView.as_view(), name='create_swimmer'), path('update/<int:pk>', views.SWGUpdateView.as_view(), name='update_swimmer'), path('read/<int:pk>', views.SWGReadView.as_view(), name='read_swimmer'), path('delete/<int:pk>', views.SWGDeleteView.as_view(), name='delete_swimmer'), path('subt/<int:pk>', views.subs, name='subt'), Thank You For The Help And Support Much Appreciate It. Have A Blessed Day You All. -
null value in column "cover_photo" violates not-null constraint
Here's the error, which is strange because I use github search to search my repository and there's nothing called "cover_photo": null value in column "cover_photo" violates not-null constraint and here's the associated code, i ensured all the model fields have null=True, but that didn't fix it.: class Anon(models.Model): username = models.OneToOneField(User, default=None, null=True, unique=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=70, default=None, null=True) last_name = models.CharField(max_length=70, default=None, null=True) topic_expert = models.CharField(max_length=70, default=None, null=True) company = models.CharField(max_length=70, default=None, null=True) title = models.CharField(max_length=70, default=None, null=True) trailings = models.CharField(max_length=70, default=None, null=True) email = models.EmailField(max_length=70, null=True) password = models.CharField(max_length=70, default=None, null=True) password2 = models.CharField(max_length=70, default=None, null=True) missionstatement = models.TextField(max_length=300, default=None, null=True) interests = models.TextField(max_length=300, default=None, null=True) profileImages = models.ManyToManyField(Profile_image, default=None, null=True) experiences = models.ManyToManyField(Experience, default=None, null=True) professional_experience = models.OneToOneField(Professional_Experience, default=None, null=True, on_delete=models.CASCADE) education_experience = models.OneToOneField(Education_Experience, default=None, null=True, on_delete=models.CASCADE) language_experience = models.OneToOneField(Language_Experience, default=None, null=True, on_delete=models.CASCADE) expertises = models.ManyToManyField(Expertise, default=None, null=True) latest_change_date = models.DateTimeField(default=timezone.now) #playlists = models.ManyToManyField(Playlist)= sent_messages = models.ManyToManyField(Comment, default=None, related_name='sent_messages', null=True) received_messages = models.ManyToManyField(Comment, default=None, related_name='received_messages', null=True) posted_comments = models.ManyToManyField(Comment, default=None, related_name='posted_comments', null=True) saved_comments = models.ManyToManyField(Comment, default=None, related_name='saved_comments', null=True) posts = models.ManyToManyField(Post, blank=True, default=None, null=True) categories = models.ManyToManyField(Category, default=None, null=True) post_sort = models.IntegerField(choices=POST_SORT_CHOICES, default=0) references = models.IntegerField(default=0) topic_sections = models.ManyToManyField(Topic_Section, default=None, null=True) sub_topic_sections = models.ManyToManyField(Sub_Topic, default=None, null=True) … -
Sort search results in django
I have a function that returns a queryset and an html file with the results, def get_queryset(self): # new query = self.request.GET.get('q') sort = '-date' post_list = Post.objects.filter( Q(title__icontains=query) #| Q(title__icontains=query) another field ).order_by(sort) return post_list form: <form class="form-inline my-2 my-lg-0" action="{% url 'search_results' %}" method="get"> <input class="form-control" name="q" type="text" placeholder="חפש מאמרים"> <button class="btn btn-outline-success my-sm-0" type="submit">חפש</button> </form> In the template for the results I want there to be a couple of links to sort by date, votes etc... -
How to set Unique Constraint across multiple tables in django?
We have two models, they are in One to One relationship: class A(models.Model): first_field_A = ... second_field_A = ... class B(models.Model): first_field_B = ... a = models.OneToOneField(A, on_delete=models.CASCADE) I need to define a Unique Constraint for first_field_A and second_field_A of model A and first_field_B of model B. Is that even possible? I have tried this: class A(models.Model): ... class Meta: constraints = [UniqueConstraint(name='unique_constraint', fields=['first_field_A', 'second_field_A', 'b__first_field_B'] ) ] and I've got this error: django.core.exceptions.FieldDoesNotExist: A has no field named 'b__first_field_B' Why we don't have access to fields of related tables? What is the alternative? -
ModuleNotFoundError: No module named 'django' get it from apache2 err log from ubuntu 20
this is the whole error log [Sun Apr 10 10:18:09.057500 2022] [wsgi:error] [pid 122773:tid 140541313599232] [remote 83.244.126.186:58941] Traceback (most recent call last): [Sun Apr 10 10:18:09.057553 2022] [wsgi:error] [pid 122773:tid 140541313599232] [remote 83.244.126.186:58941] File "/home/sk/saree3co/sash/wsgi.py", line 12, in [Sun Apr 10 10:18:09.057560 2022] [wsgi:error] [pid 122773:tid 140541313599232] [remote 83.244.126.186:58941] from django.core.wsgi import get_wsgi_application [Sun Apr 10 10:18:09.057584 2022] [wsgi:error] [pid 122773:tid 140541313599232] [remote 83.244.126.186:58941] ModuleNotFoundError: No module named 'django' [Sun Apr 10 10:18:11.068338 2022] [wsgi:error] [pid 122773:tid 140541204494080] [remote 83.244.126.186:58940] mod_wsgi (pid=122773): Failed to exec Python script file '/home/sk/saree3co/sash/wsgi.py'. [Sun Apr 10 10:18:11.068391 2022] [wsgi:error] [pid 122773:tid 140541204494080] [remote 83.244.126.186:58940] mod_wsgi (pid=122773): Exception occurred processing WSGI script '/home/sk/saree3co/sash/wsgi.py'. [Sun Apr 10 10:18:11.068510 2022] [wsgi:error] [pid 122773:tid 140541204494080] [remote 83.244.126.186:58940] Traceback (most recent call last): [Sun Apr 10 10:18:11.068531 2022] [wsgi:error] [pid 122773:tid 140541204494080] [remote 83.244.126.186:58940] File "/home/sk/saree3co/sash/wsgi.py", line 12, in [Sun Apr 10 10:18:11.068534 2022] [wsgi:error] [pid 122773:tid 140541204494080] [remote 83.244.126.186:58940] from django.core.wsgi import get_wsgi_application [Sun Apr 10 10:18:11.068548 2022] [wsgi:error] [pid 122773:tid 140541204494080] [remote 83.244.126.186:58940] ModuleNotFoundError: No module named 'django' -
how can I receive notification by another user using channels in django?
actually, this is the first time I use channels but it's an easy concept to understand. I followed a tutorial that took me to the way in which I can send the notification the real-time but there's a part that I can't see at any tutorial where they are oblivious to it. all tutorials show how can send a notification or messages via chat when I do that for a single user after I open the new page, the page works fine. for example, if I logged in by username "test" and opened a new browser logged in by username "test" will be working fine the problem is that: when I try to open for example an "incognito page" by google chrome to use a different user such as "new test" username that I want him to receive the notification we can consider him a target user from the sender on the main page "test". now the data is changing in the data but I can't see that change in front of my eyes unless I reload the web page. when I tested that out I see javascript doesn't receive any of the data in the "new test" user and … -
Django Template Tag Filter
How do I display a list of students of a particular level using template tags? {% for student in student_list %} <li>{{ student.name }}</li> <li>{{ student.level }}</li> {% endfor %} This code just displays the list of all students’ names and levels, but I just want it to show the names of students that are, for example, freshmen. Is that possible and how do I do that? -
Django. Datefield format in html
I want do like this: enter image description here date = models.DateField(auto_now_add=True, auto_now=False) View: class Blog(ListView): model = Post template_name = 'blog/blog.html' context_object_name = 'posts' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) return context def get_queryset(self): post = Post.objects.filter().select_related().defer() return post HTML: <a href="#" class="blog_item_date"> <h3>{{ post.date.day }}</h3> <p>{{ post.date|date: 'M' }}</p> </a> But i get error is: Could not parse the remainder: ': 'M'' from 'post.date|date: 'M'' -
DJANGO I am trying to add +1 whenever i click on a button Add - invalid literal for int() with base 10: 'sessions'
invalid literal for int() with base 10: 'sessions' MYCODE def subs(request, pk): sw = Swimmers.objects.filter(id=pk).values('sessions').first() sw_list = list(map(int, sw )) sw_lists = list(map(lambda x: x + 1, sw_list )) return JsonResponse(list(sw_lists), safe=False) -
How to use custom function for account activation in django graphql auth
I am using django-graphql-auth to send account activation email. It has below method, https://github.com/PedroBern/django-graphql-auth/blob/master/graphql_auth/mixins.py#L200 However I need to use my own custom function since I am using third party api service. Using my function I am able to send the email however I am not sure how can I override the default behavior. I am seeing there is an async_email_fucn at below, https://github.com/PedroBern/django-graphql-auth/blob/master/graphql_auth/mixins.py#L219 Please suggest. -
Django template- If an DateTimeField value taken from Foreignkey passed to a url, an error occurs: 'str' object has no attribute 'strftime'
I'm quite new to django and trying to figure out why I'm getting an AttributeError: 'str' object has no attribute 'strftime' when passing a datetime object to a url from a DateTimeField() value thru ForeignKey. Here are the sample codes I'm using and trying to pass last_checked value from Scrape Model. model.py class Site(models.Model): ... class Scrape(models.Model): ... last_checked = models.DateTimeField(auto_now_add=True) site = models.ForeignKey(Site, on_delete=models.SET_NULL, related_name='scrapes') url.py from django.urls import path, register_converter from . import views class DateConverter: regex = '\d{4}-\d{1,2}-\d{1,2}' def to_python(self, value): return datetime.strptime(value, '%Y-%m-%d').date() def to_url(self, value): return value.strftime('%Y-%m-%d') register_converter(DateConverter, 'date') urlpatterns = [ path('task/<pk>/<date:date_scraped>/', views.scrape_data_csv, name='scrape-csv'), ] If I'm passing the value directly from Scrape model queryset to the template like this. Everything works perfectly! <a href="{% url 'scrape-csv' site.pk scrape.last.last_checked %}" > </a> However if I passed the value to Site model queryset thru ForeignKey, which is the way to I need to have, here I get the error occurs: {% for site in sites %} <a href="{% url 'scrape-csv' site.pk site.scrapes.last.last_checked %}" > </a> {% endfor%} If we checked the values, both the same datetime objects: {{ scrape.last.last_checked }} # April 8, 2022, 10:14 a.m. {{ site.scrapes.last.last_checked }} # April 8, 2022, 10:14 a.m. … -
Django's CKEditor not appearing in Admin Panel
I have a simple Django application that allows me to create an article. It contains a title, date, author (auto applied) and body. Using the RichTextField, I created my body in the models, however, a simple plain text area is appearing in my admin instead of my RichTextField, see here Something I found during an HTML inspection is this. I didn't add that and I have no idea how to fix that as well. Here is all the relevant code Admin.py from django.contrib import admin # Register your models here. from .models import Article admin.site.site_header = 'Neostorm Admin' @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): class Media: js = ('ckeditor/ckeditor/ckeditor.js',) def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change) Models.py from django.db import models from ckeditor_uploader.fields import RichTextUploadingField from django.contrib.auth.models import User # Create your models here. class Article(models.Model): title = models.CharField(max_length=50) body = RichTextUploadingField(blank=True, null=True) #Order the articles model by the date of update created_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, editable=False) Relevant settings.py configurations STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "images/" CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = 'articles/' CKEDITORBackGround = '#7D001D' CKEDITOR_CONFIGS = { 'default': { "width": "100%", 'skin': 'moono-lisa', … -
Specific Viewing Privilege's in HTML and Python
I'm making a college events website for a project and one of the requirements is to be able to make events that are private for your student organization or your university. So all events should be tagged as either Public, Private(can only view if you attend the same university as the event creator), or RSO(can only view if you are in the same student organization as the event creator). I have managed to make a page where you can view all the events but I can't figure out how to make it so you can only view these events under the provided circumstances. Right now all the events no matter what the tag is show up for everyone looking at the events list page. Any ideas on how to do this? -
How to format date 20220410 to 2022-04-10 in Python?
I need help formatting the date. I have a variable date as an integer like this: date = 20220410 # YYMMDD Desired format: 2022-04-10 I written some algorithms to do this with for loops. But didn't work!