Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configure Django session with google app engine datastore (NDB)
Technology stack i am working. Django 3 python3 google ndb Ndb Library : Google Cloud Datastore google app engine standard enviorement i want to manage session with django and google ndb without dbsqlite and mysql database whenever a user login stored in session. i tried saving after login request.session['username'] = username but when deployed on google app engine it throws error. attempt to write a readonly database. probably because session are stored in database in django and google app engine is read only directory. Login and registration is working with flask and Flask-login with google ndb and goole app engine without saving in database. how can i store session or any other idea that i can store user and get throughout the django app with google app engine. -
Getting Image from image field to views.py model
I am making a social media site in Django. I have a page for making a new post. It has a form with a file field to take an image upload. I want to get the image in views.py to save in the database. In the image variable, a string is getting saved with the name of the image. Also, I don't want to use any external form like forms.py. Here I have also tried request.FILES["image"] but it returned an empty dict. Views.py def newpost(request): if request.method == "POST": image = request.POST.get("image") caption = request.POST.get("caption") post = Post(Image=image,Caption=caption,Owner=request.user.username) post.save() return redirect("/") return render(request,"newpost.html") newpost.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Spark X- New Post</title> <link rel="stylesheet" type="text/css" href="{% static 'css/newpost.css' %}"> <script class="jsbin" src="{% static 'js/jquery.js' %}"></script> <link rel="icon" href="{% static 'images/favicon123.png'%}" type="image" sizes="16x16" class="favicon"> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) }; reader.readAsDataURL(input.files[0]); } } </script> </head> <body> <div class="header"> <span class="topband"> <a href="/"><img src="{% static 'images/back icon.png'%}" class="topicon"></a> </span> <div class="logoholder"> <p class="logotext">New Post</p> </div> </div> <div class="mainarea"> <form action="" method="post">{% csrf_token %} <input … -
I am getting an error when trying to click on Like button This page isn’t working HTTP ERROR 405
I am new to Django and trying to implemet Like and Dislike option in Blog application. I have issue where once any logged in user click Like button the browser gives HTTP ERROR 405 Once user click Like button it redirect to PostDetailView (post_detail) I have also added POST in form method as below in post_detail.html page view.py class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = data.total_likes() liked = False if data.likes.filter(id=self.request.user.id).exists(): liked = True else: pass context["total_likes"] = total_likes context["liked"] = liked return context def LikeView(request,pk): if request.method == 'POST': post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) liked = True post.likes.add(request.user) return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) post_detail.html {% extends 'blog/base.html' %} {% block content %} {% csrf_token %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user_post' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted }}</small> </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content|urlize }}</p> {% if object.author == user %} <div> <a class="btn sm btn btn-secondary mb-1" href="{% url 'post_update' object.id %}">Update</a> <a class="btn sm btn btn-danger mb-1" href="{% url 'post_delete' object.id %}">Delete</a> </div> {% … -
Django Rest Framework not saving all foreign key objects
I am going to create a conference and select multiple departments, it is working when I send post request but in GET resquest not getting objects. class DepartmentModel(models.Model): name = models.CharField(max_length=255) conference = models.ForeignKey('ConferenceModel', on_delete=models.CASCADE, null=True, related_name='conference_departments') class ConferenceModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) description = models.CharField(max_length=255, null=True) serializers.py class DepartmentField(serializers.PrimaryKeyRelatedField): def to_representation(self, value): pk = super(DepartmentField, self).to_representation(value) try: item = DepartmentModel.objects.get(pk=pk) serializer = DepartmentSerializer(item) return serializer.data except DepartmentModel.DoesNotExist: return None def get_choices(self, cutoff=None): queryset = self.get_queryset() if queryset is None: return {} return OrderedDict([(item.id, str(item)) for item in queryset]) class ConferenceModelSerializer(serializers.ModelSerializer): conference_departments = DepartmentField(queryset=DepartmentModel.objects.all(), many=True) meeting_participants = SelectItemField(model='account.User', extra_field=['first_name', 'last_name'], many=True) class Meta: model = ConferenceModel fields = '__all__' request { "conference_departments": [ 3, 4, 5, 7, 8 ], "meeting_participants": [ 10, 12, 15 ], "description": "Bla bla bla" } it returns the expected result but If I want to save another object and get all objects it does not return objects but the latest one does. here you can see from the image below id: 19 is the latest saved object it returns department objects but id: 18 does not! can anybody help me please? any help would be appreciated! Thanks in advance! -
Django Debug Toolbar with DRF JWT
How can i use django debug toolbar with DRF and jwt authentication. When using DRF with jwt auth, I cannot use the browser(DRF static files). Thank you in advance -
Django union and if statement based on the table in database
My views.py look like this: def home(request): cars = Car.objects.all() bikes = Bikes.objects.all() vehicles_together = cars.union(bikes, all=True).order_by('power') context = { 'vehicles_together': vehicles_together, } return render(request, 'home.html', context) In my HTML I have got a redirect to the detail page, where I need to pass an id. If there was only one table involved, it would look like that: href="{% url 'detail' car.id %}" But I have data from 2 tables displayed and I need to write an If statement based on the table. Is it possible to write an If statement when union is involved? It would have to look like this: if data from table car then href="{% url 'detail' car.id %}", but if data from table bike it would pass bike.id instead of car.id. My detail view looks like this: def detail_view(request, id): car = get_object_or_404(Car, id=id) bike = get_object_or_404(Bike, id=id) photos = PostImage.objects.filter(car=car) photos2 = PostImageBike.objects.filter(bike=bike) return render(request, 'detail.html', { 'car':car, 'bike':bike, 'photos2':photos2, 'photos':photos }) -
How to forward raw email from django
So I have a raw email string I'd like to send to another recipient. I'd like to use Django for this (have 3.1 running). I know I can take my input (say raw_email) and make it a python email.Message running email.message_from_string(raw_email) but from there I'm not sure the best way. I can imagine I could do something weird like instantiate a new instance of django.core.mail.EmailMultiAlternatives and pass each argument 1 by 1 to the constructor, but that seems heavyweight. FWIW I'm not using SMTP, hence the desire to stick with django code/apis. -
functions inside view function in django did not work
I have this python code to recognize color from an image. When I run it manually from pycharm it works perfectly. Then I try to put this inside my web app (I'm using django), I put this code inside my views.py as a view function but it did not work. Can someone explain to me where is my mistake or how to solve this? def identification(request): root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() img = cv2.imread(file_path) clicked = False r = g = b = xpos = ypos = 0 index = ["color", "color_name", "hex", "R", "G", "B"] csv = pd.read_csv('planning/codes.csv', names=index, header=None) def getColorName(r, g, b): minimum = 10000 for i in range(len(csv)): d = abs(r - int(csv.loc[i, "R"])) + abs(g - int(csv.loc[i, "G"])) + abs(b - int(csv.loc[i, "B"])) if d <= minimum: minimum = d colorname = csv.loc[i, "color_name"] return colorname def draw_function(event, x, y, flags, param): if event == cv2.EVENT_MOUSEMOVE: global r, g, b, xpos, ypos, clicked clicked = True xpos = x ypos = y b, g, r = img[y, x] b = int(b) g = int(g) r = int(r) cv2.namedWindow('Machining Process Identification') cv2.setMouseCallback('Machining Process Identification', draw_function) while 1: cv2.imshow("Machining Process Identification", img) if clicked: cv2.rectangle(img, … -
how to prevent submitting a form with empty CKEditor in django
In my django project, I use Django CKEditor for getting richtextfield in a message form. I want to prevent the user from submitting an empty message. this is my simplified form in one of my templates: <form action="{% url 'contact' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12"> <div class="form-group"> <div class="row"> <div class="col-1 mr-auto"> <label for="message" class="col-form-label">Message:</label> </div> <div class="col-10 ml-auto"> <textarea name="message" id="message" class="form-control" maxlength="4096" onkeyup="textCounter(this,'counter',4096);" autofocus required ></textarea> </div> </div> </div> </div> </div> <!-- Submit button --> <div class="form-row"> <div class="col-12 col-sm-12 col-md-2 col-lg-2 col-xl-2 mx-auto"> <div class="form-group"> <button class="btn text-capitalize font-weight-bold text-light btn-block" type="submit" value="Send" > Send </button> </div> </div> </div> </form> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <script src="//cdn.ckeditor.com/4.15.0/full/ckeditor.js"></script> <script> CKEDITOR.replace( 'message' ); CKEDITOR.config.allowedContent = true; CKEDITOR.config.removeFormatAttributes = ''; CKEDITOR.config.ignoreEmptyParagraph = false; CKEDITOR.config.toolbarGroups = [ { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] }, { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'forms', groups: [ 'forms' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' … -
AUTH_USER_MODEL refers to model 'Sistema.User' that has not been installed with Pyinstaller
AUTH_USER_MODEL refers to model 'Sistema.User' that has not been installed with Pyinstaller I'm using a custom User to add fields to this model. However, I was unable to solve the problem with pyinstaller. Could anyone help? Very grateful for the attention. server@srvr:~/app$ ./dist/sistema Traceback (most recent call last): File "django/apps/config.py", line 178, in get_model KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "django/contrib/auth/__init__.py", line 157, in get_user_model File "django/apps/registry.py", line 211, in get_model File "django/apps/config.py", line 180, in get_model LookupError: App 'Sistema' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> File "manage.py", line 17, in main File "django/core/management/__init__.py", line 401, in execute_from_command_line File "django/core/management/__init__.py", line 377, in execute File "django/__init__.py", line 24, in setup File "django/apps/registry.py", line 122, in populate File "django/contrib/auth/apps.py", line 22, in ready File "django/contrib/auth/__init__.py", line 161, in get_user_model django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'Sistema.User' that has not been installed [694099] Failed to execute script manage -
GCP Cloud NLP API error when running in heroku in django
my django project is perfectly running in local computer, but when i deployed to heroku it shows error when GCP api calls. i have used GCP NLP apis and i also want to know that how to set GOOGLE APPLICATION CREDENTIALS? as i already set but showing this error on heroku server only. error is - If the request argument is set, then none of the individual field arguments should be set.enter image description here -
Static files serving from Google Cloud Console in Django
I am using GCP to serve static files. But Django is using a signed URL which contains expire googleserveraccessId and etc. Please tell me how I can use an unsigned URL which only has a path. my settings.py file DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'xyzxyzxyx' GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "project/filename.json" ) STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'myapp/static') ] STATIC_URL = '/static/' STATIC_ROOT = 'https://storage.googleapis.com/{}/static/'.format(GS_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) MEDIA_ROOT = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) -
Exception Value: Module "storages.backends.gcloud" does not define a "GoogleCloudMediaStorage" attribute/class
I am working on uploading media file to google cloud storage from my django app running on cloud engine. But while submitting file, I am keep getting error The above exception (module 'storages.backends.gcloud' has no attribute 'GoogleCloudMediaStorage') was the direct cause of the following exception:. Following error screen shot and code snippets for more details. Any help on this is much appreciated. settings.py from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'credential.json')) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudMediaStorage' GS_PROJECT_ID = 'project-test' GS_BUCKET_NAME = 'project-bucket' MEDIA_ROOT = '/media/' UPLOAD_ROOT= 'media/cad_files' MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) gcloud.py is from django.conf import settings from storages.backends.gcloud import GoogleCloudStorage from storages.utils import setting from urllib.parse import urljoin class GoogleCloudMediaStorage(GoogleCloudStorage): """ Google file storage class which gives a media file path from MEDIA_URL not google generated one. """ def __init__(self, *args, **kwargs): if not settings.MEDIA_URL: raise Exception('MEDIA_URL has not been configured') kwargs['bucket_name'] = setting('GS_BUCKET_NAME', strict=True) super(GoogleCloudMediaStorage, self).__init__(*args, **kwargs) def url(self, name): """.url that doesn't call Google.""" return urljoin(settings.MEDIA_URL, name) views.py def file_upload(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): file = form.save(commit=False) # commit=False Read file but Don't save the file yet file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter file.customer = request.user.customer # Get current … -
Django: https://127.0.0.1:8000 not working in django
Long story short, I created a django project and used the django for professionals book 2.2 as a reference(Made a couple more fields in the models). However, once I reached the security chapter and tried running the docker commands in the terminal, I get a programming error. After researching and trying to debug, I decided to delete all migrations from the project, the volume from the docker container, and delete/comment out certain files/code. From here, I reran all the migrations and now when I check my terminal, I still get 21 unapplied migrations and "Starting development server at http://0.0.0.0:8000/". When I click on the link, I get the "Disallowed Host at / ...Invalid HTTP_HOST header:..." I am just wondering what went wrong because it seems to me that my docker-compose.yml and settings.py seems to be contributing to this error. I am trying to get my terminal to get the link to "https://127.0.0.1:8000/". settings.py: I am using the postgres database DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = [] docker-compose.yml: I left out the secret key version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - DEBUG=1 - ENVIRONMENT=development volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: … -
I am tried to setup the saleor in my windows 10 but its giving error
in dlopen raise OSError(error_message) # pragma: no cover OSError: no library called "cairo" was found cannot load library 'C:\msys64\mingw64\bin\libcairo-2.dll': error 0x7e cannot load library 'libcairo.so': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0x7e -
Displaying model data in Django using for loop
Im attempting to display all the course Names in my Course Model, {% for course in object_list%} <li>{{ course.courseName}} </li> {% endfor %} </ol> Heres a snippet from the HTML page Im trying to display them in. here's my models.py # Create your models here. SEMESTER_CHOICES = ( ("SPR 21", "SPR 21"), ("FA 21", "FA 21"), ("SPR 22", "SPR 22"), ("FA 22", "FA 22"), ("SPR 23", "SPR 23"), ("FA 23", "FA 23"), ("SPR 24 ", "SPR 24"), ("FA 24", "FA 24"), ) PROGRAM_CHOICES = ( ("Architectural Science","Architectural Science"), ("Civil Engineering","Civil Engineering"), ("Computer Information Technology","Computer Information Technology"), ("Computer Science","Computer Science"), ("Construction Management","Construction Management"), ("Electrical Engineering","Electrical Engineering"), ("Engineering Technology Management","Engineering Technology Management"), ("Manufacturing Engineering","Manufacturing Engineering"), ("Mechanical_Engineering","Mechanical_Engineering") ) # declaring a Student Model class AddCourse(models.Model): program = models.CharField( max_length = 20, choices = PROGRAM_CHOICES, default = 'Architecural Science' ) courseName = models.CharField(max_length=250) semester = models.CharField( max_length = 20, choices = SEMESTER_CHOICES, default = 'SPR 21' ) preRequisites = models.TextField() def __str__ (self): return self.courseName and here is my views.py from django.shortcuts import render from .models import AddCourse from django.contrib.auth.decorators import login_required # Create your views here. @login_required def currentpathway(request): return render(request, "SEAS_Course_Planner/home.html") @login_required def newpathway(request): return render(request, "SEAS_Course_Planner/newpathway.html") Nothing is printing out and … -
Why is Django giving me a completely different image from what I have?
I've been practising Django for quite awhile and so I've been redoing projects to get myself familiar with the whole process. However, when I started a new project and made a static folder, the image appearing on the website is not the new image I have in my static folder, but is the image from the previous project which has already been deleted. In fact, I've already deleted everything used in that project, but still the image I am trying to use appears as the previous one. On top of that, when I inspect element and look at sources, the image is from my previous django project and not of my new static folder. Is this a bug or feature or did I mess something up? -
I'm learing about Conda environment.yml and I'm not sure how to get Conda to find a certain version of dependancy
So I want to be able to build a environment that contains all libs I need for my project that im going to port to Docker. So far my yml looks like this: name: wt channels: - anaconda - conda-forge - defaults dependencies: - python=3.7.* - django=3.1.1 - wagtail=2.11 So judging by the compatibility link I have the correct versions to run Wagtail but when I goto call conda env create -f environment.yml I get: ResolvePackageNotFound: - wagtail=2.11 So I had a look on the Conda repo and I can't see a version 2.11. How would I get V 2.11 when can only get with v1 or v 2.7 which are both incompatible? I have checked Wagtail Github and they are on version 2.7 but version 2.1 has LTS and thats why I would like to use it. -
how to get data from gst api while click on submit button in django
I have a field gst in that when user input the data get from the gst api .i am totally beginers and don't know how to do this. -
How do you add a constraint? in the models.py in Django to check the variable the models get?
I have a code as the following: # models.py class UserFollower(models.Model): user_id = models.ForeignKey(CustomUser, related_name="following", on_delete=models.CASCADE) following_user_id = models.ForeignKey(CustomUser, related_name="followers", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) def __str__(self): return f"{self.user_id} follows {self.following_user_id}" Now here, I want to check when the data is passed, if the user_id equals the following_user_id, it will output a message saying something like "It isn't possible" and not save the model. Of course later in the development, I wouldn't have the "Follow" button or something like that associated with the same user, but in this case, how would I do so?? Or is it something I can't do in the models.py and do it in the views.py? -
Django admin panel has no styling
When I started my project and went to the admin panel the admin panel had no styling There is no styling as usual. What should I do to fix it. Thank you -
Django not creating new object instance
Hey guys I'm getting an error when I try to submit a reply to a post on my forum app. It says that Reply is not defined. But, as you can see, it is defined in my Models.py file and I have run makemigrations and migrate. I have opened the database with a viewer and I can see that the Reply table exists with all the required fields. Anyone know why I'm getting error? views.py: def reply(request, id): query = NewPost.objects.filter(id = id) return render(request, "network/reply.html", {"queries": query}) def replied(request): body = request.POST.get("body") username = request.POST.get("username") postID = request.POST.get("postID") #new = Reply.objects.create(postID = postID, username = username, body = body) #new.save() return render(request, "network/replied.html") Models.py: class Reply(models.Model): postID = models.IntegerField(default=0) username = models.CharField(max_length=64) body = models.CharField(max_length=64, default="") rating = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True) reply.html: {% extends "network/layout.html" %} {% block body %} {% for query in queries reversed %} <h2>Reply to {{query.username}}'s Thread</h2> <form method="POST" name="replied" action="/replied"> {% csrf_token %} <input type="text", name="title", value="Re:{{query.title}}" readonly> <p>{{query.username}} said: </p> <textarea name="oldBody" readonly>{{query.body}}</textarea> <p></p> <textarea name="body" placeholder="Enter Thread Body"></textarea> <p></p> <p></p> <input type="hidden" value={{ user.username }} name="username"> <input type="hidden" value={{ query.id }} name="postID"> <input type="submit" value="Reply"> </form> {% endfor %} … -
Django TestCase helper function inheritance
After writing tests for my Django Model Validators I found I was duplicating a lot of code and wanted to simplify it using some sort of helper function. This answer may be a solution but I can't translate it to my problem. The code example below will return the following error message: AttributeError: 'ExampleTestCase' object has no attribute 'assertRaised' from django.test import TestCase from django.core.exceptions import ValidationError from .models import ExampleModel class ExampleTestCase(TestCase): def setUp(self): ExampleModel.objects.create(string='1-2-3') def test_string_validation(self): example_model = ExampleModel.objects.get(pk=1) field_name = 'string' expected_raise = ['1', 'a-a-a', '1--23'] # These inputs should raise Validation Errors expected_ok = ['9-8-7', '2-2-2'] # These inputs should not raise Validation Errors self.helper_func( obj=example_model, field_name=field_name, raise_list=expected_raise, ok_list=expected_ok ) # Duplicated code I want to avoid: # example_model.string = '1' # self.assertRaises(ValidationError, example_model.full_clean) # example_model.string = 'a-a-a' # self.assertRaises(ValidationError, example_model.full_clean) # example_model.string = '1--23' # self.assertRaises(ValidationError, example_model.full_clean) # example_model.string = '9-8-7' # example_model.full_clean() # self.assertEqual(example_model.string, '9-8-7') # example_model.string = '2-2-2' # example_model.full_clean() # self.assertEqual(example_model.string, '2-2-2') def helper_func(self, obj, field_name, raise_list, ok_list): for i in raise_list: setattr(obj, field_name, i) # Current code uses try, except blocks but below is desired self.assertRaised(ValidationError, obj.full_clean) for i in ok_list: setattr(obj, field_name, i) # Current code uses try, except blocks … -
Django Has to Keep Updating The Backed Updated Info
I need technical advice about Django and I have no idea where to even look for the general direction. Right now, I have an app that keeps track of work/shift schedule. It is an Android/iOS app with a Django backend and I am the backend engineer. When a user updates their schedule and makes a backup to our server, the phone sends a long sequence of requests. This sequence starts with 'backup' URI and ends with 'vacationData' URI. When the backup is successful, the last request my server will receive will be the 'vacationData' URI. What I am trying to achieve is this: just like in Google Spreadsheet, whenever the user updates their schedule and make a backup, the "shared schedule" URI has to update accordingly. I began setting up the "share schedule" URI with Django Signals that listens to the "vacationData" URI. However, now I realize that the only user sends GET request to "shared schedule" URI and thus the shared timetable won't be updated unless the user chooses to send a new GET request to "shared schedule". Is there any way to send the updated(newly backed up) schedule info to the client regardless of whether they requested it … -
How to get msgctxt in .po file with Django and pgetttext()
I am writing a notification module for a booking app which has English and Spanish. It is supposed to be flexible enough to deal with any model and any status change (e.g. created, updated, cancelled etc). The get_subject() function will prepare a 'subject' line for the notification using the related object's model name (e.g. Appointment) and the status verb. So we should get 'Appointment 123ABC modified' or 'Payment 789XYZ created' etc. I have it working translationwise all apart from allowing for the grammatical gender of words in Spanish. So 'Appointment 123ABC modified' would be 'Cita 123ABC actualizada' whereas say, 'Payment 123ABC modified' would be 'Pago 123ABC actualizado'. I know the solution is to use pgettext(context, string) along with having the msgctxt in the .po file, but I just can't figure out how to get manage.py makemessages to add the msgctxt when it preps the .po file. I have tried various ways of editing the .po directly but I am getting errors when running compilemessages (Execution of msgfmt failed: backend/locale/es/LC_MESSAGES/django.po:3966: duplicate message definition...) and makemessages just overwrites my edits anyway. I am not sure whether all I need is the right format for the po file or whether I need the …