Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Many Users to One model. A Model about the User
I'm trying to figure out how the many users can be associated with one instance of a model. I have a sports club project. There is many users (admin and staff) only one Club. I can't seem to form a many to one relationship with the User model. I want to filter mainly by club. Say if 3 clubs use the project, each club would want to be separated by club and not by user. Below is a simplified version of my models. I've also tried to add the ForeignKey to the club and go the other way. Class Club(models.model): name = models.CharField(max_length=40, null=True) Class User(AbstractBaseUser): name = models.CharField(max_length=40, null=True) club = models.ForeignKey(Club, on_delete=models.CASCADE) -
Function missing 1 required positional argument(pandas)
I am trying to return a ratio between two tickers but am getting an error when trying to view it locally. I'm new to both pandas and django so any help will be much appreciative. def tkr_ratio(ticker1, ticker2): tickers_dict = TSDB.objects.filter(TICKER__in = [ticker1, ticker2]).values('DATE', 'TICKER', 'CLOSE') df = pd.DataFrame(tickers_dict, columns = ['DATE', 'TICKER', 'CLOSE', 'RATIO']) df = pd.pivot_table(df.sort_values('DATE'), values = 'CLOSE', index = 'DATE', columns = 'TICKER') json_list = [] df['RATIO'] = df[ticker1]/df[ticker2] for i in df['RATIO'].itertuples(): json_list.append([totimestamp("DATE"), i]) return json_list TypeError: tkr_ratio() missing 1 required positional argument: 'ticker2' -
get_FIELD_serializer in Django Rest Framework
I'm in a situation where I want to change the serializer field depending on a condition. Where the condition comes doesn't matter but I want to be able to switch between serializer fields as the following example: class EntrySerializer(serializers.ModelSerializer): # author defined from ModelSerializer def get_author_serializer(self): request = self.context.get('request') GET = getattr(request, 'GET', {}) if request and GET and GET.get('include_author')=='true': author_serializer = UserSerializer() else: author_serializer = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) return author_serialize Of course this doesn't work because get_FIELD_serializer doesn't exist, but I'm looking for the simplest solution that can do this. I've tried writing author as a property in a naive attempt but it didn't work. I am aware that I can write multiple EntrySerializers and use get_serializer_class but that is just too much boilerplate code for such a small customization. -
Django: Creating query set?
I am trying to get the following outcome <EventQuerySet [{4: 10000, 5: 20000, [...]}]>. The way to "get" there is the following workflow: 1) Get each active event of the organizer def organizers(self): return self.request.user.organizers Event.objects.filter( organizer__in=self.organizers, status=EventStatus.LIVE ) 2) For each event > get all tickets that belong to that specific event. Especially, I need to get access to quantity & price of each ticket 3) Get the amount of tickets which are already sold .annotate( sold_tickets=Count('attendees', filter=Q(attendees__canceled=False)) ) .order_by('organizer') 4) Now we have all the information we need to calculate the max_remaining_gross_sale per event: Example: Event with pk 4 Ticket 1: price_gross * (quantitiy - sold_tickets) Ticket 2: price_gross * (quantitiy - sold_tickets) Event with pk 5 Ticket 1: price_gross * (quantitiy - sold_tickets) [...] 5) From all tickets per event we build the Sum an get the following result: <EventQuerySet [{4: 10000, 5: 20000, [...]}]> I didn't manage to build that QuerySet in a way that gives me the result from 5). Do you have any advice for me? Here my models with the relevant fields: class Ticket(TimeStampedModel): quantity = models.PositiveIntegerField( verbose_name=_("Quantity"), validators=[MinValueValidator(1), MaxValueValidator(100_000)], ) status = models.CharField( max_length=8, choices=TicketStatus.CHOICES, default=TicketStatus.ON_SALE, verbose_name=_("Status"), ) price_gross = models.PositiveIntegerField( verbose_name=_("Price … -
Django Rest doesn't change cookie/sessionid on password change
I want to flush an old cookie and set a new one, so that an old cookie would be invalidated. My method for password changing def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get("new_password")) self.object.save() print(self.object) update_session_auth_hash(request, self.object) request.session.flush() return Response("Success.", status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) and my method for logging user in def login_user(self, request, *args, **kwargs): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'Result': {'error': 'Please provide both username and password'}}, status=HTTP_400_BAD_REQUEST) user = authenticate(request, username=username, password=password) if not user: return Response({'Result': {'error': 'Invalid Credentials'}}, status=HTTP_400_BAD_REQUEST) if user: login(request, user) return Response({"Result": {'Success': 'Logged in'}}, status=HTTP_200_OK) when i logout it shows that my cookie is change, but whenever I login again it sets an old cookie :/ upd: My settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'COERCE_DECIMAL_TO_STRING': True } STATIC_ROOT = os.path.join(STATIC_URL + 'Test') SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_HTTPONLY = True SESSION_SAVE_EVERY_REQUEST = True MIDDLWARE = [... 'django.contrib.sessions.middleware.SessionMiddleware', ....] -
How to add custom ID for Celery task in order to revoke task later?
I want to create delayed task and if there would be some conditions, I need to find that task and revoke it. This is how I create task: notify_before_departure.apply_async( args=(user.fcm_registration_token, booking.bus_stop_from.title,), eta=notification_time, ) So is there any attribute apply_async has where I can define my custom ID which can later be used to revoke this exact task? Something like this: # create task notify_before_departure.apply_async( args=(user.fcm_registration_token, booking.bus_stop_from.title,), eta=notification_time, custom_id=booking.id ) # revoke if needed from celery.task.control import revoke revoke(booking.id, terminate=True) -
Suppress Status Output in Django
I tried to find this, but I'm probably not searching the right way. When I run my Django app, I get a record printed to the error output every time an endpoint is called, similar to: [20/Jun/2019 09:45:37] "GET /analyst/run_session/ HTTP/1.1" 200 1271 The problem is, I have a call set up every second to refresh data from the api, so my console is being flooded by these entries. I have tried setting DEBUG=False, and setting MESSAGE_LEVEL=message_constants.ERROR, but it doesn't seem to suppress these entries. Is there something obvious I'm missing? -
Creating a Django Rest Framework log activity for users that are Reading or Writing to certain APIs
Want a way to log users activity on my api. For example, want to see which users are hitting certain APIs. Also seeing if they're making any changes to the APIs -
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)