Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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(). -
Why django creates new default permissions even with default_permissions=() in the Meta?
I setup some test app to check django's behaviour. Makefile for testing: clean: rm db.sqlite3 mig_model: python manage.py migrate flights 0001 mig_all: python manage.py migrate show1 show2: python manage.py shell -c "from django.contrib.auth.models import Permission; print(list(Permission.objects.values_list('id', 'codename')))" all: clean mig_model show1 mig_all show2 removing old db migrating to the point when first own model is created after migration default permissions should be created in post_migrate signal. But I specify in Model.Meta that no default permissions should be created check all permissions - I can see that they were indeed generated migrate everything else, which is just 1 more data-migration where I delete all permissions in the system show all permissions again and I can see that old permission were deleted and new ones created after migration (they all have new ids) models.py: class Schedule(models.Model): flight_day = models.DateField() class Meta: default_permissions = () permissions = () -
How to hide a list element in html
I want to hide a list element when I click on a button. I tried it with in Javascript. This does not work. document.getElementById("1").children[0].style.display = "none" <script> function hid(){ document.getElementById("1").children[0].style.display = "none" } </script> <div class="container-fluid"> <div class="column"> <div class="col-md-2 "> <ul class="list-group" id="1"> <li id="2"><a href="{% url 'search:barbars' %}" class="list-group-item list-group-item-action">barbar <div class="image-parent"> <img src="http://cool-web.de/icons/images/024800/024768.ico" class="img-fluid" alt="nothing"> </div> <!-- The Button --> <button onclick="hid" class="btn btn-outline-success my2 my-sm-0" type="submit">Search</button> -
Define python directory in cpanel
My Cpanel host has 2 instances of Python. Python 2.6 - /usr/bin/python Python 3.6 - /usr/bin/python3.6 If I run this script: #! /usr/bin/python print "Content-type: text/html\n\n" print "<html>Hello world!</html>" It works! But If it doesn't work (Internal error 500) if I run: #! /usr/bin/python3.6 print "Content-type: text/html\n\n" print "<html>Hello world!</html>" I know python 3.6 is installed and in the specified path, as you can see below: Thanks. -
Django annotate(...) taking a dictionary
I have somewhat complex django query with a lot of .annotate: query = ModuleEngagement.objects.filter(course_id=course_id)\ .values('username')\ .annotate( videos_overall=Sum(Case(When(entity_type='video', then='count'), output_field=IntegerField()))) \ .annotate( videos_last_week=Sum(Case(When(entity_type='video', created__gt=seven_days_ago, then=1), output_field=IntegerField()))) \ .annotate( problems_overall=Sum(Case(When(entity_type='problem', then='count'), output_field=IntegerField()))) \ .annotate( problems_last_week=Sum(Case(When(entity_type='problem', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( correct_problems_overall=Sum(Case(When(entity_type='problem', event='completed', then='count'), output_field=IntegerField()))) \ .annotate( correct_problems_last_week=Sum(Case(When(entity_type='problem', event='completed', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( problems_attempts_overall=Sum(Case(When(entity_type='problem', event='attempted', then='count'), output_field=IntegerField()))) \ .annotate( problems_attempts_last_week=Sum(Case(When(entity_type='problem', event='attempted', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( forum_posts_overall=Sum(Case(When(entity_type='discussion', then='count'), output_field=IntegerField()))) \ .annotate( forum_posts_last_week=Sum(Case(When(entity_type='discussion', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( date_last_active=Max('created')) Does annotate accept a dictionary as a parameter so I can move all the annotates into it? If so, what would be the syntax? -
Celery task.status method rises a exception : AttributeError: module <module_name> has no attribute 'DoesNotExist'
Stack: django = "==2.2.2" django-celery-beat = "==1.4.0" celery = "==v4.3.0rc1" python_version = "3.7" I have a class that import some data from csv/xls file and save da data, here is my celery config: CELERY_TASK_ALWAYS_EAGER = False CELERY_BROKER_URL = config('REDIS_BROKER_URL') CELERY_RESULT_BACKEND = config('REDIS_RESULT_URL') CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Here is where i call my task (some class based view): def form_valid(self, form): if self.request.is_ajax(): form.save() instance = form.save() kwargs = { 'corporation_id': self.corporation.id, 'file_id': instance.id, } task_id = import_file_task.apply_async( kwargs=kwargs, ) instance.tas_id = task_id instance.save() return JsonResponse( { 'form_status': 'Success', 'task_id': str(task_id), } ) return super().form_valid(form) Here is where i call my task: @celery_app.task(bind=True) def import_file_task(_, corporation_id, file_id): sale_file = SaleFile.objects.get( id=file_id, corporation_id=corporation_id, ) if sale_file.type == PRODUCT_FILE: error = ProductImporter( corporation_id=corporation_id, file_id=file_id, product_file=sale_file, ).save() elif sale_file.type == RECEIVABLE_FILE: error = ReceivableImporter( corporation_id=corporation_id, file_id=file_id, receivable_file=sale_file, ).save() else: raise ValueError('File type is not valid') task = AsyncResult(sale_file.tas_id) task.info = error task.status = 'COMPLETED' Here is where i try to poll the task status and i get the error! class TaskStatus(View): def get(self, request): task_id = request.GET.get('_task_id') task = AsyncResult(task_id) print(task) print(task.state) #HERE IS THE ERROR print(dir(task)) #THE STATUS APPEAR HERE success_response = ( { 'status': ['state: ' ], … -
Adding the class name to the selection options. Django - forms
I have a very simple forms.py PROVINCE_CHOCIES = [ (1, 'New York'), (2, 'Las Vegas'), (3, 'San Francisco'), ] class SearchForm(forms.Form): province = forms.ChoiceField(choices=PROVINCE_CHOCIES) Is it possible to add a class to the drop-down list? My form in htmlu looks like this: <option value="1">New York</option> <option value="2">Las Vegas</option> <option value="3">San Francisco</option> The expected result is: <option value="1" class="A">New York</option> <option value="2" class="A">Las Vegas</option> <option value="3" class="D">San Francisco</option If possible? how can I do this in my forms.py file, or using some external plug? The solution will be useful for me to use the simple dependent/chained drop-down list. As in this exampe. Any help will be appreciated. -
Convert context into serialize data
I have a function in django app which I want to convert into serializer data to use it in react via API. class DispatchHistory(ListView): model = DispatchPlan context_object_name = 'plan' template_name = 'classroom/teachers/dispatcher_history.html' def get_queryset (self): return DispatchPlan.objects.filter(owner_id=self.request.user.pk) def get_context_data (self, **kwargs): context = super().get_context_data(**kwargs) dispatch_plans = DispatchPlan.objects.filter(owner_id=self.request.user.pk) dis_items = [] for i in dispatch_plans: it = i.items obj_list = [] for j in it: obj = get_object_or_404(ItemBatch, id=j) obj_list.append(obj) dis_items.append(obj_list) context['t_items'] = dispatch_plans context["ttt"] = dis_items return context I created a Serializer for this: class dispatchhistorySerializer(serializers.ModelSerializer): class Meta: model = DispatchPlan fields = "__all__" and tried this: class DispatchHistoryAPI(APIView): serializer_class = dispatchhistorySerializer def get(self, request, **kwargs): try: dispatch_plans = DispatchPlan.objects.filter(owner_id=request.user.pk) context = {} dis_items = [] for i in dispatch_plans: it = i.items obj_list = [] for j in it: obj = self.serializer_class(get_object_or_404(ItemBatch, id=j)).data obj_list.append(obj) dis_items.append(obj_list) context['t_items'] = dispatch_plans context["ttt"] = dis_items #what comes here ? return JsonResponse({ "details": context }) except: raise return JsonResponse({ "details": "Failed " }, status=500) How do I use this serializer to convert the context data to serializer data to use it in an API? -
How to make a copy of a table before delete ( django pre_delete )
I'm new to Django so I guess my Question is basic but I need your help. I have a table called Answer. class Answer(models.Model): id = models.AutoField(auto_created=True,primary_key=True) sku = models.CharField(max_length=128, default=secrets.token_urlsafe(16), editable=False) user = models.ForeignKey(User,on_delete=models.SET_NULL, null= True) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL, null=True) content = models.TextField() created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) it's for a forum. Before a user deletes his/her answer, I want to make a copy of the answer. I want to make a new table that has the values of this table, for example, a table named DeletedAnswer that has all the values in Answer table. thanks -
Cancel impact of css from bootstrap4 (Chrome)
I added a bootstrap template to my Django project and I have a different element size compared to the source code. https://startbootstrap.com/previews/business-frontpage/ I found out that issue deals with h-100 Removed h-100 in dev tools I removed h-100 from .css file, but result is the same. How can I cancel impact of h-100 style ??? My code: https://github.com/mascai/datat_site -
I tried to run the command : "py manage.py runserver" but i's not working anymore,why?
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it I tried to run the command: py manage.py runserver but it gives the error mentioned above, the problem isn't only that, I've been using django for days and it was working fine until today -
masking port number django runsslserver in nginx
I have django project running in ngnix in port 4321. i am runing django project using runsslserver which is returning me https using below command python manage.py runsslserver --certificate /etc/nginx/ssl/XXXXXXX.pem --key /etc/nginx/ssl/XXXXXXX.key 0.0.0.0:4321 my website is ready when i run like https://mywebsite.com:4321 I want to show it as https://mywebsite.com/miniweb i have 2 files in /etc/nginx/sites-enabled which is default and ssl Tried below code and few others with many changes in ssl file but not working server { server_name mywebsite.com:4321; listen 443; # tried this because its in https return 301 https://mywebsite.com/miniweb$request_uri; } Please help me -
How to serve static files with Django via mod_wsgi and Apache on a windows server?
So I know this question has been asked a lot, but I have attempted every answer and still came to no solution. The problem is that static files are not found (404 error) when I open my website. (css files throw an Refused to apply style from 'example.com/static/css/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled., however I think this is due to the css not being found.) I am running Apache 2.4 on a windows 10, 64-bit server with python 3.7 installed. I installed django in a virtualenvironment using virtualenvwrapper-win. Here the httpd.conf: Define ALPHAROOT d:/django/alpha LoadFile "c:/users/truninger-admin/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/truninger-admin/envs/djangoenv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/truninger-admin/envs/djangoenv" WSGIScriptAlias / ${ALPHAROOT}/alpha/wsgi.py WSGIPythonPath ${ALPHAROOT} <VirtualHost *:80> ServerName alpha.truningerag.ch Alias /static/ d:/django/static/ <Directory d:/django/static> Require all granted </Directory> WSGIScriptAlias / ${ALPHAROOT}/alpha/wsgi.py <Directory d:/django/alpha/alpha> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> And the settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") And the wsgi.py: import os,sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alpha.settings') application = get_wsgi_application() from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() The odd thing here is that if I comment out application = get_wsgi_application() the server raises an exception django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Things … -
Optimising API queries using JSONField()
Initial opening: I am utilising postgresql JSONFields. I have the following attribute (field) in my User model: class User(AbstractUser): ... benefits = JSONField(default=dict()) ... I essentially currently serialize benefits for each User on the front end with DRF: benefits = UserBenefit.objects.filter(user=self) serializer = UserBenefitSerializer(benefits, many=True) As the underlying returned benefits changes little and slowly, I thought about "caching" the JSON in the database every time there is a change to improve the performance of the UserBenefit.objects.filter(user=user) QuerySet. Instead, becoming user.benefits and hopefully lightening DB load over 100K+ users. 1st Q: Should I do this? 2nd Q: Is there an efficient way to write the corresponding serializer.data <class 'rest_framework.utils.serializer_helpers.ReturnList'> to the JSON field? -
django-crontab not executing django custom command
I am using django-corntab to execute my Django Commands after specific interval of time. I am having trouble while defining django settings for CORNJOBS. I read the doc of django-corntab and mentioned the path of my django command class but its not working. management/commands/send_email.py class Command(BaseCommand): def handle(self, *args, **kwargs): try: msg = EmailMessage('Hi! I am using Cron!', 'I am using django commands and cron for scheduled tasks.', to=['manju.negi14@gmail.com']) msg.send() self.stdout.write(self.style.SUCCESS('Successfully sent email')) except Exception: raise CommandError('Sorry! something went Wrong!') settings.py INSTALLED_APPS = [ .... # third party packages 'django_crontab', # local apps 'mynewapp',] CRONJOBS = [ ('*/1 * * * *', 'mynewapp.management.commands.send_email.Command', '>> '+os.path.join(BASE_DIR,'log/mylogfile.log 2>&1'))] -
How to have multiple integer or Charfields that belong to same formfield in django
I need to group 4 integer or charfields under a same form field like FORMFIELD: No of students in each year? INTEGERFIELDS: 2016-2017 2 INTEGERFIELDS: 2017-2018 4 INTEGERFIELDS: 2018-2019 3 INTEGERFIELDS: 2019-2020 5 I need only one main formfield and other fields must belong to the same category plzz help me writing the code in django .Thanks in advance -
Pass both name and dictionary via urls.py
I am trying to pass a value in a dictionary via a url. Django tells me I can do this via a 3rd parameter , but this seems to conflict with setting the name value for the link. I have this in my project urls.py at the moment, which it doesn't like at all (presumably because it has 4 parameters): urlpatterns += [re_path(r"^$", views.HomePageView.as_view(), name="homepage", {"display": "all"}] I'd also like to be able to pass {"display": "user"} in urls.py in one of the apps. The reason for this is so I can use the same list view, and just change the query to return either all records (which will be displayed most recent first in paginated list view on the homepage), or only those owned by the current logged in user (when they opt to view their records). I am thinking that in the list view I will interrogate this value and use it in get_queryset to determine which records I want. How can I pass both the name and the dictionary via the url? Or am I approaching this whole thing incorrectly? -
Displaying foreign key with DRF create api
Display Foreign Keys correctly I have 2 models in DRF: class Location(models.Model): country = models.CharField(max_length=50, null=False) city = models.CharField(max_length=50, null=False) currency = models.CharField(max_length=20, null=False) def save(self, *args, **kwargs): super(Location, self).save(*args, **kwargs) class Meta: unique_together = ('country', 'city', ) permissions = ( ('can_view', 'Can View'), ('can_modify', 'Can Modify'), ) def __str__(self): return (self.country + ":" + self.city) class Holiday(models.Model): country = models.ForeignKey(Location, related_name='location_country', on_delete='CASCADE') city = models.ForeignKey(Location, related_name='location_city', on_delete='CASCADE') holiday_date = models.DateField(auto_now=False, auto_now_add=False) def save(self, *args, **kwargs): super(Holiday, self).save(*args, **kwargs) def __str__(self): return (self.country + ":" + self.city + ":" + self.holiday_date) class Meta: unique_together = ('country', 'city', 'holiday_date') When trying to create a Holiday, for country and city field I get dropdown as below: country: country_name:city_name city: country_name:city_name I want to display these fields correctly so that country and city fields are displayed properly. I understand the current output is because of str definition in Location models and I need that to display the table fields in django admin. How can I overwrite these for the API only. Below is the create API I am using: class HolidayCreateView(generics.CreateAPIView): serializer_class = HolidayCreateSerializer def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) class HolidayCreateSerializer(serializers.ModelSerializer): class Meta: model = Holiday fields = ('id', … -
How should I make a model object remember the result of a field's pre_save?
I have a model Task and two calculated fields key and key_sort and a related field content_object. key should be copied from the related object: self.content_object.key key_sort should be a variant of the value in key (suitable for natural sorting, so A10 becomes a0010, but that's another story) I have implemented this using custom fields which override pre_save: class KeyField(CharField): def pre_save(self, model_instance, add): return model_instance.content_object.key class NatsortField(CharField): # ... def pre_save(self, model_instance, add): return natsort_str(getattr(model_instance, self.for_field)) class Task(Model): key = KeyField() key_sort = NatsortField(for_field='key') content_object = ForeignKey(Thing) When saving, the key field is saved correctly to the database, but the model instance is not updated, so in the pre_save for the key_sort field, the new value of key is not available. Thus the key_sort field will not be calculated correctly. Should we always update model_instance in pre_save? Should I have plain CharFields and do the calculations by overriding Model.save instead? -
How to keep a list of all active users of the web app?
I am new to Django. I have been trying a store a list of all active ip addresses which are using the web app currently. My approach is to add a new entry to the database table with the IP address of the user as soon as a person logs in. And keep updating the timestamp column (LastPingTime) in the table with the current time every 3 seconds or so. So the active ip addresses would be all the rows in the table whose LastPingTime is less than or equal to 3 seconds from the current time. But I don't know to go about it. Please help with this. How do I run a periodic function which does this for every new user? Thanks in advance.