Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i generate pdf from html code and pdf file along with sendgrid API V3 uisng python django
i have a variable which contain the template code like template = ''' <html> <div> Hello world </div> </html> ''' i want to generate a pdf and attach file with the sendgrid code below import os from sendgrid import SendGridAPIClient template = ''' <html> <div> Hello world </div> </html> message = { 'personalizations': [ { 'to': [ { 'email': 'test@example.com' } ], 'subject': 'Sending with Twilio SendGrid is Fun' } ], 'from': { 'email': 'test@example.com' }, 'content': [ { 'type': 'text/plain', 'value': template } ] } try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(str(e)) currently i have created a template of invoice and now i want to know how to generate a pdf with that template and attach that pdf file with the email my template code is too lengthy so im not including it here -
Call function when click function django
I want to call my python function, when user clicked button "submit" on this page http://junjob.ru/accounts/login/ How can I do it? My code: views.py class BBLoginView(LoginView): template_name = 'vacancy_list/login.html' class BBLogoutView(LoginRequiredMixin, LogoutView): template_name = 'vacancy_list/vacancy_list.html' next_page = reverse_lazy('vacancy_list') urls.py urlpatterns = [ path('accounts/login/', BBLoginView.as_view(), name='login'), path('accounts/profile/', profile, name='profile'), path('accounts/logout/', BBLogoutView.as_view(), name='logout'), ... login.html {% block content %} <div class="container" style="margin-top:10px"> <h2>Login</h2> {% if user.is_authenticated %} <p>You are already registered</p> {% else %} <form method="post"> {% csrf_token %} {% bootstrap_form form layout='horizontal' %} <input type="hidden" name="next" value="{{ next }}"> {% buttons submit="Submit" %} {% endbuttons %} </form> {% endif %} </div> {% endblock %} -
Django template rendering HTML elements in the wrong order
This is a Django beginner question (or possibly just an HTML problem). I'm rendering a very simple HTML page with a template (I'll make it look nice later). It has two divs, each containing a header and a table. If I print the rendered content in my view, it looks right, but the HTML delivered to the browser has both headings, then both tables. Template <!doctype html> <html style=\"font-family:Helvetica\> <head> <meta charset="utf-8"> <title>Choir Database</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/choirdb.css' %}"> </head> <body> <!-- MAIN TABLE --> <div> <h1>{{ title1 }}</h1> {% if value_list1 %} <table style=\"width:25%;font-family:Helvetica\"> <tr/> {% for valuePair in value_list1 %} <tr><td>{{ valuePair.0 }}</td> <td>{{ valuePair.1 }}</td></tr> {% endfor %} <tr> <td><a href=\"..\">Home</a></td> {% else %} <p>No values found</p> {% endif %} </div> <!-- SECONDARY TABLE --> <div> <h2>{{ title2 }}</h2> {% if value_list2 %} <table style=\"width:25%;font-family:Helvetica\"> <tr/> {% for valuePair in value_list2 %} <tr><td>{{ valuePair.0 }}</td> <td>{{ valuePair.1 }}</td></tr> {% endfor %} <tr> <td><a href=\"..\">Home</a></td> {% else %} <p>No values found</p> {% endif %} </div> </body> </html> View context = { 'title1': 'Liturgy Detail', 'value_list1': nameValuePairsPiece, 'title2': 'Laudate Recommendations', 'value_list2': rec_details, } output = render(request, 'two_tables.html', context) print ("output is " … -
Why my slug related field shows users object(1) instead of suggested field name in Django?
I wrote an app named as credentials. models, serializers and views are : models.py : from django.db import models class Users(models.Model): username = models.CharField(max_length=20, blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('inserted_timestamp',) class UsersDetails(models.Model): user = models.ForeignKey( Users, related_name='id_user_details', on_delete=models.DO_NOTHING, ) user_title = models.CharField(max_length=30, blank=True) user_first_name = models.CharField(max_length=25, blank=True) user_last_name = models.CharField(max_length=40, blank=True) user_birthdate = models.DateField(blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) details_creator = models.ForeignKey( Users, related_name='dtlcreator_user_details', on_delete=models.DO_NOTHING, # default=1 ) class Meta: ordering = ('user_id',) class UsersPasswords(models.Model): user = models.ForeignKey( Users, related_name='id_user_password', on_delete=models.DO_NOTHING) salt = models.CharField(max_length=200, blank=True) pwdhash = models.CharField(max_length=200, blank=True) inserted_timestamp = models.DateTimeField(auto_now_add=True) pwd_creator = models.ForeignKey( Users, related_name='pwdcreator_user_details', on_delete=models.DO_NOTHING) class Meta: ordering = ('user_id',) Here is serializers.py : from rest_framework import serializers from credentials.models import Users from credentials.models import UsersDetails from credentials.models import UsersPasswords class UsersSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Users fields = ( 'url', 'pk', 'username', 'inserted_timestamp', ) class UsersDetailsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) details_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) class Meta: model = UsersDetails fields = ( 'url', 'pk', 'user', 'user_title', 'user_first_name', 'user_last_name', 'user_birthdate', 'inserted_timestamp', 'details_creator' ) class UsersPasswordsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username' ) pwd_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username' ) class Meta: model = UsersPasswords fields = ( 'pk', 'user', 'salt', 'pwdhash', 'inserted_timestamp', 'pwd_creator' ) … -
Django REST framework adding multiple default objects
I am creating an app for my School which lets you add Teachers/Subjects/lessons...basic school life managing app...I want to give the user a list of the most basic/common subjects. I know that you can assign a default value in Django Models... but that would only create one Object with all the subjects in it... Is there a way to create multiple default object when a new user is created ? Thanks in advance django==2.2 djangorestframework==3.9.2 note : the user should be able to edit the subject list later. -
Build Firebase google signin in Django
I am looking to integrate firebase auth google sign in with Django. But I am not getting a clear picture of how can I achieve it. As Pyrebase has an attribute sign_in_with_email_and_password but not any for Google SignIn. How will view and template be designed? -
django: adding custom permissions stopped working
I have a django project with multiple apps. In one of the apps when I add custom permissions to any model and run makemigration, the migration-file to add the permission is created. When I apply the migration I get no error messages but the permission isn't added to the auth_permission table. class Meta: app_label = 'my_app' permissions = ( ('test_perm', 'Testing'), ) I have tried doing the same in other apps and that works. I have also tried adding a column to the current app and that works as well. Anyone got any idea what it could be? I am running django 1.11.26 -
Pycharm identifies new Django test file as a unittest, not a django test
How do I tell pycharm that the new test file I created is a django test file, and not a unittest file? I have pycharm setup with a django project. I can run all django tests as django tests with the test runner. I created a new test file, wrote a simple unittest on it. The tests run fine with manage.py and with the run configuration for running all tests. But, when I try to run an individual test within the new test file from pycharm it fails because pycharm is trying to run it as a unittest instead of a django test. As shown in the screenshots below, pycharm considers this new file a unittest file, not a django test file. Yet both files are in the same directory, both implement a class that extends Unittest, and both have tests. -
display data in html from django
I tried to display the data (the result return back from upload_file in views.py) in HTML from django, but it didn't show anything after clicking submit button, only jump back to the initial ui. undex.html <!DOCTYPE html> <head> <title>Detect Pothole</title> </head> <body> <p>upload image</p> <form method="post" enctype="multipart/form-data">{% csrf_token %} <input type="file" name="img" accept="image/*" onchange="loadFile(event)"></input> <img id="output"/> <script> <!--view selected image --> var loadFile = function(event) { var output = document.getElementById('output'); output.src = URL.createObjectURL(event.target.files[0]); }; </script> <input method='POST' type="Submit" name="submit" value="submut"></input> </form> {% if submitbutton == "Submit" %} {% for res in result %} {{res}} {% endfor %} {% endif %} </body> </html> view.py def upload_file(request): submitbutton= request.POST.get("submit") if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['img']) result=process('a.png') ## will return 0 or 1 print(result) context= {'form': form, 'submitbutton': submitbutton,'result':result} return render(request, 'index.html', context) else: form = UploadFileForm() return render(request, 'ui.html', {'form': form}) -
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?