Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Page not found (404) when posting form data
I am trying to create a form to submit a blog post on an author detail page, so that the blog post will automatically use the current author as its "blog_author" foreign key. The Django docs recommended using 1 parent view and 2 subviews to handle get and post respectively (https://docs.djangoproject.com/en/3.0/topics/class-based-views/mixins/). The page renders fine with the get, but the post gives me an error reading "Page not found (404) - no blog post found matching the query." The exception is raised by my parent view (blog.views.AuthorDetail), but there is no traceback. Here are my views: class BlogAuthorDetailView(generic.DetailView): model = BlogAuthor def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = BlogSubmitForm() return context class BlogSubmit(SingleObjectMixin, FormView): template_name = 'blogauthor_detail.html' form_class = BlogSubmitForm model = BlogPost def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() #Should I be overriding form_valid() to use the line above? Not sure if I'm doing my data #handling in the right place return super().post(request, *args, **kwargs) def form_valid(self, form): blogpost = form.save(commit=False) blogpost.blog_author = self.object blogpost.save() return redirect('blog_author-detail', pk=self.object.id) class AuthorDetail(View): def get(self, request, *args, **kwargs): view = BlogAuthorDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = BlogSubmit.as_view() return view(request, … -
Django: Official recommendations for using try - except (aka try catch exception handling)
In Django specifically, what are the recommendations for using try/except, for example, in a view or similar area of the code? I could not find an official document on best practices & performance considerations for Django specifically. For context, if an exception is raised in a view without a try-except, the error and some trace is reported in the log and the Django server keeps running. Now, there are some times when a try-except is necessary for logic. There are other times when it's not- the best course of action is to raise it anyhow and leave the function. Technically, almost every line of code could be a try-except. In practise, that code gets very long, and rather than having 1 central way to deal with raised exceptions, it creates lots of copying and pasting across the dev team which can result in consistency issues/cat herding. What are the official recommendations, and failing that, what rules of thumb are there? FYI, using Python3. -
Web Socket through connection handshake error, status: 200 on production while on local its working fine, Django + Angular
I'm trying to set up a web-socket for real-time notification. My Frontend is Angular & Backend is Django using docker for both backend and frontend. On the local machine, it's working perfectly fine. Connection successfully establish & signal can transmit/broadcast. But when I deployed it on the server it through error 200 Here is the backend connection code: main -> routers.py application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( sog.notification.routing.websocket_urlpatterns ) ), }) app -> routers.py websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer ) ] consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] #usename self.room_group_name = self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) Here is the Frontend code: While I'm on local machine In Frontend I wrote WEB-SOCKET URL: wss://localhost:8000/ws/chat/notification_'+ authService.getUsername() For Server I used: wss://domain.com/ws/chat/notification_'+ authService.getUsername() websocket.service.ts import { Injectable } from "@angular/core"; import * as Rx from "rxjs/Rx"; @Injectable() export class WebsocketService { constructor() {} private subject: Rx.Subject<MessageEvent>; public connect(url): Rx.Subject<MessageEvent> { if (!this.subject) { this.subject = this.create(url); console.log("Successfully connected: " … -
How to multiply 2 fields and save the result to another field in django
i want to multiply 2 fields of django database and save the result to another field. like i want to multiply the selling price and total quantity of a product to find total price of all those products. -
Return serialized JSON from DRF Serializer
I have a custom serializer that is returning a string representation of JSON. This serializer uses django.contrib.gis.serializers.geojson.Serializer which is much faster than the DRF serializer. The downside of this serializer is that it returns everything already serialized into a string, rather than as a JSON serializiable object. Is there a way to shortcut the DRF obj>json string process and just pass the string as the json response? Currently I am doing the following, but the obj>string>dict>string process is not ideal: from django.contrib.gis.serializers.geojson import Serializer from json import loads class GeoJSONFastSerializer(Serializer): def __init__(self, *args, **kwargs): self.instances = args[0] super().__init__() @property def data(self): # The use of json.loads here to deserialize the string, # only for it to be reserialized by DRF is inefficient. return loads(self.serialize(self.instances)) Which is implemented (simplified version) in the view: from rest_framework.mixins import ListModelMixin from rest_framework.viewsets import GenericViewSet class GeoJSONPlaceViewSet(ListModelMixin, GenericViewSet): serializer_class = GeoJSONFastSerializer queryset = Places.objects.all() -
how to get the context of an object in object_list?
I have a query set in the PostListView, and I would like to access the .likes attribute of a single object in a post.objects.all() query_set. But in the templates' context, I can only access the context dict of: context {'is_paginated': True, 'object_list': <QuerySet [<Post: aasd>, <Post: asd>, <Post: ads>, <Post: asd>, <Post: asd>]>, 'page_obj': <Page 1 of 3>, 'paginator': <django.core.paginator.Paginator object at 0x10e5901c0>, 'posts': <QuerySet [<Post: aasd>, <Post: asd>, <Post: ads>, <Post: asd>, <Post: asd>]>, 'view': <blog.views.PostListView object at 0x10e5904f0>} How can I get the context of the single Post object from the QuerySet and therefore accessing that Post.likes attributes? Thanks Edited: Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'post': post, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect('http://127.0.0.1:8000/') class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['posts'] #attribute error, no attr likes in posts queryset if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return … -
Django select oneotone from queryset in view
view @login_required def users(request): """List all users page""" t_users = User.objects.all() users = t_users.usersettings.filter(search_hidden=False).select_related('user') context = {'users': users} return render(request, 'users/users.html', context) model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserSettings(models.Model): """Stores the user's settings.""" user = models.OneToOneField(User, related_name='usersettings', on_delete=models.CASCADE) public_profile = models.BooleanField(default=True) search_hidden = models.BooleanField(default=False) class Meta: verbose_name_plural = 'usersettings' def __str__(self): return f"{self.user}'s settings" @receiver(post_save, sender=User) def create_user_usersettings(sender, instance, created, **kwargs): if created: UserSettings.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_usersettings(sender, instance, **kwargs): instance.usersettings.save() I want to select all users that have search_hidden disabled, however what I've tried doesn't work.The error 'QuerySet' object has no attribute 'usersettings' is displayed whenever the page is requested. I probably need to select each user and retrieve the settings, but I don't know how to do that in an efficient manner. -
Find the specific work via beautifulsoup in django
i started to learn beautifulsoup. I tried to make web application with django that have a html form and get the keyword from this form. When it get keyword, need to find related words inside the website.It can successfully retrieve the form from post request but for some reason, the function is not returning the rendered html as expected. its also not printing output.text. When i change the code for find tags(div,p,a etc...) it's working without any problem. This code giving output until i make any request. i didn't understand where is the problem, render or patterns? How can i fix this problem? if request.method == "POST": keyword = request.POST['keyword'] if '£#$½{[]}' in keyword: print("Please enter invalid words") else: url = 'https://www.emu.edu.tr/en' contents = requests.get(url) page_html = contents.text pagesoup = bs4(page_html, 'html.parser') mykeyword = pagesoup.find_all(keyword) for output in mykeyword: if output.select('p')[0].text == '1': print(output.text) return render(request, 'BeatifulSoup.html', {} -
Do Django models tests need database usage?
Here an minimal example (full code), a foobar application with a Class Fruit whom I want to test the __str__() method. foobar.models : from django.db import models class Fruit(models.Model): """An MVC for testing models without using Django DB""" name = models.CharField(max_length=42) def __str__(self): return self.name.upper() foobar.tests from pytest import mark from foobar.models import Fruit fruit_name = "cherry" def test_fruit__str__py(): """testing Fruit.__str__() whitout using Django DB""" test_fruit = Fruit(name=fruit_name) assert test_fruit.__str__() == fruit_name.upper() @mark.django_db def test_fruit__str__dj(): """testing Fruit.__str__() using Django DB""" Fruit.objects.create(name=fruit_name) test_fruit = Fruit.objects.last() assert test_fruit.__str__() == fruit_name.upper() Question : Since the method you would test do not involve database or pre-loaded dataset and if I want to unit-test, is the first one (test_fruit__str__py()) enough relevant? -
Django collectstatic does not collect media files from react npm build folder
I have a frontend react app, after using npm run build it creates build folder with: build favicon.ico index.html service-woker.js static After using django's python manage.py collectstatic I noticed what django has done was that it pulls out only the static folder, favicon.ico is not pulled out. So, my website icon doesn't work. In my index.html, <link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.ico" /> In my settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../frontend/build/static') ] STATIC_ROOT = '/var/www/web/home/static/' STATIC_URL = 'home/static/' In chrome inspect in the headers element: <link rel="icon" href="./home/favicon.ico"> How do I get it to display my web icon. Thankyou! -
How to serve Static Folder files in script tag - Django
I am creating a project where i create a files dynamically and store those file in staticfiles folder But when i am accessing this file it is showing file in browser http://localhost:8000/static/rest_framework/css/bootstrap.min.css But when i trying to access file which i have created and stored in staticfiles/bot_js http://localhost:8000/static/bot_js/cfe96a9a-dc84-4127-9b00-0411b7b3288e.js It is showing Page not Found I want this file to hosted on my website serve as script file for different website, like this <script src="http://localhost:8000/static/bot_js/cfe96a9a-dc84-4127-9b00-0411b7b3288e.js"></script> But it is giving me Page not found (404). How can i serve this file for different website. settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' # Add these new lines STATICFILES_DIRS = ( os.path.join(BASE_DIR, '../frontend/build/static/'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') -
How to request a user response in the middle of a django view?
I have an html page, where a user sees information about an employee, on that page I have a query button, when I click on that button I open a modal with the information needed for the query such as Name, record, date of birth. In this modal I have a continue button, when the user clicks on that button I make an ajax request for a django view, in this view I create a Query type object, my query is performed on a page external to my code, and it follows the following steps: Consult.add_page () (basically inserts the user's data in a section). Consult.capcha () (at this point I make a post request on the page with the section data to obtain a captcha), here is my problem, I need to render the captcha on the screen, I need the user to answer it, and after that I need to continue the view flow to make a Consulta.consulta_page (). Following the commented code for better understanding obs: Consult is a class Obs2: I validate codes using Tkinter to render image for user and get response, but i cant use Tkinter in server Production, and i cant return HttpResponse … -
AllAuth allowing login from users.email and account_emailaddress tables
Allauth is allowing me to log in from email addresses in account_emailaddress.email and from user.email. How can I keep these both consistant so it only allows login from one table or another? Considering updating account_emailaddress.email in views but not sure if thats the best way to go about it. models.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) secondary_email = models.EmailField(max_length=254, unique=False, null=True, blank=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) settings.py ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = 'dashboard' ACCOUNT_LOGOUT_REDIRECT_URL = 'home' LOGIN_URL = 'signin' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None -
Reverse for 'editar_arvore' with arguments '('',)' not found. 1 pattern(s) tried: ['arvore/editar_arvore/(?P<id>[0-9]+)/$']
I am having this error when I try to click to edit a form already submitted, it is as if I was not passing the arvore.id in the template ver_arvore. When I change arvore.id to a number(eg. 1) I can see all my records in the database, otherwise I have the NoReverse Match error. It is as if the view ver_arvore is not saving my dictionary, as shown in the traceback My models: class Arvore(models.Model): tag = models.CharField(max_length=255) nome = models.CharField(max_length=255) nivel = models.CharField( default='Planta', max_length=50, choices=( ('Planta', 'Planta'), ('Sistema', 'Sistema'), ('Equipamento', 'Equipamento'), ('Peça', 'Peça'), ) ) criticidade = models.TextField() requisitos = models.TextField(blank=True, null=True) descricao = models.TextField(blank=True, null=True) fabricante = models.CharField(max_length=255, blank=True, null=True) modelo = models.CharField(max_length=255, blank=True, null=True) pai = models.CharField(max_length=255, blank=True, null=True) localizacao = models.CharField(max_length=250,blank=True, null=True) link_historico = models.CharField(max_length=255, blank=True, null=True) link_pm = models.CharField(max_length=255, blank=True, null=True) link_foto = models.ImageField(blank=True, null=True) def __str__(self): return self.nome class Meta: managed = True db_table = 'arvore' class FormArvore(forms.ModelForm): class Meta: model = Arvore my url: app_name = 'arvore' urlpatterns = [ path('', views.ver_arvore, name='ver_arvore'), path('cadastro_arvore/', views.cadastro_arvore, name='cadastro_arvore'), path('editar_arvore/<int:id>/', views.editar_arvore, name='editar_arvore'), path('deletar_arvore/<int:id>/', views.deletar_arvore, name='deletar_arvore'), ] My views: def cadastro_arvore(request): if request.method != 'POST': form = FormArvore return render(request, 'arvore/cadastro_arvore.html', {'form': form}) form = FormArvore(request.POST, … -
Input redirect me on the wrong view
Hello i'm a beginner at django and i got this problem. (i don't know if the code i put is enough) When i decide to create a new comment, if i click on "create" instead of redirect me to "usercomments" and send the data to the database, it log me out and send me where log out is supposed to send me. i can't find a similar problem, i don't even know what kind of error it is, help Thanks :) Templates of "create comment" : <div class="create-comment"> <h2>Write a comment</h2> <form class="site-form" action="{% url 'usercomments:create' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> Urls.py : from django.conf.urls import url from . import views app_name = 'usercomments' urlpatterns = [ url(r'^$',views.comments_list, name="list"), url(r'^create/$', views.comments_create, name="create"), url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"), ] Views of create comment : @login_required(login_url="/userprofile/login/") def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST) if form.is_valid(): # save article to db instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('usercomments:list') else: form = forms.CreateComment() return render(request, 'usercomments/comments_create.html', { 'form': form }) Views of log out : def logout_view(request): if request.method == 'POST': logout(request) return redirect('/') <--- Where i get redirected when i press "create" else: pass Urls of … -
Django server is not running after added a new path function
I have created an app name 'calc' in Django and in the app, I have edited two files codes. urls.py from django.urls import path from . import views urlpattern = [ path('', views.home, name='home') ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello Django!") and finally, I have changed my directory folder's file urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] now I am running the command on terminal: python manage.py runserver and it's giving me these below errors and not connecting to the server. terminal errors: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\shuvra\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\shuvra\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File … -
Elastic Beanstalk - django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17)
Elastic Beanstalk with Python 3.6 and Amazon Linux 1. Django 3.0.7. Trying to create environment using eb create django-env, I get: Command failed on instance. Return code: 1 Output: (TRUNCATED)...backends/sqlite3/base.py", line 63, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). container_command 01_migrate in .ebextensions/02_setup.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Have read that downgrading django would solve the issue, but I need a recent django version so that it works with django channels. Any straightforward way to upgrade SQLite? -
How to give permission to some user which allow only view one instance by one time?
I always want allow to check for all users view one instance by one time. But another function like get(list)\post\patch\update\delete only for user which have got general perm for this actions. class IsCardAccess(BasePermission): def has_permission(self, request, view): has_perm = False if request.user and request.user.is_authenticated: if request.user.has_perm_extended(PERM_CARD_ACCESS): has_perm = True elif request.user.has_perm_extended(PERM_CARD_SUPER_ACCESS): has_perm = True return has_perm In this way user without PERM_CARD_ACCESS and PERM_CARD_SUPER_ACCESS can't do anything, but when PERM_CARD_ACCESS user can do all of this actions (get\post\patch\update\delete). I don't understand what I need to do. Anyone have any ideas? -
How to store Advance Python Scheduler Job on my database
I am trying to create various scheduling tasks to manage objects and store these jobs as a Django model on postgres and manage them through admin panel. Could anybody please help me. Thanks in advance. -
Django pagination not showing links to other page links
I am following a django book to learn django.I tried implementing pagination on a differnt website,it worked.But it's not working in my fyp.Each page has 3 objects as specified by me but the links to change pages are not appearing. My views.py:- from django.shortcuts import render from .models import song_thumb from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from django.views.generic import ListView # Create your views here. class SongListView(ListView): model=song_thumb context_object_name='artists' paginate_by=3 template_name='home.html' my template: {% block content %} <form class="" action="mediaplayer.html" method="get"> <div class="data-content"> {% for artist in artists %} <div class="container"> <div id="img-1" class="tabcontent"> <div class="blog-content"> <div class="row"> <div class="col-sm"> <div class="card" style="width: 18rem;"> <div class="img"> <img class="img-thumbnail" src="{{ artist.img.url }}" alt=""> </div> <div class="card-body"> <div class="title"> <p>{% trans 'Artist:' %} {{artist.artist}} </p><br> <p>{% trans 'Title:' %} {{artist.song_title}}</p><br> <p>{% trans 'Album:' %} {{artist.album}}</p><br> <p>{% trans 'Duration' %} {{artist.song_duration}}</p><br> </div> <audio controls> <source src='{{ artist.song.url }}' type="audio/mpeg"> Your browser does not support the audio element. </audio> </div> </div> </div> </div> </div> </div> </div> {% endfor %} </div> </form> {% include "pagination.html" with page=page_obj %} {% endblock %} my pagination.html: <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page.number }} of {{ page.paginator.num_pages … -
What's the best DRY way to repeat a class based view in Django?
I have an app that acts as a booker for the end-user; it's basically a form that calls various apis (BookerApp). It uses two main APIs but in different ways; It calls Google to get geo-location (retrieving lat-long data) to pass through the second api. The issue is I need to use this app in main WebsiteApp and its subsequent templates but with slight modification to the appearance (templates). I know I can repeat the CBV in the website app and modify the leading rendered template file; but was wondering if there was a better DRY method for this? Here is the current structure Project folder > |___ MainProject |__ settings.py |__ urls.py |__ settings.py |___ WebsiteApp |__ Templates |__ views.py <----- repeat the same CBV (found in booker) to here with DRY method |__ urls.py |__ etc.. |___ BookerApp |__ Templates |__ views.py <--- CBV held here |__ etc.. |___ Static I hope this makes sense; I know my project is all over the place and any recommendations would be welcome. In essence the app in Booker is basically a complicated form that I want to be able to use in other templates (mostly held in the WebsiteApp folder … -
Django/inlineformset: override clean method but validation error is not displayed
I try to override clean method in my inlineformset (2 fields app_app_nom and app_dro) but failed I need to test that same app_app_nom is not selected twice To test raise error in clean method (I will code logic after), I try to raise error each time form is submitted (if True: raise error) data are not registered but message error is not displayed and I am redirected...? forms.py class ApplicationInlineFormSet(BaseInlineFormSet): def clean(self): super().clean() # example custom validation across forms in the formset for form in self.forms: # your custom formset validation # app_app_nom = form.cleaned_data.get('app_app_nom') if True: raise ValidationError('You select the same app twice') else: # update the instance value. form.instance.app_app_nom = app_app_nom NAME = Thesaurus.options_list(2,'fr') ACCESS = Thesaurus.options_list(3,'fr') ApplicationFormset = inlineformset_factory( UtilisateurProjet, Application, fields=('app_app_nom','app_dro'), widgets={ 'app_app_nom': forms.Select(choices=NAME), 'app_dro': forms.Select(choices=ACCESS) }, extra=3, can_delete=True, formset=ApplicationInlineFormSet ) template.html <form id="utilisateureditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <a style="margin-right: 40px" data-target="" class="" href="{% url 'project:edit_utilisateur' %}">Nouvel utilisateur</a> <br> <br><div class="dropdown-divider"></div><br> <h2>Applications</h2><br><br> <!-- {{ application|crispy }} --> <!-- curieusement si j'enlève cette ligne le style crispy disparait --> {{ application.management_form|crispy }} <div class="row"> <div class="col-6"><p>Nom de l'application</p></div> <div class="col-5"><p>Droits</p></div> <div class="col-1"><p></p></div> </div> {% for application_form in application %} <div class="row link-formset"> {% … -
Django: how to get a javascript value from template to view?
I am currently using Django framework. I would like to get the value of a javascript value wrote in an html file. I would like to be able to display it in my view file Here is my html file from the folder templates: <script> var toto = "javascript"; document.write(toto) </script> This is my view file: def javascript(request): # print the javascript value here return render(request, "rh/javascript.html") Thank you for your help ! -
Newletter Views not sending Emails after being saved with no error showing
I have created a newsletter app to send emails to subscribers. After adding a new newsletter and setting it to be equal to published it should send the email, but instead, the newsletter is saved with no emails sent. I am sure that the email setting is correct as I am receiving an email after a successful subscription for testing. Here is the complete views.py def newsletter_signup(request): form = NewsletterUserSignupForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): messages.warning( request, 'Your email is already exists in our database') else: instance.save() messages.success( request, 'Your email has been added in our database') subject = "Thank you for Joining our Newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] with open(settings.BASE_DIR + "/templates/newsletter_signup_email.txt") as f: signup_message = f.read() message = EmailMultiAlternatives( subject=subject, body=signup_message, from_email=from_email, to=to_email) html_template = get_template( "newsletter_signup_email.html").render() message.attach_alternative(html_template, "text/html") message.send() context = {'form': form} template = "newsletters_signup.html" return render(request, template, context) def newsletter_unsubscribe(request): form = NewsletterUserSignupForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): NewsletterUser.objects.filter(email=instance.email).delete() messages.success( request, 'Your email has been removed from our database') subject = "You have been removed from our newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] with open(settings.BASE_DIR + "/templates/newsletter_unsubscribe_email.txt") as f: signup_message = f.read() message = … -
Rq worker failed job
I am running a python Django app. It runs rq worker in background to perform additional longer tasks. Every time the call to worker is made it exits with the message Moving job to 'failed' queue (work-horse terminated unexpectedly; waitpid returned 11) The environment setup is redis==2.10.6, rq==0.12.0, python 3.6.10 My system has more than sufficient memory to run the worker thread. When I run the same worker in a docker, it works fine. ------------------------------ ------------ amqp 2.4.2 appdirs 1.4.3 appnope 0.1.0 asgi-redis 1.4.3 asgiref 1.1.2 atomicwrites 1.3.0 attrs 19.1.0 autobahn 19.3.3 Automat 0.7.0 awscli 1.18.69 Babel 2.6.0 bandwidth-sdk 3.0.3 beautifulsoup4 4.7.1 billiard 3.5.0.5 bleach 3.1.0 blis 0.4.1 boltons 19.1.0 boto3 1.9.137 botocore 1.16.19 cached-property 1.5.1 cachetools 3.1.0 catalogue 1.0.0 celery 4.2.1 certifi 2019.3.9 cffi 1.12.3 channels 1.1.8 chardet 3.0.4 Click 7.0 colorama 0.4.3 configparser 4.0.2 constantly 15.1.0 convertdate 2.2.0 croniter 0.3.30 cymem 2.0.2 Cython 0.29.14 daphne 1.4.2 dateparser 0.7.1 DateTimeRange 0.5.5 ddtrace 0.36.1 decorator 4.4.1 defusedxml 0.6.0 dill 0.2.9 dj-database-url 0.5.0 Django 1.11.27 django-appconf 1.0.3 django-axes 4.5.4 django-bower 5.2.0 django-compressor 2.2 django-cors-headers 2.5.3 django-debug-toolbar 1.11 django-extensions 2.1.6 django-htmlmin 0.11.0 django-ipware 2.1.0 django-json-response 1.1.5 django-model-utils 3.1.2 django-phonenumber-field 2.3.1 django-ratelimit 2.0.0 django-redis 4.10.0 django-rest-auth 0.9.5 django-rq 1.2.0 django-static-precompiler 1.8.2 django-test-without-migrations 0.6 …