Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send mass emails using Django EmailMultiAlternatives
I want to send mass email using Django EmailMultiAlternatives because I am using an HTML email to send as newsletters and send_mass_mail does not support. Below code working fine and sends email only first recipients form the list but I have multiple recipients in the list. Here is my code: def send_birthday_email(): today = date.today() get_dob_email = CoWorker_Data.objects.filter(dob__day=today.day, dob__month=today.month).values('email') mailtosend = "" for mail in get_dob_email: mailtosend = mail["email"] + "," + mailtosend threading.Timer(120, send_birthday_email).start() # Send email subject = 'Happy Birthday from LaunchPad7' from_email = settings.EMAIL_HOST_USER to_email = mailtosend print('Hellll:', mailtosend) with open(settings.BASE_DIR + '/lp7ms/templates/emails/birthday_email.txt') as f: text_message = f.read() message = EmailMultiAlternatives(subject=subject, body=text_message, from_email=from_email, to=[to_email]) html_content = get_template('emails/birthday_email.html').render() message.attach_alternative(html_content, 'text/html') message.send() send_birthday_email() -
what is haystack ,elastic search, elasticsearch_dsl in django?
can anyone explain what is : 1. haystack 2. elastic search 3. elasticsearch_dsl what is the purpose to use this in Django project. i tried to learn in websites but i cannot understand the usage purpose. -
Django debug False prevents access to files saved in media folder
I have a model that takes a File Field which is uploaded in Django admin. I noticed that the files save in the proper folder. But when Debug is set to False, I cannot access the file from the admin area or from the front end user interface. I get an error message that says "The resource could not be found on the server." The app is hosted on Heroku and does the same thing in localhost and live. I read in another post that Whitenoise would work with Heroku but it hasn't resolved the issue. Could someone please point me in the right direction to a fix? The relevant files are below. models.py from django.core.files.storage import FileSystemStorage from django.db import models class DataSet(models.Model): title = models.CharField(max_length=255) date_added = models.DateField(auto_now=True) file_size = models.CharField(max_length=20) file_type = models.CharField(max_length=20) data_file = models.FileField(upload_to='delivery/') def __str__(self): return self.title settings.py import os import django_heroku import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = Redacted # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', … -
Filtering without submit button (Django)
I filter objects by choose one in dropdown box and click submit button, then it will work. But I don't want to click submit button. I need it work immediately after I click on alternative in dropdown box. <form method="GET" class="form-inline"> <select name="filtering" class="form-control"> <option value="none">Alt 1</option> <option value="01">Alt 2</option> <option value="02">Alt 3</option> </select> <input type="submit" value="Filter"> </form> PS. I use html with python+django. -
Register multiple routes in Django DRF - using and calling methods in ModelViewSets or Generics
I want to understand how to use Django DRF to register: two different endpoints, and only one endpoint making use of custom fields Please show the differences in using ViewSets and Generics. These are my attempts. I came from Flask, and found very clear to define multiple end-points with decorators. Flask - example endpoints to get a list of objects,last object option 1 @application.route('/people/', endpoint='people') def people(): # return a list of people pass @application.route('/last/', endpoint='last_person') def last_person(): # return last person pass option 2 @application.route('/people/', endpoint='people') def people(): field = request.args.get('last', None) if field: # return last person from list of people else: # return list of people I understood the benefit of DRF may be consistency and read the documentation, but found cumbersome and wish to understand more clearly how to make use of ModelsViewSets and Generics to see the benefits VS flask. Please help with an example to fetch a list of users, and last user. Django DRF - first approach (ModelViewSet) # serializer.py from rest_framework import serializers from .models import Person class PersonSerializer( serializers.HyperlinkedModelSerializer): class Meta: model = Person fields = ('name', 'nickname', 'timestamp') # views.py class PersonViewSet( viewsets.ModelViewSet): queryset = Person.objects.all().order_by('name') serializer_class = PersonSerializer I … -
django form input range how to show value?
I have a question about range input in Django 2. How can I display the current value of the input range slider? Now its only slider without any values. Maby I should save value every time it changes, but I'm looking for simplicity. Form: scale = forms.IntegerField(widget=forms.NumberInput(attrs={'type':'range', 'step': '5', 'min': '-100', 'max': '100'}), required=False) Template: {{form.scale}} this how it looks like -
how to schedule a same (function) task for different users for different time dynamically with different arguments in python3
I am working with a project.It was an web application. With this there is a module named Scheduler(scheduling task and get updated data as csv file). we have a task and we have to run that task on user basis timings.time is also give by users . please help me to out this problem Thank you ji -
Pass data from Django view to template
I have a very basic view that is supposed to render a page and pass some data to this page, here is how i do it: def myview(request): request = mydb.objects.filter(user=request.user) return render(request, "main/mytemplate.html", context={"data":request}) When the page is loaded, the data is passed to the template, so to show that data, i'll only have to go to my html and add this: {{data}} But how can i do the same from a view that is not the same view that renders the page? Let's say that this is a view that i can call with an Ajax request, so when the Ajax request is triggered, the view should send data in the same way and i want to be able to use it in the Django template language. Here is an example: def secondview(request): request = mydb.objects.filter(item='free') return HttpResponse(request) This view is called from an Ajax request, it will send a response with the data, but i don't want to get the data in this format or in json format, instead i want to use it from the Django template language, just as i did with the first example. Is there any way to do it? Or can i … -
How do you post a file along with some other data using axios react?
So my model looks like this. # posts/models.py from django.db import models class Post(models.Model): title = models.TextField() cover = models.ImageField(upload_to='images/') def __str__(self): return self.title And I know you can upload file using axios like this fileUpload(file){ const url ='http://example.com/file-upload'; const formData = new FormData(); formData.append('file',file) const config = { headers: { 'content-type': 'multipart/form-data' } } return post(url, formData,config) } But I want to upload the image along with the title. How do I do that in axios? -
I want to edit only one database field with one click with django
I have a Movie database and a boolean field init. I want to click a button and change that boolean field's value. But I couldn't manage to get Movie pk from the url. I'm getting this error: 'WSGIRequest' object has no attribute 'kwargs' Here is my views: @login_required def one_cikan_button(self, **kwargs): pk = self.kwargs['pk'] print(pk) film = Movies.objects.get(pk=pk) try: film.featured = False film.save() return redirect('/headoffice/onecikanlar/') except Exception as e: return redirect('/headoffice/onecikanlar/') return redirect('/headoffice/onecikanlar/') My urls: path('onecikanlar/kaldir/<pk>/', views.one_cikan_button, name="onecikankaldir"), My template: <a href="/headoffice/onecikanlar/kaldir/{{obj.pk}}/" title="Sil"><i class="notika-icon notika-trash" style="font-size:14pt; color:black;"></i></a> My models: class Movies(models.Model): featured = models.BooleanField(default=False) How can I solve this? Or can I use UpdateView with custom settings? -
Django: How to log out a user using Javascript's window.confirm()
I am making a web app using Django/Python. There is a navigation at the top of the web app, and if a user clicks on the 'logout' link a pop-up window using Javascript's window.confirm() asks them if they are sure that they want to log out. I have the following in logout.js: function logout() { if(window.confirm("Are you you sure that you want to log out?")) { window.open("index.html"); } return; } If a user selects 'OK' in the pop-up that is displayed, I want the app to log the user out and display the home page of the app (represented by index.html). However, to log the user out I need to do this in views.py. I have the following code in views.py: def logoutUser(request): if request.POST: if request.POST.get("confirm-btn"): logout(request) return render(request, 'index.html') if request.POST.get("cancel-btn"): return redirect('/dashboard/') return render(request, 'logout.html') I have a page called logout.html which has two buttons, and if a user clicks the confirm button they are logged out and taken to the home page. However, I want a pop-up to be displayed instead. My question is, how can I connect the Javascript code for the logout pop-up with the backend code in views.py that deals with the user … -
Haystack/Whoosh convert string to bytes-like object? "Cannot use a string pattern on a bytes-like object" error
On my Django (2.2.7, Python 3.7) project, I use Haystack(2.8.1) and Whoosh(2.7.4) for fulltext search. When searching, I always get Cannot use a string pattern on a bytes-like object error. I know, in general, why this error happens, but I don't know hot to avoid it. I pass a proper string keyword to haystack/whoosh functions, but it gets probably converted to bytes-like object somewhere inside the above libraries. E.g. I give it a string somestring, but it becomes b'somestring' in the file "/usr/local/lib/python3.7/site-packages/haystack/inputs.py" in self.exact_match_re.findall(query_string) function. Local vars at that moment: __class__ <class 'haystack.inputs.AutoQuery'> query_obj <haystack.backends.whoosh_backend.WhooshSearchQuery object at 0x7fea4c19c550> query_string b'somestring' self <AutoQuery 'somestring'> The whole stack trace: ERROR 2019-11-23 01:17:51,136 middlewares 5013 140644284933888 http://www.my_project.loc/hledat?q=ATIKA&x=3&y=16 Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/haystack/views.py", line 51, in __call__ return self.create_response() File "/my_project/search/views.py", line 57, in create_response for item in self.results: File "/usr/local/lib/python3.7/site-packages/haystack/query.py", line 154, in _manual_iter if not self._fill_cache(current_position, current_position + ITERATOR_LOAD_PER_QUERY): File "/usr/local/lib/python3.7/site-packages/haystack/query.py", line 231, in _fill_cache results = self.query.get_results(**kwargs) File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 638, in get_results self.run(**kwargs) File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 550, in run final_query = self.build_query() File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 693, in build_query final_query = self.query_filter.as_query_string(self.build_query_fragment) File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 381, in … -
How can a result from one class can be used in another class. I'm trying to user my SearchResultsView result as the author in PostCreateView
class SearchResultsView(ListView): model = User template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.object_list return super().form_valid(form) -
why am I not able to get a dropdown on my html template?
I have added a screenshot of how my html template looks in the browser. I'm not getting a dropdown in my form for Name label. I am getting the desired output(dropdown) in my model. I have already gone through the official documentation of Django, but was not able to find a solution. I am new to Django.what should I do? models.py from django.db import models class Record(models.Model): CHOICES = ( ('john', 'JOHN'), ('sam', 'SAM'), ('lucy', 'LUCY') ) date = models.DateTimeField(auto_now_add = True) emp_name = models.CharField(max_length=10, choices=CHOICES) amount = models.PositiveIntegerField(default=0) views.py from django.http import HttpResponse from django.views.generic import FormView from .models import Record from .forms import RecordForm class home(FormView): template_name = 'myapp/home.html' form_class = RecordForm def form_valid(self, form): return HttpResponse("Sweeeeeet.") forms.py from django import forms from .models import Record CHOICES = [ ('john', 'JOHN'), ('sam', 'SAM'), ('lucy', 'LUCY') ] class RecordForm(forms.ModelForm): name = forms.CharField(label='Name', widget=forms.Select(choices=CHOICES)) amount = forms.IntegerField() class Meta: model = Record fields = '__all__' urls.py from django.urls import path from django.contrib.auth import views as auth_views from .views import EmployeeListView, home from . import views urlpatterns = [ path('', home.as_view(),name='home'), path('logout/', auth_views.LogoutView.as_view(template_name = 'myapp/logout.html'), name='home-logout'), path('profile/', views.profile, name='home-profile'), path('employee/', EmployeeListView.as_view(), name='home-employee'), ] home.html <style type="text/css"> .form-container { border-radius: 10px; padding: … -
i want to must be require login by the user in django
i am beginner in django and i want to that the user must be login if user want to see the detail of the property [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/MXhbW.jpg View Detail apply restriction on this View detail button that if user not login then user can't see the property details -
Django rest framework. Return multiple models nested
I'm trying to create a combined viewset that displays data in a nested format from three django models. I'm receiving an error when I try to return the viewset. Got AttributeError when attempting to get a value for field `runner` on serializer `CombinedSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Runner` instance. Original exception text was: 'Runner' object has no attribute 'runner'. class CombinedSerializer(serializers.Serializer): event = EventSerializer(many=True) market = MarketSerializer(many=True) runner = RunnerSerializer(many=True) class Meta: fields = ('event' , 'market', 'runner') class CombinedViewSet(mixins.ListModelMixin, viewsets.GenericViewSet, mixins.RetrieveModelMixin): queryset = Runner.objects.all() serializer_class = CombinedSerializer For some reason when I remove runner from the serializer Event and Market display in my api in nested format. When I add Runner I get the above error. How can I fix this and display all three in my API? -
CORS is not enabling in django backend?
I'm trying to enable CORS for my django project which is interacting with ionic on frontend.When i send a post request to django backend, browser shows following error message:- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:3000/api/customer. (Reason: CORS header 'Access-Control-Allow-Origin' missing). While console shows options request method instead of Post .I enabled my custom middleware for handling CORS which is:- class CorsMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response["Access-Control-Allow-Origin"] = "*" return response But it still keeps showing same error.My ionic server is running at http://127.0.0.1:8100 while django backend is running on http://127.0.0.1:3000 -
i try ajax partial refresh html,but it does't work
I'm trying to load the page locally with Ajax, but the following code doesn't work. My idea is to pass the 'MSG' information of 'views' to Ajax and refresh the page locally without loading the entire page. If the input does not meet the requirements, the front end rejects the submission and gives a prompt message. views.py def login(request): hashkey = CaptchaStore.generate_key() image_url = captcha_image_url(hashkey) captcha = {'image_url': image_url, 'hashkey':hashkey} if request.POST: username = request.POST['username'] password = request.POST['password'] key = request.POST['hashkey'] capt = request.POST['captcha'] if username and password: if captchautil.is_valid(capt, key): user = auth.authenticate(username=username, password=password) human = True if user: auth.login(request, user) return redirect('/') else: msg = '用户名密码错误' else: msg = '请输入正确的验证码' else: msg = '请输入用户名与密码' return render(request, 'login.html', locals()) return render(request, 'login.html', locals()) login.html {% block content %} <div id="login" class="login"> <form action="/login/" method="post" class="navbar-form"> {% csrf_token %} <div id="input" class="form-group"> <input type="username" name="username" class="form-control" placeholder="请输入手机号或邮箱" id='user' title="请输入手机号或邮箱"><br><br> <input type="password" name="password" class="form-control" placeholder="密码" id='pwd' title="请输入密码"><br><br> <img src="{{image_url}}" alt='验证码' id='id_captcha'> <span><a href="#" id="refresh_captcha">看不清验证码?刷新</a></span> <br> <input id='captcha' placeholder="请输入验证码" name="captcha" class="form-control" type="text" data-toggle="tooltip" data-placement="bottom" title="请输入验证码"> <input value="{{hashkey}}" type="hidden" name="hashkey" id='hashkey'> <br> <button type="submit" class="btn btn-primary form-control" name="click" id='click'>登录</button> </div> <p style="margin-left: auto;" id="msg">{{ msg }}</p></div> </form> <div style="margin-left: 3%"> <span> <a href="">忘记密码了?</a> … -
Run Celery Interval task every 95/100/105 minutes
I use django_celery_beat and try to set up tasks to run every 95/100/105/120 minutes. Are these settings correct? On what time it will be run? -
'Section4' object has no attribute 'user'
I am trying to customize the default django admin and add the total field in the footer. I don't know if this is the correct way to do. @admin.register(Section4, site=admin_site) class Section4Admin(ReadOnlyParamsMixin, admin.ModelAdmin): change_list_template = 'admin/section4/section4/total_review_count.html' def get_total(self, user): total_n = CarePlanNeed.objects.all().count() td = datetime.timedelta(29) last_review = timezone.now() - td total_review_upto_date = len(Counter([p['latest'] for p in self.get_careplan(user).values('resident', 'aspect_of_life').annotate( latest=Max('history_date')).filter(latest__gt=last_review).order_by() if p['latest']+td>timezone.now()])) total_review_tobe_updated = len(Counter([p['latest'] for p in self.get_careplan(user).values('resident', 'aspect_of_life').annotate( latest=Max('history_date')).filter(latest__gt=last_review).order_by() if p['latest']+td<timezone.now()])) total_review_added = self.get_careplan(user).values('resident', 'aspect_of_life') total_review_tobe_added = total_n * 17 - len(total_review_added) return total_review_upto_date, total_review_tobe_updated, total_review_tobe_added def changelist_view(self, request, extra_context=None): total_review_upto_date, total_review_tobe_updated, total_review_tobe_added = self.get_total(request.user) my_context = { 'total_review_upto_date': total_review_upto_date, 'total_review_tobe_updated': total_review_tobe_updated, 'total_review_tobe_added': total_review_tobe_added } return super(Section4Admin, self).changelist_view(request, extra_context=my_context) total_review_count.html: {% extends "admin/section4/section4/change_list.html" %} {% load i18n admin_urls %} {% block result_list %} {{ block.super }} <footer style="color:blue;"> <p >The total review upto date: {{ total_review_upto_date}}<br> </p> <p>The total review to be updated: {{ total_review_tobe_updated}}<br></p> <p>Total review to be added : {{ total_review_tobe_added }}</p> </footer> <p> {{ user }}</p> {% endblock %} Error : AttributeError at /section4/section4/ 'Section4' object has no attribute 'user' home/bishwa/PycharmProjects/johnson/section4/admin.py in changelist_view, line 430 I actually wanted to add the total_review_tobe_updated, total_review_tobe_updated, total_review_tobe_added in the footer of the list_view of django admin. -
How to render Django model form drop down manually in the template?
Here is my model form class CategoryCreateForm(forms.ModelForm): class Meta: model = Category fields = [ 'nature', 'name', 'description', ] The field nature is a foreign field. I know I can render this field in the template using {{ form.nature }} but I would like to render the form manually without the help of Django or crispy forms. I have managed to do so for the other fields but don't know how to do it for a select field of a model form. I am looking for a solution similar to the following <select class="custom-select custom-select-sm{% if form.nature.errors %} is-invalid{% endif %}" id="{{ form.nature.id_for_label }}" name="{{ form.nature.html_name }}"> {% for nature in form.nature.objects %} <option value="{{ nature.id }}">{{ nature.name }}</option> {% endfor %} </select> -
Normalize Mobile Numbers using Python
I have a string of digits, how can I format this as a mobile number? I am trying to create a python def that takes a string and normalizes them into a format I can use. I am trying to remove all symbols and spaces and just leave the numbers. As well as add +98 to the beginning Some trivial examples: 916 222 3344 > +989162223344 09375554433 > +989375554433 +98 912 999 88 77 > +989129998877 -
How to change the value of an href attribute with JS?
I want to change the value of the href attributes of the anchor tags on my website when the user clicks a button. In particular I want to change the value of a GET parameter in this url. (If you are not familiar with the {% url 'select_question' %} and {{ subcategory.name }} tags just ignore them they are Django template tags.) The text on the button changes but the url in the href doesn't. Mode is always "unsolved". What am I doing wrong? Thanks! <button id="changeModeBtn" class="btn btn-primary" type="button" name="button" onclick="change()">Unsolved Questions</button> <a class="question_link" href="{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=unsolved">{{ subcategory.name }}</a> <script type="text/javascript"> function change(){ var btn = document.getElementById("changeModeBtn"); var link = document.getElementsByClassName("question_link"); if (btn.textContent=="Unsolved Questions") { btn.textContent="Solved Questions"; link.setAttribute("href", "{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=solved"); } else if (btn.textContent=="Solved Questions") { btn.textContent="All Questions"; link.setAttribute("href", "{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=all"); } else { btn.textContent="Unsolved Questions"; link.setAttribute("href", "{% url 'select_question' %}?subcategory={{ subcategory.slug }}&mode=unsolved"); } } </script> -
Groupby time intervals
I have a model with a DateTimeField and I want to run some queries so I can get sum of other fields, grouped by specific time intervals like: 5min, 10min, 1hr, 3hr and etc. I also need the intervals begining and end. count = models.IntegerField(null=False) time = models.DateTimeField(null=False) -
I want to update my student record in the database, but its not working
The first problem is that when the update form is appeared date-of-birth field is not getting data from the database. The Second thing is that whenever i click on the submit button it will not update my values in the databse. The Third thing is after i click on the update or submit button it will automatically redirect to me in the insertion form which i don't want to be there (and i not even give the link or render to that page and i don't understand what is going on here beacause instead of it it will need to show my editstudent.html page not insertstudent.html page) and YES!!! MY UPDATE IS ALSO NOT WORKING...... PLEASE HELP ME OUT AT THIS....... editstudent.html PAGE:- {% extends 'student/index.html' %} {% block content %} <div class="col-md-6"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Update Student Here</h3> </div> <!-- /.card-header --> <!-- form start --> <form action="{% url 'studentinsert' %}" role="form" method="POST"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">Student ID</label> <input type="text" class="form-control" name="id" placeholder="Enter Student ID" value="{{ student.sid }}"> </div> <div class="form-group"> <label for="exampleInputPassword1">First Name</label> <input type="text" class="form-control" name="firstname" placeholder="Enter First Name" value="{{ student.first_Name }}"> </div> <div …