Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to prevent messages get stored in cache?
Is It possible to avoid cache messages provided by Django messaging framework when use cache_page decorator? Thing is that on a page with, for example article, if I change it’s content, old cache gets invalidated on model’s change and new version on the page stores to cache. Problem is when I change context on page reload I get success message and this message gets captured by cache ( I guess it just stores httpresponse where message represented by block). Then when I visit this page again or reload it it shows me this message from the cache, which is sucks... Question is how to avoid this situation or how to have 2 separate cache versions for page with message and without message? <div class="messages" id="message_container" style="display: none;"> <div class="alert alert-success alert-dismissable fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="close">×</button> Article Justa n article has been edited and saved successfully </div> </div> -
django admin custom css only in changeview
I need to have bootstrap css in django admin, but only in change view, not list view. If I use class Media: css = { 'all': ('tagsinput/bootstrap-tagsinput.css', 'bootstrap-3.3.7-dist/css/bootstrap.css',) } It affects both views and breaks some elements in list view. How can I do that? -
Update view with formset factory not work
I'm trying to do an updateview on a formset but it does not find the data from the second form. in my models.py class OrdemServicoCoroa(models.Model): ordem_servico = models.ForeignKey( OrdemServico, related_name='coroas', on_delete=models.CASCADE, blank=True, null=True ) coroa = models.ForeignKey( Coroas, related_name='ordens_servico', on_delete=models.CASCADE, blank=True, null=True ) quantidade = models.IntegerField(default=0, blank=True, null=True) frase = models.CharField(max_length = 100) observacao = models.CharField(max_length=100, blank=True, null=True) foto_coroa_valida = models.ImageField(upload_to = "upload/flora",blank=True) inicio_flora = models.DateTimeField(blank=True, null=True) termino_flora = models.DateTimeField(blank=True, null=True) def _str_(self): return '{}: {}: {}'.format(self.coroa, self.quantidade, self.frase) in my forms.py class OrdemServicoForm(forms.ModelForm): class Meta: model = OrdemServico fields = ( 'empresa_origem','atendente','funeraria', 'falecido', 'cpf_falecido', 'abrangencia', 'tipo', 'forma_sep', 'taxas_apagar', 'quais_taxas', 'remocao', 'codigo', 'forma_pagamento', 'urna', 'biblia', 'cristo', 'sem_adereco', 'veu', 'preparacao', 'preparacao_opcional', 'ornamentacao', 'obs_ornamentacao', 'previsao_pronto_laboratorio', 'cafe', 'local_velorio', 'capela', 'local_sepultamento', 'previsao_velorio', 'data_sepultamento' ) class OrdemServicoCoroaForm(forms.ModelForm): class Meta: model = OrdemServicoCoroa fields = ('coroa', 'quantidade', 'frase', 'observacao') OrdemServicoFormset = forms.formset_factory( form=OrdemServicoCoroaForm, extra=1, ) in my views.py class OrdemServicoUpdateTeste(UpdateView): template_name = 'ordem_servico/ordem_servico_cadastro.html' model = OrdemServico form_class = OrdemServicoForm def get_success_url(self): self.success_url = reverse_lazy('ordem_servico:listagem') return self.success_url def get_context_data(self, **kwargs): context = super(OrdemServicoUpdateTeste, self).get_context_data(**kwargs) ppk = OrdemServicoCoroa.objects.filter(ordem_servico_id=self.kwargs['pk']).values() if self.request.POST: context['coroa_set'] = OrdemServicoFormset(self.request.POST, prefix='ordem_servico') else: context['form'] = OrdemServicoForm(instance=self.object) context['coroa_set'] = OrdemServicoFormset(initial=ppk) return context def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) ordem_servico_form … -
Django can't get user IP in AWS Elastic Beanstalk Load-Balanced Environment
I have a load-balanced environment set up in AWS Elastic Beanstalk with a Django app deployed and running Django-user-sessions. I'd like it to be able to log the user session external IP addresses, but everything that gets logged is an internal IP. I have another environment that is not load-balanced and external user IPs are being collected, so I'm fairly sure the user IP is getting overwritten by the internal IP of the load balancer. I have tried to install django-xforwardedfor-middleware which supposedly adds request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() to each request, but this has not solved the problem. I also have an HTTPS engine rewrite in my .ebextensions that is not running on the environment that is working properly, but I don't think it is the problem: files: "/etc/httpd/conf.d/ssl_rewrite.conf": mode: "000644" owner: root group: root content: | RewriteEngine On <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'"> RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L] </If> Are there any other things I could try to get django-user-sessions to collect external user IPs? -
Dynamic form field in Django REST
I'm trying to create a form where the user can create a blog. The form will have a title, one to many authors, and content. For the authors part, I'd like to have an input autocomplete search box (like stackoverflow's tags search box) that will add authors to the blog. I know how to create the frontend look of this, but as far as using Django's REST framework to add the authors in my model I don't know how to do that. Models: class Story(models.Model): title = models.CharField(max_length=100, null=False) content = models.TextField() created_at = models.DateField(auto_now_add=True) class StoryAuthor(models.Model): story = models.ForeignKey(Story, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) How do I go through each added author from the input and add it into my StoryAuthor model? So for example, one story should look like this: id title content created_at 1 Hello world blah, blah 2019-06-04 story user 1 John 1 Jack 1 Brad As far as the input box, the data would look like this: "John, Jack, Brad" how can I use Django's REST to have a serializer/endpoint that can do this? -
Referencing host url in settings.py
this is a really basic question, but I cannot seem to find the answer on the internet. In settings.py I have a line that looks like this. settings.py LOGIN_REDIRECT_URL = 'http://localhost:8000/profile' Obviously having "localhost" is not very stable when pushing into production. And everytime I deploy it the URL changes. How to I reference the URL in settings.py? -
I am trying to create registration form with django forms.But when i enter data it returns ValueError at /register?
I am trying to create form using django forms.I created registration form when i enter data and click on submit it returns ValueError at /register and if i enter wrong data for example invalid email its not showing corresponding error? def register(request): if request.method == "POST": form = Register(request.POST) if form.is_valid(): email = form.cleaned_data['Email'] User_name=form.cleaned_data['Username'] Password=form.cleaned_data['Password'] Confirm_Password=form.cleaned_data['Confirm_Password'] User.objects.create_user(username=User_name, password=Password,email=email) return redirect("register") else: form = Register() return render(request,'register.html',{'form': form}) <!------register.html---> {% extends 'layout.html' %} {% block content %} <div class="box"> <h2> <center>Register</center> </h2><br> <form action='register' method='POST'> {% csrf_token %} <div> <label>Email:</label> {{ form.Email }} {{ form.Email.errors }} </div> <div> <label>Username:</label> {{ form.Username }} {{ form.Username.errors }} </div> <div> <label>Password:</label> {{ form.Password }} </div> <div> <label>Confirm Password:</label> {{ form.Confirm_Password }} {{ form.Confirm_Password.errors }} </div> <input type="Submit" id="lg"/><br> <center><a href="login" >Already have an account.Login here.</a> </center> </form> </div> <div> {% for message in messages%} <h1>{{message}}</h1> {% endfor %} </div> {% endblock %} forms.py from django import forms from django.contrib.auth.models import User from django.core.validators import validate_email class Register(forms.Form): Email = forms.EmailField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Username = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) Confirm_Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) class Meta(): model = User fields = ['email','username','password'] def clean_Email(self): try: validate_email(self.cleaned_data['Email']) except: raise forms.ValidationError("Email is not in correct format!") … -
How to create a new instance of some model when instantiating some another model?
I want to instantiate the Blog model when instantiating the User model and associate a new instance of the Blog model with a just created instance of the User model (and save both in database) by the OneToOneField. I want always create a new instance of the Blog model when I creating a new instance of the User model and associate them by the OneToOneField. class User(AbstractUser): # some logic to create a new instance of the Blog model # and associating it with a just created instance of the User # by the OneToOneField class Blog(models.Model): author = OneToOneField(User, on_delete=models.CASCADE, primary_key=True) How can I get it? Thank you in advance! -
Trouble Making Soundboard in Django Html Template
I'm setting up a django website, and I've made a html template for the page I want the soundboard to be in. In the template, I wrote some code for a button, and it runs fine, but when I click the button, the sound doesn't play. I've tried making a new directory in my templates directory and loading it from there, but to no avail. The mp3 works perfectly as it should when played normally (the windows groove app thing). This is the html template. In my template directory, there's a file named 'bruh.mp3' <!DOCTYPE html> </html> <head> <title>The Bruh Button</title> </head> <body> <audio id="bruhsound" src="bruh.mp3"></audio> <button onclick="document.getElementById('bruhsound').play()">BRUH</button> </body> </html> All I want it to do is for the button to play the sound file on a click. Preferably, for every button click, the sound file restarts. In other words, if you spam click the button, each click would interrupt the current sound playing, so it essentially can be spammed. -
CSS not applying to HTML page when receiving a new render in Django
I am currently struggling on a problem of HTML response. I have an HTML page with CSS,JS working fine, the user will do an interaction that will go to JS -> send ajax request and do some treatment within a working view. And this view give me back a rendered view with all the info updated. The problem is that the HTML given is containing everything but looks like "raw" HTML a.k.a no CSS applied to it, (scripts are working fine) In the head of my HTML file : <head> <meta charset="utf-8"> <title>Sorting video: {{video.title}}</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'modelReco/cssFiles/swipeFrames.css' %}?v=00002'"> <script type="text/javascript" src='{% static "modelReco/jsScript/swipeFrames.js" %}?v=00003'></script> </head> The view that render the HTML: def sendSortVideoResponse(request,untreatedFrame,myVideo,frames,tracks,url): response = render(request, url, { 'video':myVideo, 'frames':frames, 'tracks':tracks, 'untreatedFrame': untreatedFrame[0], 'countTreated': untreatedFrame[1], 'totalFrames': len(frames), 'progressBar': untreatedFrame[1]/len(frames)*100, }) response["Cache-Control"] = "no-cache, no-store, must-revalidate" response["Pragma"] = "no-cache" # HTTP 1.0. response["Expires"] = "0" # Proxies. return response In settings.py : PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..') SITE_ROOT = PROJECT_ROOT MEDIA_ROOT = os.path.join(SITE_ROOT, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(SITE_ROOT, 'static') STATIC_URL = '/static/' If you F5 the page then everything works fine again. For the user, … -
Duplicated results after filtering
When I filter by id, first_name or last_name I get duplicated results. If I put .distinct() after filter() I get even more duplicate results than before. It seems to be the involved__user__ relation. jobs = Job.objects.order_by(order) if _filter: jobs = jobs.filter(Q(bundle__icontains=_filter) | Q(onBehalfOf__icontains=_filter) | Q(involved__user__first_name__icontains=_filter) | Q(involved__user__last_name__icontains=_filter) | Q(involved__user__email__icontains=_filter) | Q(description__icontains=_filter) | Q(id__iexact=_filter)) With distinct() I get even more duplicate results than without it: jobs = Job.objects.order_by(order) if _filter: jobs = jobs.filter(Q(bundle__icontains=_filter) | Q(onBehalfOf__icontains=_filter) | Q(involved__user__first_name__icontains=_filter) | Q(involved__user__last_name__icontains=_filter) | Q(involved__user__email__icontains=_filter) | Q(description__icontains=_filter) | Q(id__iexact=_filter)).distinct() -
Django html adding 'selected' to <option> if item is in list
I need to add the attribute selected to an html <option> tag if the current item is in another list This is my code: <option {% if leiter is in programmpunkt.leiter %}selected{% else %}{%endif %} value="{{ leiter.username }}">{{ leiter.username }}</option> -
how can i implenet Machine Learning for multiple tasks?
currently in our project we have movies (something close) as main content and the user can comment on that using text, i m wondering if it is possible to make a machine learning engine which will be used as a recommendation system AND will be used as a text filter (filtering bad words) , i have literally only basic knowledge when it comes to Artificial intelligence in general , my question is : Is it possible to make a single machine learning engine which does 2 different things or should we build the two separately? , any guides or resources are much appreciated -
SECRET_KEY variable is printing, but still receiving SECRET_KEY must not be empty error
I am deploying my application to Heroku but when I attempt to push the code to Heroku, I receive the The SECRET_KEY setting must not be empty. error. When I replace the SECRET_KEY = os.getenv('SECRET_KEY') with SECRET_KEY = 'XXXXXXXXXXX', there is no longer an error. I thought it would be that the my environment variable is not being read correctly and is returning None. However, when I use the shell to print my settings.SECRET_KEY while it's set to os.getenv('SECRET_KEY'), it prints my environment variable. Also, if I remove the AWS_SECRET_ACCESS_KEY, it appears to be working as well. I am not sure what is going on. I am on Windows by the way, working with Django 2.2.2 and Python 3.7.3. Here is my settings.py: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY … -
Django: Filter query set on two levels
My query set is qs = Event.objects.filter(organizer=1, status=EventStatus.LIVE,).exclude(tickets__status=TicketStatus.PAUSED,).values('pk', 'tickets__pk', 'tickets__quantity', 'tickets__price_gross') As a result I get <EventQuerySet [{'pk': 4, 'tickets__pk': 13, 'tickets__quantity': 20, 'tickets__price_gross': 2000}, {'pk': 6, 'tickets__pk': 17, 'tickets__quantity': 123, 'tickets__price_gross': 2000}, {'pk': 6, 'tickets__pk': 16, 'tickets__quantity': 10, 'tickets__price_gross': 1000}, {'pk': 5, 'tickets__pk': 14, 'tickets__quantity': 10, 'tickets__price_gross': 1000}]> Now I have the challenge that I want to annotate tickets_left to my values. For that I 1) have to count attendees. I came that far .annotate(sold_tickets=Count('attendees', filter=Q(attendees__canceled=False))). 2) I have to make a subtraction tickets__quantity - attendees. The result is tickets left. But I still don't manage to get to a result such as <EventQuerySet [{'pk': 4, 'tickets__pk': 13, 'tickets__quantity': 20, 'tickets__price_gross': 2000, 'tickets_left' 123}, {'pk': 6, 'tickets__pk': 17, 'tickets__quantity': 123, 'tickets__price_gross': 2000 'tickets_left' 322}, The problem I can't fix right now is that attendees are counted "per ticket". Do you have ideas on how to solve that? -
how to implement vue.js search filter in django template
Here I am implementing the search filter of vue.js in my django app template. I have tried the following code but it is not working. How can I do this?? vue.js new Vue ({ el: '#app', delimiters: ['[[', ']]'], data: { search: '', List : [ {% for item in items %} { "id" : "{{ item.id }}", "name": " {{ item.name }} " }, {% endfor %} ] }, computed: { filteredProducts() { // var lowerTitle = product.title.toLowerCase(); return this.List.filter((list) => { return list.name.toLowerCase().match(this.search); }); } } }) template <div id="app"> <div class="search-wrapper"> <input type="text" v-model="search" placeholder="Search title.."/> </div> <div class="wrapper"> <div class="card" v-for="item in filteredList" :key="list.id"> [[ item.name ]] </a> </div> </div> </div> -
I can't add the created map from django editor ymaps to my template
How i can add the created map from Django Editor Yandex Maps in to my html template? I read the tutorial in Python website, about how to add the map in to template but i don't have some files in static\ folder. So if someone knows, I'll be glad to get solving my problem) -
Multiprocessing within redis queue
I'm working with a django application hosted on heroku with redistogo addon:nano pack. I'm using rq, to execute tasks in the background - the tasks are initiated by online users. I've a constraint on increasing number of connections, limited resources I'm afraid. I'm currently having 2 connections for 2 diffrent types of task. For instance, lets say if 4 users initiate same type of task, I would like to have my main worker create child processes dynamicaly to handle it. Is there a way to achieve required multiprocessing and concurrency? I tried with multiprocessing module, initially without introducing Lock(); but that exposes and overwrites user passed data to the initiating function, with the previous request data. After applying locks, it restricts second user to initiate the requests by returning a server error - 500 github link #1: Looks like the team is working on the PR; not yet released though! github link #2: This post helps to explain creating more workers at runtime. This solution however also overrides the data. The new request is again processed with the previous requests data. Let me know if you need to see some code. I'll try to post a minimal reproducible snippet. Any … -
how to print png chart from google charteditor?
From the official documentation of Google charts, It provides the following syntac for getting the imageURI() for a specific chart type: var my_div = document.getElementById('chart_div'); var chart = new google.visualization.ChartType(chart_div); google.visualization.events.addListener(my_chart, 'ready', function () { var imgUri = chart.getImageURI(); //perform print function }); However I am using Google's chart editor method, and I am unable to retrieve the imageURI for the chart selected. chartEditor = new google.visualization.ChartEditor(); google.visualization.events.addListener(wrapper, 'ready', function () { var imgUri = chartEditor.getChart().getImageURI(); //throws error: getChart().getImageURI() not a function of chartEditor }); I am particularly new to the usage of Chart editor function. -
How to implement facebook like notifications using django 1.9 as backend and angular 7.2 as frontend?
I have a web application which uses DRF as backend and angular 7.2 as frontend. The version of Django we are currently using is 1.9. I want to implement facebook like notifications so what would be the best way to implement. Is sending request from FE on certain endpoint after few seconds good option? I also went through channels library for WebSockets but seems like it doesn't support Django 1.9. -
How to create monthly shift scheduler in Django
I would like to kindly ask you for some idea how to approach a shift scheduling app in Django. I need to push forward. In the picture, there is described how I want the app to look. https://imgur.com/a/d8XxdKX I have models Shift, Department, Employee and Scheduler (Date, shift_fk, department_fk, employee_fk) How would you approach it? I just need an idea how to connect all those models and display shifts in correct columns and rows Thank you very much Filip -
Django - Create An Endpoint Which Accepts Multiple Values For A Search Field
Full Disclosure: I am a front-end Javascript developer helping with resolving this internal issue we have: Our Django backend is currently serving an endpoint with the following signature: *.api/search_field/?category=abc&category=bcd&category=def What I want to know is that is there a way to simplify the above endpoint to something simple as follows: *.api/search_field/?category=abc,bcd,def And how would we do this in Django? Thanks -
How to pass pk from view to key_prefix function in cache_page decorator
Is it possible somehow pass “pk” from the view “ show_by_heading_view” to the function “ vary_on_paginated_or_not” using decorator/function relationship?? Only I idea how to do it that came to my mind is to analyze request and get it from there: pk = request.get_full_path_info().split("/")[-2] But it kind of unreliable way as url might get changed . I would prefer to do it pythonic way sort of but dont know how. @cache_page decorator from fancy_cache package, so it can use callable… Function “ vary_on_paginated_or_not” specifies wherther pagination is involved or not to invalidate cache if so... Thank you def vary_on_paginated_or_not(request): pk = request.get_full_path_info().split("/")[-2] count_eq = Article.objects.filter(foreignkey_to_subheading=int(pk)).count() return "show_by_heading_view+%s" % True if count_eq > 10 else False @cache_page(60*60*24*7, key_prefix=vary_on_paginated_or_not) def show_by_heading_view(request, pk): #597 current_heading = get_object_or_404(SubHeading, pk=pk) list_of_articles = Article.objects.filter(foreignkey_to_subheading=pk) if "keyword" in request.GET: keyword = request.GET["keyword"] keyword_unidecode = unidecode.unidecode(keyword) q = Q(title__icontains=keyword) | Q(content__icontains=keyword) | Q( title__icontains=keyword_unidecode) | Q(content__icontains=keyword_unidecode) list_of_articles = list_of_articles.filter(q) else: keyword = "" form = SearchForm(initial={"keyword": keyword}) paginator = Paginator(list_of_articles, 10) if "page" in request.GET: page_num = request.GET["page"] else: page_num = 1 page = paginator.get_page(page_num) context = {"current_heading": current_heading, "page": page, "list_of_articles": page.object_list, "form": form} # 597 return render(request, "articles/show_by_subheading.html", context) -
Email not showing in recipient inbox but it is sent from the Django app
I am using mailtrap.io to send email through Django's email service. The email is sent as it's shown in mailtrap's sent items but it doesn't reach the recipient. I tried using other SMTP as well such as mailjet but no email. I don't see an error in the logic none that I can understand. Kindly check. views.py def send_email(request, in_id, pr_id): invite_data = Invite.objects.get(id=in_id) person_data = PersonData.objects.get(id=pr_id) context = {'invite_data': invite_data, 'person_data': person_data} subject = "Come Join us" # email subject email_from = "settings.EMAIL_HOST_USER" # email from to_email = [person_data.person_email] # email to msg = EmailMultiAlternatives( subject=subject, body=invite_data.invite_msg, from_email=email_from, to=['pumuxum@emailtex.com'] ) print (invite_data.invite_msg) print (email_from) print (to_email) html_template = get_template( "userfiles\email.html").render() msg.attach_alternative(html_template, "text/html") msg.send() messages.success(request, ("Email Sent !!")) return redirect("InviteList") email.html <h3>Application accepted</h3> <h6>Have a good day</h6> //Data from the database {{person_data.person_first_name}} {{person_data.person_last_name}} {{person_data.person_contact_number}} <hr><hr> {{invite_data.invite_msg}} {{invite_data.event_date}} -
How to run the post_save signal after a specified time?
There is a post_save signal. Need to run it no earlier than an hour after the creation of the object. I can use time.sleep(3600), but this is not the best approach, as I understand it. What other options are there?