Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
submitting a form with multiple different buttons
I am trying to make a form that has three different submit buttons or inputs. I read that to do that I have to provide a name and a value attribute to the button. I already tried the button tag and input tag. But when I try to submit them and then print the POST request from within Django. nothing is printed. Only the csrf token is included with the POST request. This is the code I am trying. It only works when there is an input tag other than the submit type. but then I can't seperate them because any button will post everything in the form. THanks! <input type="submit" name="first_choice" value="first" class="btn btn-danger" > <input type="submit" name="first_choice" value="second" class="btn btn-info" > <input type="submit" name="first_choice" value="third" class="btn btn-success" > -
having the full field object instead of it's ID in django model
with these two models TblPhoto class TblPhoto(models.Model): #path = models.CharField(max_length=256) type = models.ForeignKey('TblPhotoTypes', models.DO_NOTHING, blank=True, null=True) path = models.ImageField(upload_to='images') def __str__(self): return str(self.id) class Meta: managed = False db_table = 'tbl_photo' verbose_name = "Photo" verbose_name_plural = "Photos" and TblCustomer class TblCustomer(models.Model): name = models.CharField(max_length=32) email = models.CharField(max_length=32) password = models.CharField(max_length=32) token = models.CharField(max_length=64, blank=True, null=True) firebase_token = models.CharField(max_length=64, blank=True, null=True) registration_date = models.IntegerField(blank=True, null=True) last_login_date = models.IntegerField(blank=True, null=True) about = models.TextField(max_length=128, blank=True, null=True) active = models.BooleanField(blank=True, null=True) photo = models.ForeignKey(TblPhoto, models.DO_NOTHING) def __str__(self): return str(self.id)+' : '+self.name class Meta: managed = False db_table = 'tbl_customer' verbose_name = "Customer" verbose_name_plural = "Customers" the api response is... { "response_status": { "code": 200, "internalMessage": "", "message": "" }, "user": { "id": 1, "name": "deya", "email": "3denator@gmail.com", "password": "e10adc3949ba59abbe56e057f20f883e", "token": null, "firebase_token": null, "registration_date": null, "last_login_date": null, "about": "hello, i'm Deya !", "active": true, "photo_id": 4 } } notice the field photo_id, how can I alter the TblCustomer model to show the photo object instead of the photo id? Disclaimer : I can do this easily out of the model, but I want it to be in the model class. -
Nested get or create functionality - DRF
There have been some posts about nested create functionalities however none seem to have helped me out. You can see here what my json post request looks like: { "games": [ { "company": { "name": "Google", "website": "https://google.com", "trustedpilot": "5" }, "genres": [], "formats": [], "platforms": [], "title": "Call of duty modern warfare", "cover": "https::cover.jpg", "link": "https://google.com", "prev_price": "60.00", "price": "40.00" } ], "company": { "name": "Google", "website": "https://google.com", "trustedpilot": "5" }, "name": "Bundle name", "prev_price": "50.00", "price": "20.00" } The game serializer seems the work fine when creating a single game: class GameSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer(many=False) genres = GenreSerializer(many=True) formats = FormatSerializer(many=True) platforms = PlatformSerializer(many=True) class Meta: model = Game fields = '__all__' def create(self, validated_data): # Many to one company_data = validated_data.pop('company') # Many to Many genres_data = validated_data.pop('genres') formats_data = validated_data.pop('formats') platforms_data = validated_data.pop('platforms') # Company company, created = Company.objects.get_or_create(**company_data) # Get the game or created a new one if it doesn't exist yet game, created = Game.objects.get_or_create(**validated_data, company=company) # Platform for platform_data in platforms_data: platform, create = Platform.objects.get_or_create(**platform_data) game.platforms.add(platform) # Format for format_data in formats_data: format, create = Format.objects.get_or_create(**format_data) game.formats.add(format) # Genre for genre_data in genres_data: genre, create = Genre.objects.get_or_create(**genre_data) game.genres.add(genre) return game This is the … -
Passing List as Parameter in Python Requests
I generate a list of IDs, x = [1,2,3] from a set of records pulled from an API request. I then take this list and pass it as a parameter in a second API request which returns a set of records, y = [1,2] which are related to the first by foreign key. The problem I am having is that I need to return or assign a value for each ID in the list, as not every ID in the list has a corresponding record. Therefore, my two lists differ in size when I need them to be 1:1 for when I iterate through the data. How can I return some default value for when the query is false or how can I assign a value for when there is no corresponding record for a given ID? So as, x = [1,2,3] and y = 1,2,3] or x == y. Please let me know if any further information is needed. views.py def do_something(self, request): try: r = requests.get( self.URL + 'domain/endpoint in (' + request + ')', headers=self.Header) r.raise_for_status() except: print(r.text) raise return r.json() y = obj.do_something(x) -
Ubuntu server with Postgres - django.db.utils.OperationalError: fe_sendauth: no password supplied
I am deploying my Django website using Linode (using ubuntu for the server). I manage to create a virtual environment on my Linode server and push my application into it. Now, I want to test if it works, so I run on my server (not local machine): python manage.py runserver 0.0.0.0:8000 However, I get the error: django.db.utils.OperationalError: fe_sendauth: no password supplied On my localmachine, I used postgres: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cocdb', 'USER': 'name', 'PASSWORD': '', # Yes, there is NO password 'HOST': 'localhost', 'PORT': '', } } I think the error is due to the fact that I did not create the postgres database on my Linode server. Is it correct? In order to do so, I plan to follow this guide: https://www.linode.com/docs/databases/postgresql/how-to-install-postgresql-on-ubuntu-16-04/ Access my linux server from Bash and activate my virtual enviroment sudo passwd postgres su - postgres psql -d template1 -c "ALTER USER postgres WITH PASSWORD 'newpassword';" I do not understand what 'template1' refers to createdb cocdb psql cocdb I am not sure if this is correct. What else should I do? a) Change the DATABASES in settings.py? If yes, how? b) My postgres USER in my localmachine is called name … -
How to view OpenCv in Django's Screen
Im planning to create a Web app system where i'm going to detect the vehicle's license plate no. using django and openv. The problem is, how to use django to livestream OpenCv? -
Many to Many in two directions
I have a friend that requested something that I was thinking would be simple and quick. It never turns out that way. Quick disclaimer, model design is a krux of mine. I often spend too long perfecting it only to have to rework it several times. Anyway, here is the current state of my model. For everything, it works, except when creating 'raids'. from django.db import models # Create your models here. class PlayerRole(models.Model): """ PlayerRole Model """ role = models.CharField(max_length=20) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.role # this is a inner class which is used to define unique index columns. You can specify multiple columns in a list or tuple. class Meta: unique_together = ['role'] class PlayerClass(models.Model): """ PlayerClass Model """ name = models.CharField(max_length=100) color = models.CharField(max_length=6) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.name # this is a inner class which is used to define unique index columns. You can specify multiple columns in a list or tuple. class Meta: unique_together = ['name'] class Player(models.Model): """ … -
When I run python manage.py migrate I'm getting a Error
when i try to run python manage.py migrate I always get a traceback error. Help me to solve this problem. I have deleted a model called Program. Operations to perform: Apply all migrations: admin, auth, ca, contenttypes, courses, index, languages, online_courses, sessions Running migrations: Applying courses.0007_auto_20190816_2209...Traceback (most recent call last): File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__courses_courses.program_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) return executor(sql, params, many, context) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: new__courses_courses.program_id -
How to interact with client side without finding any request from client
Scenario; 1. Creating QRCODE and displaying it to the client. 2. Client scanning the code from the browser by using its mobile and responding to our server by using callback uri. 3. We find the response from the qr scanner application. 4. But how we can interact with the client side on the behalf of this response, actually client is not requesting directly. I am waiting for your kind response, Thanks. -
Django App using Celery Beat + Worker as Windows Service
I created a Django app that runs tasks using Celery as specified in tasks.py. Currently, I'm running it with 2 command prompts windows, one for beat and one for worker with the following commands as per this post: celery -A main worker -l info -P gevent celery -A main beat -l info I read about supervisor but that is for Linux. I have to make this work on a Windows server. I looked at several posts and many of them are old articles with deprecated libraries. This is the most current one I found. I'm following the instructions, but I don't understand where the beat and worker commands go. How does it know to go to my tasks.py and run? I would have commented to the actual post, but I'm not allowed to post because I have less than 50 reputation. This is the script from the post with my path and directory: '''Usage : python celery_service.py install (start / stop / remove) Run celery as a Windows service''' import win32service import win32serviceutil import win32api import win32con import win32event import subprocess import sys import os import shlex import logging import time # The directory for celery.log and celery_service.log # Default: … -
Django crispy-forms how to create a 2 separated column form
I dug into the crispy forms Layout documentation as well as some stackOverflow threads, trying to create a 2 separated column form. I created this layout on a forms.Form: class BasicForm(forms.Form): label_1 = forms.CharField(label='label1') label_2 = forms.CharField(label='label2') label_3 = forms.CharField(label='label3',help_text='This is help text', widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ) ) And what i get in the browser is: You can see that the TextArea block is not aligned to top. I wanted it to be near label1. When i try this layout: self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid') ) ) Putting the textarea on the first row, i get this: Which also does not look OK. I wanted the label2 block to be right under label1, and not under the TextArea -
How to render a bound Django model form as HTML-safe?
I am trying to return a bound form modified to insert some text and HTML into it. I have done some research and have been able to successfully insert some arbitrary text into a bound form but I haven't found any way render the injected HTML as HTML. It renders as plain text. How can I achieve my goal? Here is the code: # views.py def multi_text(request): if request.method == 'POST': data = request.POST.copy() form = MultilineForm(data=data) if form.is_valid(): cd = form.cleaned_data form.data['text'] = '<i>Hello hello</i>' return render(request, 'multi_text.html', {'form': form}) else: form = MultilineForm() return render(request, 'multi_text.html', {'form': form}) # forms.py class MultilineForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['text'].widget.attrs.update({'class': 'form-control'}, verbose_name='Text', placeholder='Type your text here...') self.data['text'] = '...' class Meta: model = Multiline fields = ['text'] widgets = { 'text': Textarea(attrs={}), } # template.html <form method="post" action="" class="form"> {% csrf_token %} {{ form.text.as_widget }} <span class="input-group-btn"> <input type="submit" value="Check" class="form-control btn btn-primary"> </span> </form> -
How to add more columns to pivot table in many to many relations in Django?
I have 2 models united by a Many to Many relationship, in this case is Policies and Coverages so far it works fine, but I want to add another column to the pivot table since it wont work on any of the modeled tables (I want to add a IntegerField with the name 'amount' so I can store how much money are we covering for that specific coverage in that specific Insurance Police) class Policy(models.Model): """Insurance Policies Model""" number = models.CharField(max_length=25, unique=True) company = models.OneToOneField(Company, on_delete=models.CASCADE) client = models.OneToOneField(Client, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() comission = models.PositiveIntegerField() salesperson = models.ForeignKey(Salesperson, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) rif = models.CharField(max_length=50) phone = models.CharField(max_length=100) class Meta: db_table = 'policies' class Coverage(models.Model): """Coverage of the different types of policies""" name = models.CharField(max_length=55) policies = models.ManyToManyField(Policy) class Meta: db_table = 'coverages' I made the migrations and the pivot table was made without problems, but I don't know how to add another field to the pivot table -
Django model won't update using .update()
I am trying to update a record in my database using info provided by my website's front-end using Model.objects.update(**kwargs) however on running the code I get the following error: "'Record' with this Id already exists." I would have expected that using the "update" method instead of the "create" method would mean that it shouldn't matter / should be expected that there is already a record with the same ID. def find_patient(request): my_form = ExampleForm() if request.method == "POST": my_form = ExampleForm(request.POST) if my_form.is_valid(): UserInfo.objects.update(**my_form.cleaned_data) else: print(my_form.errors) context = { 'form': my_form, 'data_input': DataInput.objects, 'sections': SECTION_CHOICES } return render(request, 'example.html', context) The resulting error looks tike this: idUser info with this Id already exists. Am I misunderstanding the use case for "update" and if so, how would I go about using kwargs to update all fields for a given record in my db? -
Displaying Django templates in a VueJS template
I have the following django index page: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/MaterialDesign-Webfont/3.8.95/css/materialdesignicons.css"> <meta charset="UTF-8"> <title>My test</title> </head> <body> <div id="app"> <h1>TEST</h1> </div> {% render_bundle 'main' %} </body> </html> This template is supposed to call my VueJS frontend, so that i can use Vue on my Django templates, this is the Vue template being called: <template> <v-app id="sandbox"> <v-navigation-drawer v-model="primaryDrawer.model" :clipped="primaryDrawer.clipped" :floating="primaryDrawer.floating" :mini-variant="primaryDrawer.mini" :permanent="primaryDrawer.type === 'permanent'" :temporary="primaryDrawer.type === 'temporary'" app overflow ><v-switch v-model="$vuetify.theme.dark" primary label="Dark" ></v-switch></v-navigation-drawer> <v-app-bar :clipped-left="primaryDrawer.clipped" app > <v-app-bar-nav-icon v-if="primaryDrawer.type !== 'permanent'" @click.stop="primaryDrawer.model = !primaryDrawer.model" ></v-app-bar-nav-icon> <v-toolbar-title>TRADIFY</v-toolbar-title> </v-app-bar> </v-app> </template> Which is just a simple Vuetify default template, really similar to this. Until now, it's alright, i can see the page but i don't see the Django part in my template. To debug it, i added that <h1> TEST </h1> to my index page, so when i open http://127.0.0.1:8000/ i should see the Vue template + the Django template. The problem is that i don't see the <h1>. I think that somehow the Vue/Vuetify components are hiding it, because if i remove everything from the Vue part, except <template></template> i will see the <h1>TEST</h1> appearing. I need to fix this … -
Django and VueJS. Response cookies are not being saved on browser
I have some trouble with cookies in Django. VueJS Frontend makes Django a POST request and in Django POST response I send a cookie and in the browser dev tools I see: Response headers But when I go to DevTools/Application/Cookies, the cookie does not appears. -
Django Methods in Model Not Updating Properly
I created some functions within my models.py in Django that tracks the users' money but for some reason, they only update once Profile is reloaded or when I add transactions. When I try to delete, it does not update until I refresh the page and when I try to search the tags, the method values completely disappear from the page. I have no idea why this happens nor what I can do to fix it. views.py def profile(request): if request.method == 'GET': return render(request, 'users/profile.html', { 'transactions': Transaction.objects.all(), 'balance':Profile.total_balance(request.user), 'income':Profile.total_income(request.user), 'expense':Profile.total_expenses(request.user)}) if request.method == 'POST': form = TransactionForm(request.POST) if form.is_valid(): tag = form.cleaned_data.get('tag') amount = form.cleaned_data.get('amount') category = form.cleaned_data.get('category') user=request.user Transaction.objects.create( user=user, tag=tag, amount=amount, category=category ).save() elif request.method == 'DELETE': id = json.loads(request.body)['id'] transaction = get_object_or_404(Transaction,id=id) transaction.delete() return HttpResponse('') return HttpResponseRedirect(reverse('profile')) def search(request): query = request.GET.get('q') if query and query!="": results = Transaction.objects.filter(Q(tag__icontains=query)) else: results = Transaction.objects.all() transactions = { 'transactions' : results, } return render(request, 'users/profile.html', transactions,{ 'balance':Profile.total_balance(request.user), 'income':Profile.total_income(request.user), 'expense':Profile.total_expenses(request.user)}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def total_balance(User): transaction_list = Transaction.objects.filter(user=User) total_balance_amount = 0 for transaction in transaction_list: if transaction.category=='Income': total_balance_amount += transaction.amount elif transaction.category=='Expense': total_balance_amount -= transaction.amount return total_balance_amount def total_income(User): transaction_list = Transaction.objects.filter(user=User) total_income_amount = 0 … -
How to handle django regex url with vue.js?
I am trying to link vue.js with my Django application but having trouble with URL, I have created my app using Django rest framework,I have a two models with one to many relationship and used regex in url to link each other . I am new to vue.js and it's getting more complicated for me to find a way to connect URL to my Django app models.py: class TreatmentGiven(models.Model): id = models.AutoField(primary_key = True) patient = models.ForeignKey(Ipd,on_delete = models.CASCADE,default = None) medicine_name = models.CharField(max_length = 100,null = True) types_of_doses = models.CharField(max_length = 100,null = True) route = models.CharField(max_length = 100,null = True) number_of_days = models.IntegerField(null = True) views.py : class DischargeViewSet(viewsets.ModelViewSet): queryset = TreatmentGiven.objects.all() serializer_class = TreatmentGivenSerializer filter_backends = (filters.SearchFilter,) search_fields = ('ipd','medicine_name','types_of_doses','route','number_of_days') @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method == "POST": formtwo = DischargeForm(request.POST) if formtwo.is_valid() : formtwo.save() return HttpResponseRedirect(reverse('dischargelist')) else: return HttpResponse(formtwo.errors.as_data()) else: formtwo = DischargeForm() return render(request, 'dischargedetails.html', {'object':object, 'form2': formtwo}) serializers.py: class TreatmentGivenSerializer(serializers.ModelSerializer): class Meta: model = TreatmentGiven fields = '__all__' routers.py: router = routers.DefaultRouter() router.register(r'^(?P<ipd_id>\d+)/dischargedetails/$', DischargeViewSet) urls.py urlpatterns = [ path('api/', include(router.urls)), re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) vue.js : Vue.http.headers.common['X-CSRFToken'] = "{{ csrf_token }}"; new Vue({ el: '#starting', delimiters: ['${','}'], data: { treatmentgivens: … -
Add url to API response on serializers.Serializer
I have a django-application with the followin files models.py from datetime import datetime class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() serializers.py from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() url = serializers.CharField(source='get_absolute_url', read_only=True) in views.py I now define a a ViewSet to return the serialized results. In this class I define a list of comments views.py from rest_framework import viewsets from .serializers import * from .models import Comment from rest_framework.response import Response class CommentViewSet(viewsets.ViewSet): lc = [Comment(email='jan@auto.com', content='hallo mike'), Comment(email='jan@auto.com', content='hallo jan'), Comment(email='jan@auto.com', content='hallo niklas')] def list(self, request): serializer = CommentSerializer(self.lc, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): user = self.lc[int(pk)] serializer = CommentSerializer(user) return Response(serializer.data) When I now call the api (http://127.0.0.1:8000/comments/?format=json) I get the following result [ { "email": "jan@auto.com", "content": "hallo mike", "created": "2019-08-16T16:53:56.371890Z" }, { "email": "jan@auto.com", "content": "hallo jan", "created": "2019-08-16T16:53:56.371890Z" }, { "email": "jan@auto.com", "content": "hallo niklas", "created": "2019-08-16T16:53:56.371890Z" } ] In this response I would have hoped to see a url for each dataset. The error ist probably that url = serializers.CharField(source='get_absolute_url', read_only=True) the source is undefined in the Comment class. However I have no … -
How to submit CSRF_TOKEN with Django and Vue.js
I have a django template using Vue.js that I am using with django-rest-framework as an API. In a form I am including {% csrf_token %} but I still get the following error: {\"detail\":\"CSRF Failed: CSRF token missing or incorrect.\"}". This is the vue function that is getting called. getMarketplaces: function() { this.loading = true; this.$http.get('/app/api/marketplace/') .then((response) => { this.marketplaces = response.data; this.loading = false; }) .catch((err) => { this.loading = false; console.log(err); }) I am using django-rest-framework's router, serializer and viewset. I am using some code from the following tutorial - https://medium.com/quick-code/crud-app-using-vue-js-and-django-516edf4e4217. What have I forgotten to add/do other than including the token? -
django logging sql: can we know the line details in the views.py which executes its database query
I am trying to know the sql executed and also the line from which it got triggered in Django using logging. Django has built in loggers. So using django.db.backends in built logger we can see the raw sql in the console. The below a simple view code in views.py def test(request) import logging l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler()) user_set = User.objects.all() for user in user_set: print(user.last_name) # print is just for testing As we know from Django's Documentation When QuerySets are evaluated When QuerySets are evaluated¶ Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset. and also A QuerySet is iterable, and it executes its database query the first time you iterate over it. So in the above code the database query is executed at the line for user in user_set: I want the following information along with the sql in logging: The line number The filename with fullpath The function name Also if possible the code statement with few lines above and below. Is this possible because this can give me the full picture. I tried using formatter … -
Django calculate mean of two field from a dataset in views.py
hi i have a dataset with population of man and woman by years. i want to calculate mean of man and woman population by years. i mean (man+woman)/2 for 2018 and so on. i wrote the code below views.py def Nufus_ilce(request): dataset = models.population.objects.all() means = context = { 'dataset': dataset, 'means': means, } return render(request, 'population.html', context) population.html {{ dataset.year }} {{ dataset.man }} {{ dataset.woman }} {{ means }} so how can i calculate means? -
Change Django REST Authentication Message when `IsAuthenticated` is on the Settings
I know that you can redefine the message you get from Django REST Framework by overriding the message variable inside your custom permissions classes. However, if I put a specific permission class on my REST_FRAMEWORK settings, I seem to not be able to change the message. In my case, that might be because I have some other added settings for extra authentication procedures. For instance, my REST_FRAMEWORK settings.py looks like: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ], 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } What I want is to alter the top-level message I get from my API, e.g., when I try to login. So far, what I receive is the standard: Authentication credentials were not provided. So... what is the proper way of changing the message in this case? -
Using environment variables from .env in Django Celery
I'm using Django 2.x and Celery 4.3.x In my Django application, I'm using dotenv to serve environment variable from .env file and to load the environment variable, I have following script in the manage.py and wsgy.py files env_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.env') dotenv.read_dotenv(env_file) The environment variables have AWS credentials being used by anymail plugin to send mail using SES. Now, I'm using a Celery task to send the email and running the celery worker from the command line using celery -A myapp worker -l debug The worker is running but when sending an email, it gives an error in the celery task as ERROR/ForkPoolWorker-2] An error occurred (AccessDenied) when calling the SendRawEmail operation: User `arn:aws:iam::user_id:user/my-laptop` is not authorized to permorm this action... It seems trying to connect with my laptop's user instead of using the credentials defined in the .env file. How can I use the .env file to server the environment files to the Celery worker? -
ValueError : not enough values to unpack (expected 2, got 1)
I am trying to send mail through my django application the same way as I have done before, but this one returns the above error. What is wrong with my code? Please help. views def paymail(request,pk): usermail = Payment.objects.get(id=pk) centre = usermail.username.premises client = usermail.username.user.username email = UserProfile.objects.filter(role = 'Centre Manager', premises__address=centre).values_list('user__email')[0] message = 'User' + client + ' from your centre has requested to pay their dues by cash. Kindly take action soon.' msg = EmailMessage('Re : Cash Payment',message, to=[email], ) msg.send() return HttpResponseRedirect(reverse('manager:paymentclient')) The error to be specific is being displayed in msg.send().