Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to log, then send single email using Django Mailer?
So I have this function for sending messages queued by Django Mailer: from django.core import management #send queued emails with django-mailer. def email_now(): management.call_command('send_mail') Then I overwrite the Django PasswordResetForm's send_mail() method: def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): subject = loader.render_to_string(subject_template_name, context) subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') #log the message mailer.send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [to_email]) #then send via management command email_now() So, primarily I'm wondering if the final 2 lines, and using email_now() is an acceptable way to do this. Also, wondering if there's a way to implement this using the email_message object. Thank you. -
I am looking for a solution concerning the datefield
how to add the number of days to recover from the computer example: January 12, 2021 +10 = January 22, 2021 help me?un -
Optional parameters passed in a Django URL
Sorry if this is complete noob question, I just can't seem to get a straight answer with this very simple concept. In Django (Django Rest Framework actually, but I assume it would be the same), how do I pass optional parameters in the URL? Based on all the info I could gather, I have a urls.py that goes like this: # urls.py from .views import (HistoryIndex, from django.urls import re_path urlpatterns = [ re_path(r'^history/(?P<limit>)/$', HistoryIndex.as_view(), name='history_index'), ] The idea is to pass in a optional parameter (using the ? & syntax), limit, to limit the results passed back: # views.py from rest_framework.views import APIView from rest_framework.response import Response from .models import EventHistory from .serializers import class HistoryIndex(APIView): def get(self, request, **kwargs): user = request.user limit = int(kwargs['limit']) histories = EventHistory.objects.filter(user=user).order_by('-updated_at')[:limit] history_index = [ HistorySerializer(history).data for history in histories ] return Response(history_index) I'd like to be able to hit the endpoint like so: http://localhost:8000/history/ or http://localhost:8000/history/?limit=10 but I can't even get as far as my view. The django browsable API shows a 404, but in its list of possible endpoints, it includes ... ^history/(?P<pk>[\w-]+)/$ [name='history_index'] ... as an available endpoint. What am I missing? I'm sure it's something trivial but I … -
Custom errors in forms
I'm trying to make a custom error in a form in a class based view (CreateView). I have read the documentation and it is supposed that with the "clean()" function you can add errors, but my problem is that the form is submitted even when the error should appear. this is my class: class RecommendationCreateView(LoginRequiredMixin, CreateView): model = Recommendation template_name = 'recommendation/recommendation_new.html' form_class = NewPostForm success_url = reverse_lazy('home') def get_form_kwargs(self): """ Passes the request object to the form class. This is necessary to only display members that belong to a given user""" kwargs = super(RecommendationCreateView, self).get_form_kwargs() kwargs['request'] = self.request.user return kwargs def post(self, request): super(RecommendationCreateView, self).post(request) to_user=request.POST['to_user'] to_user = user_model.objects.filter(id = to_user).get() hobby = request.POST['hobby'] hobby = Hobby.objects.filter(id = hobby).get() recom = Recommendation.objects.create(from_user=request.user, to_user=to_user, hobby=hobby, text=request.POST['text']) recom.save() return redirect('recommendations') this is my form: class NewPostForm(forms.ModelForm): def clean(self): super(NewPostForm, self).clean() to_user = self.cleaned_data.get('to_user') to_user = user_model.objects.filter(username=to_user.username).get() if to_user.username == 'NAME': self._errors['to_user'] = 'Custom error to display' return self.cleaned_data class Meta: model = Recommendation fields = ('from_user', 'to_user', 'hobby', 'text') widgets = {'from_user': forms.HiddenInput()} this is my model: class Recommendation(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False ) from_user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="recommendation_request_sent", ) to_user = … -
Django Q query with string generated query is giving error
I am trying to create a Django Q query, with any number or inputs having OR condition. E.g. there can be any number of trends from a list of 5 trends When I hardcode the query using two trends, it works fine: data.objects.filter(Q(trend__trend='Investment') | Q(trend__trend='Collaboration')) However, when I create a string of Q queries with n number of trends qString = "Q(trend__trend='Investment') | Q(trend__trend='Collaboration')" ... and pass it as data.objects.filter(qString)... it throws the following error: ValueError at /trend=Investment|Collaboration too many values to unpack (expected 2) I don't know how many trends would a user select, so have to make the query dynamic. What am I doing wrong? TIA -
Django user login session not accessible when I try to fetch it from my React frontend
I have a django app running. I have created a login_status view under my API that returns JSON:true/false if I am logged in or not. When I load this in my browser it works fine. When my React app tries to fetch this same page, Django ALWAYS returns false. Somehow my login session is invisible. How do I fix this? Note: My React app & Django app are running on two different ports. I have enabled CORS by installing django-cors-headers. I am not using the React REST Framework, just plain Django. here is my front end code: import React, {useState, useEffect} from 'react'; import ReactDOM from 'react-dom' import Modal from 'react-modal' import Vim from './Vim'; import './Main.css'; import './modal.css'; Modal.setAppElement('#root') function Main():JSX.Element { const [postId,updatePostId] = useState<number|null>(null) const [content, updateContent] = useState<string>('default text'); const [auth, updateAuth] = useState<boolean>(false) const [authModalIsOpen, setAuthModal] = useState(false) const [username, setUsername] = useState('') const [password, setPassword] = useState('') const apiUrl = 'http://127.0.0.1:8000/' function openAuthModal(){ setAuthModal(true) } function closeAuthModal(){ if(auth){ setAuthModal(false) } } function get_api(path:string){ return fetch(apiUrl+path) .then(res=>res.json()) .then(result=>result) } useEffect(()=>{ if(postId){ // Detect change in PostID & go download it. // Ignore if we are coming from null->number fetch(apiUrl+'get_post/'+postId) .then(res=>res.json()) } },[postId]) useEffect(()=>{ // if … -
Django register user extending djoser view with custom view
I'm trying to use djoser. I need to customize the registration flow. To have this I'm trying to create my custom view extending the Djoser view. But something seems wrong. I'm trying in this way: from djoser.views import UserViewSet class SignUpView(UserViewSet): def perform_create(self, serializer): super(SignUpView, self).perform_create(serializer) # My custom logic into my app urls file: urlpatterns = [ url(r'^auth/signup$', views.SignUpView.as_view(), name='sign-up'), ] I'm not able to call my custom view. If the called url is correct, using the POST method, I'm obtaining this error: CSRF verification failed. Request aborted. I stared from this link: Djoser Adjustment But, is this still correct for djoser 2.1.0 version? -
django - dash app ImportError: cannot import name 'Dash' from 'dash'
There's actually no useful solution online. I get this error : Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.8/site-packages/django_plotly_dash/__init__.py", line 31, in <module> from .dash_wrapper import DjangoDash File "/app/.heroku/python/lib/python3.8/site-packages/django_plotly_dash/dash_wrapper.py", line 32, in <module> from dash import Dash ImportError: cannot import name 'Dash' from 'dash' (/app/.heroku/python/lib/python3.8/site-packages/dash/__init__.py) while pushing an app that contains dash components to heroku. It seems something is wrong with paths here. It happend during collectstatic phase. … -
How to deal with "Django error - Matching query does not exist" without breaking your code?
I came across this error where I was trying to retrieve a user using a query from the database. Below was my initial code which wanted to retrieve a user from a model called Order with the object writer def assigned(request): orders = Order.objects.get(writer=request.user) if orders: return render(request, 'mainapp/assigned.html', {'orders': orders}) else: return render (request, 'mainapp/assigned.html') However, after running my page I got a DoesNotExist: Comment matching query does not exist Error. This was not the correct way to handle this. -
Django project doesn't 'see' Python modules installed with Pipenv
I am just starting out with Django and I have this problem. The files are written in the Pipfile, for future reference, but my Django project cannot make use of the actual modules. I have to go to the folder where pipenv install them: C:\Users\my_name.virtualenvs\my_folder and I usually copy them from there and paste them in my working folder. That kind of defeats the purpose, and its not very convinient. How can I solve this? -
Django-admin AttributeError:
I've just started learning how to use django for some school projects.I installed django with pip but when I try to start a project with django-admin startproject abc I get error: File "c:\users\user\.virtualenvs\project-gnrbo21b\lib\site-packages\django\utils\crypto.py", line 74, in <genexpr> return ''.join(secrets.choice(allowed_chars) for i in range(length)) AttributeError: module 'secrets' has no attribute 'choice' I can't find any solutions on internet, any ideas ? Thank you -
Is there a way to include the ForeignKeys from other models in Django?
I'm creating a simpel website in Django (latest) that does the following: In the admin panel I can create a company and a team, there's a third model that contains the forms. In models.py: class Company(models.Model): companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) companyname = models.CharField(max_length=254) ....some other fields.... class Team(models.Model): teamId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) teamname = models.CharField(max_length=254) company = models.ForeignKey(Company, related_name='teams', on_delete=models.CASCADE) ....some other fields.... class UserForm(models.Model): UserForm_id = models.AutoField(primary_key=True) UserForm_company = models.ForeignKey(Bedrijf, related_name='UserForm_company', on_delete=models.CASCADE, null=False) UserForm_team = models.ForeignKey(Team, related_name='UserForm_team', on_delete=models.CASCADE, null=False) ....some other fields.... In views.py: class UserFormCreateView(CreateView): context_object_name = 'form_UserForm' form_class = UserFormName template_name = 'app/form.html' success_url = reverse_lazy('') #leads to index.html model = models.UserForm In the urlpatterns (urls.py) I include the following: (I have included the slugs in my models and views) urlpatterns = [ ..... path('<slug:urlCompany>/<slug:urlTeam>/<slug:urlForms>', views.UserFormCreateView.as_view(), name='UserForm'), ] Individual members are not registered. I just have multiple companies and each can have multiple teams. Teams would navigate to a url similar to: app/1239a36e-9694-42c3-a6f8-e058db218feb/b28819e0-5d97-4c3f-97aa-9d6cb55a0b07/userform which corresponds with app/urlCompany/urlTeam/urlForm So far so good. What I would like to have is that when the form is submitted, the companyname and teamname is included automatically. When I test the form, these fields (in the adminpanel) remain empty. Is there … -
Cart transfer between sites [closed]
Python/Django: Im trying to build something that would allow a user to make a cart on my site and then redirect that user to the e-commerce site where the basket is from. My problem is that I dont know how to transfer the whole basket to the e-commerce site. Could you please let me know what do you think? ( also the e-commerce site in question does not have an API, or an affiliate program I can work with )Thank you ! -
ProgrammingError at /admin/order/order/ relation "order_order" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "order_order"
I'm working with django rest framework and I have a app named order. I wanted to change my order logic and I changed order app's models. but when I want to open order and order_item models in admin panel I have this error: ProgrammingError at /admin/order/order/ relation "order_order" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "order_order" and also when i run migrate command it doesn't migrate well and doesn't create the order and OrderItem tabels in the database. I'm using postgres db. there is my code: models: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) # products = models.ManyToManyField(OrderItem) created_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.full_name def total_price(self): total = 0 for order_item in self.products.all(): total += order_item.get_final_price() return total class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='products') ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.product.name}" def get_total_item_price(self): return self.quantity * self.product.price def get_total_discount_item_price(self): return self.quantity * self.product.discount def get_amount_saved(self): return self.get_total_item_price() - self.get_total_discount_item_price() def get_final_price(self): if self.product.discount: return self.get_total_discount_item_price() return self.get_total_item_price() admin: class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'created_date', 'total_price' ] list_display_links = ['user', ] … -
sum values from database in DJANGO templatetags
''' {% for d in pointss %} {{ d.points }} {% endfor %} ''' I have such a recurrence i know you need to use a ‘sum’ filter for this ''' from django import template register = template.Library() def summing(value): return register.filter("sum", summing) ''' I don't know how to use it here -
Django - how can i return a json response error?
I created a simple API endpoint using Django Rest Framework and i created a very basic logic where if the user doesn't provide any filter, the API needs to return a custom error, something like {'error': 'no parameter provided'}. The problem with my code is that i keep getting this error: object of type 'JsonResponse' has no len(). Here is my code: class WS_View(viewsets.ModelViewSet): pagination_class = StandardResultsSetPagination http_method_names = ['get'] serializer_class = WS_Serializer def get_queryset(self): valid_filters = { ... } filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()} #If there are filters, execute the query if len(filters) > 0: queryset = WS.objects.filter(**filters) return queryset #If there isn't any filter, return an error else: return JsonResponse({"error": "no parameter required"}) Now i know i'm getting this error because i'm supposed to return a Queryset, and JsonResponse is not a Queryset of course, but i don't know how to actually solve this. Any advice is appreciated! -
Filtering by category
I want to filter by categories. I have a lot of categories and they are translated into 3 languages. They also can be added dynamically. Now I am filtering by primary key and it seems to work fine, but I need to have the category 'All' which will be selected by default. How can I avoid hardcode values for this category? def autocomplete(request): if 'term' in request.GET: term = request.GET.get('term') qs = Article.objects.all() if 'category_id' in request.GET: category_id = request.GET.get('category_id') # 4 stands for all category if category_id != '4': qs = qs.filter(category__pk=category_id) qs = qs.filter(name__istartswith=term) names = [] for article in qs: names.append(article.name) return JsonResponse(names, safe=False) return render(request, 'home.html') Thank you! -
How do I use django models.py classes in my own python programs?
So, I want to make some changes in the database using python outsite Django, but I am unable to. I'm trying to import the model from models.py but i'm unable to. from models import NumberInfo There is this error: Traceback (most recent call last): File "/home/sagan/p/matematika/matematika/mnumbers/prime_insert.py", line 1, in <module> from models import NumberInfo File "/home/sagan/p/matematika/matematika/mnumbers/models.py", line 5, in <module> class NumberInfo(models.Model): File "/home/sagan/.local/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/sagan/.local/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/sagan/.local/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/home/sagan/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/sagan/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/sagan/.local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'matematika'``` -
A clear resource to understand django-helpdesk
I'm not sure if this is a valid question for this community, but I've linked my django website with django-helpdesk as its ticketing system, I'm facing an issue with uploading attachments, as they are not being saved, and wanted to read about the right way to upload an attachment, I've only found this documentation link https://django-helpdesk.readthedocs.io/en/0.2.x/install.html which explains absolutely nothing. Is there another resource I'm missing?? -
AttributeError at /admin/blog/post 'list' object has no attribute 'lower'
I have a simple blog code in Django , I write the error and my codes: there is my codes models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title views.py from django.views.generic import ListView from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' urls.py from django.urls import path from .views import BlogListView urlpatterns = [ path('', BlogListView.as_view(), name= 'home') ] and home.html {% extends 'base.html' %} {% block content %} {% for post in object_list %} <div class="post-entry"> <h2><a href="">{{ post.title }}</a></h2> <p>{{ post.body }}</p> </div> {% endfor %} {% endblock content %} There is Error message after running code: AttributeError at /admin/blog/post 'list' object has no attribute 'lower' Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/post Django Version: 3.1.5 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'lower' Exception Location: C:\Users\nilaroz\.virtualenvs\blog-Keg_c4F1\lib\site-packages\django\utils\http.py, line 295, in is_same_domain Python Executable: C:\Users\nilaroz\.virtualenvs\blog-Keg_c4F1\Scripts\python.exe Python Version: 3.8.6 Python Path: ['D:\\MyDjangoProject\\blog', 'c:\\program files (x86)\\python38-32\\python38.zip', 'c:\\program files (x86)\\python38-32\\DLLs', 'c:\\program files (x86)\\python38-32\\lib', 'c:\\program files (x86)\\python38-32', 'C:\\Users\\nilaroz\\.virtualenvs\\blog-Keg_c4F1', 'C:\\Users\\nilaroz\\.virtualenvs\\blog-Keg_c4F1\\lib\\site-packages'] Server time: Sun, 31 Jan 2021 19:53:08 +0000 why? I don't make any list! what's mean "'list' object has no attribute 'lower'"? I think … -
Dynamic urls for hierarchy tree on django
I would like to build a hierarchy tree of content with no depth limits. models.py: class Element(models.Model): name = models.CharField(verbose_name="Nombre", max_length=250) parent = models.ForeignKey("self", on_delete=models.CASCADE) slug = models.TextField(verbose_name="Slug", blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Element, self).save(*args, **kwargs) .../element_n-1/element_n/element_n+1/... How do i have to write the path in urls.py to get this functionality? Thanks in advanced. -
Django modal forms with ajax tables
I am using modal forms with django ajax tables: https://pypi.org/project/django-bootstrap-modal-forms/ https://pypi.org/project/django-ajax-tables/ How can I update data asychronously by the modal form? Here is some example code: Registered Views: def index(request): return render(request, 'proto/index.html') class BookTableView(View): model = Books my_table = BooksTable def get(self, request): data = self.model.objects.all() #filtering table = self.my_table(data) RequestConfig(request, paginate = {"per_page": 6, "paginator_class": LazyPaginator}).configure(table) return HttpResponse(table.as_html(request)) class BookUpdateView(BSModalUpdateView): model = Books template_name = 'proto/books/update_book.html' form_class = BookModelForm success_message = 'Success: Book was updated.' success_url = reverse_lazy('index') Table: class BooksTable(tables.Table): column1 = tables.TemplateColumn(verbose_name='Read', template_name='proto/columns/column1.html', orderable=False) column2 = tables.TemplateColumn(verbose_name='Update', template_name='proto/columns/column2.html', orderable=False) class Meta: model = Books Column2 html template button <button type="button" class="update-book btn btn-sm btn-primary" data-form-url="{% url 'update_book' record.id %}" onclick="updateBookModalForm()"> <span class="fa fa-pencil"></span> Close update buttons on update_book.html modal form <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="update_books_id('', '/proto/books')"> <span aria-hidden="true">&times;</span> </button> ... <div class="modal-footer"> <button type="button" class="submit-btn btn btn-primary">Update</button> </div> Calling ajax tables on index.html and javascript for modals : ... <div class="col-12 mb-3"> {% ajax_table "books_id" "books" %} </div> <script> function updateBookModalForm() { $(".update-book").each(function () { $(this).modalForm({ formURL: $(this).data("form-url"), asyncUpdate: true, asyncSettings: { closeOnSubmit: false, successMessage: asyncSuccessMessageUpdate, dataUrl: "books/", dataElementId: "#books-table", dataKey: "table", addModalFormFunction: updateBookModalForm } }); }); } updateBookModalForm(); </script> Surprisingly this works and appears … -
xhtml2pdf heroku can't load font
I'm creating a PDF based on xhtml2pdf (Django). In my localhost I need to provide absolute path for font 'D:\user\folder1\folder2\project\static\fonts\DejaVuSansMono.ttf' because reference of {% static 'fonts/DejaVuSansMono.ttf' %} doesn't work. My font isn't loading. If i provide absolute path, it is working fine. But it isn't working when I publish my app on Heroku. I don't know how to do. I know that the xhtml2pdf has reference only on xhtmlpdf catalog (please correct me if I'm wrong). What should I do that the font will be working on localhost and Heroku too? I've tried to do something like that but it isn't working as well. base_url = "{0}://{1}{2}".format(request.scheme, request.get_host(), request.path) My app in heroku return only /static/fonts/DejaVuSansMono.ttf -
Create a nested Form in Django
I've been pondering a lot, but I'm still not sure how best to implement it. I want to get a nested Formular(a real Formular, not a Django Form) in Django. What I mean with nested is, that there are categorys and if the user ticks the boxes there appear subcategorys and so on. The filling of the form can be over several pages. I'm happy about every inspiration, it doesn't have to be full guide. -
How to filtering in Django use specific user
I try to filtering django some specific user. I try with list but it not working. Do you have any solution. list = ['bill gates','elon musk','aamir khan','larry page'] allPosts = Post.objects.filter(author=list) When I change list filter can work dynamically