Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.ImproperlyConfigured: WSGI application 'wsgi.application' could not be loaded; Error importing module
Can someone help me figure this one out please. My peer was able to run my code on their Mac just fine. I have been unable to get past this error. I am encountering it while running the app in Windows in PyCharm using a virtualenv. Unhandled exception in thread started by .wrapper at 0x04E22150> Traceback (most recent call last): File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\core\servers\basehttp.py", line 44, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\utils\module_loading.py", line 15, in import_string raise ImportError("%s doesn't look like a module path" % dotted_path) from err ImportError: application doesn't look like a module path The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\Tacfa\Google Drive\Code\CS33A\project3_env\lib\site-packages\django\core\servers\basehttp.py", line 49, in get_internal_wsgi_application ) from err … -
How do I output a django.forms.SelectMultiple for a models.ManyToManyField so that the existing relations are rendered ordered?
I am using django-1.9 and select2 to enable my users to select, create and order relations between section and image data in their books. models.py class Section(django.Model): title = models.CharField(max_length=500) parent = models.ForeignKey('self', related_name='subsections', null=True, blank=True) phrases = models.ManyToManyField(Image, through=ImageOrdering, blank=True, related_name='sections') class Image(models.Model): name = models.CharField() class ImageOrdering(models.Model): section = models.ForeignKey('Section', on_delete=models.CASCADE) image = models.ForeignKey('Image', on_delete=models.CASCADE) order = models.IntegerField() class Meta: ordering = ['order', ] forms.py class SortedSelectMultiple(forms.SelectMultiple): def render(self, name, value, attrs=None, choices=()): """ The selected values need to be rendered sorted and last. """ choices = list((image.pk, str(image)) for image in Image.objects.filter(id__in=value)) choices.sort(key=lambda image: value.index(int(image[0]))) self.choices.queryset = Images.objects.exclude(id__in=value) return super(SortedSelectMultiple, self).render(name, value, attrs, choices) class SectionForm(forms.ModelForm): class Meta: model = Section fields = ('title', 'images') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), # 'core_phrases': forms.SelectMultiple(attrs={'class': 'form-control select2-multiple-sortable'}), 'core_phrases': SortedSelectMultiple(attrs={'class': 'form-control select2-multiple-sortable'}), } def save(self, commit=True): """ All this hackery to preserve the order. """ this = super(SectionForm, self).save(False) if commit: this.save() self.instance.images.clear() sort_order = dict(self.data).get('images') images = list(self.cleaned_data['images']) images.sort(key=lambda image: sort_order.index(str(image.pk))) for index, image in enumerate(images): ordering, created = ImageOrdering.objects.get_or_create(image=image, section=self.instance, order=index) ordering.save() return self.instance I've found that this is the only way I can preserve the order Select2 gives to its elements after users drag and drop … -
Exclude instance user from Django autocomplete light form
I am trying to do 3 things. 1) exclude the instance user from a django autocomplete light dropdown, 2) restrict that user from being chosen (in the backend), and 3) customize the validation message if that user is chosen. As of now, I have #2 that seems to be working, but I cannot figure out how to change the validation error message and how to exclude it from the drop down all together. Here is my code: forms.py class UserSurveyQueueForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['queue'].queryset = User.objects.all().exclude(pk=user) class Meta: model = UserSurveyQueue fields = ('queue',) widgets = { 'queue': autocomplete.ModelSelect2Multiple( url='user-autocomplete', ), } views.py class UserAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return User.objects.none() # Here is where I want to remove the instance user from the list of available options qs = User.objects.all() if self.q: qs = qs.filter(username__icontains=self.q) return qs def set_user_queue(request, username): u = get_object_or_404(User, username=username) employee = Employees.objects.filter(employee_id=u.id) # Get current user's queue to display as instance queue_exists = UserSurveyQueue.objects.filter(user=u) if not queue_exists: queue = None else: queue = queue_exists.get(user=u) if request.method == "POST": form = UserSurveyQueueForm(request.POST, instance=queue, user=u.id) if form.is_valid(): form.instance.user = u form.save() return HttpResponseRedirect(reverse('home')) else: form = UserSurveyQueueForm(instance=queue, user=u.id) return … -
Passing model object between views django (Object is not JSON serializable)
I've made model objects for my forms (Didn't use form models) and I want the user to progressively fill out the model as they go through the different web pages (views). To do this I need to obviously pass the model object through views. I've already tried sessions as you'll see below however the model object is not JSON Serializable. Is there anyway I can get around this? def home(request): request.session['client'] = user_information(answers=personal_injury_answers()) return render(request, 'homescreen.html') def firstStep(request): client = request.session['client'] if request.method == 'POST': preliminary_user_info = dict(QueryDict(query_string=request.body)) client.zipcode = int(preliminary_user_info['identifier'][1]) print(client.zipcode) if preliminary_user_info['identifier'][0] == 'personal_injury': return redirect('piuserform') else: return redirect('home') -
Django river user based UI
I am trying to design a workflow using Django-river. A part of this UI will be used by engineers to approve/ disapprove a request. I do not want the engineers to access the Django-admin UI , is there any way I can bring the workflow dashboard to the main front end UI or design a separate UI for the workflow? Please help -
ModelChoiceField widget attrs have no effect
I have this model form that I have to render manually but the ModelChoiceField attributes don't have any effect. class ExtendedUserForm(forms.ModelForm): favourite_provider = forms.ModelChoiceField(queryset=Provider.objects.all()) class Meta: EXPERTISE_CHOICES = ( ('N', 'Novice'), ('B', 'Beginner'), ('I', 'Intermediate'), ('E', 'Expert'), ) model = ExtendedUser labels = { 'expertise': 'Expertise', 'favourite_provider': 'Favourite provider', 'job_title': 'Job title', 'job_place': 'Company/Institution', } widgets = { 'expertise': forms.Select(choices=EXPERTISE_CHOICES, attrs={'class': 'form-control'}), 'favourite_provider': forms.Select(attrs={'class': 'form-control'}), 'job_title': forms.TextInput(attrs={'placeholder': 'Your job title', 'class': 'form-control'}), 'job_place': forms.TextInput(attrs={'placeholder': 'Your company/institution', 'class': 'form-control'}), } exclude = ['user', 'history', 'favourite_services'] The rendered HTML is as follow: <div class="form-group"> <label><label for="id_expertise">Expertise:</label></label> <select name="expertise" required id="id_expertise" class="form-control"> <option value="" selected>---------</option> <option value="N">Novice</option> <option value="B">Beginner</option> <option value="C">Competent</option> <option value="P">Proficient</option> <option value="E">Expert</option> </select> </div> <div class="form-group"> <label><label for="id_favourite_provider">Favourite provider:</label></label> <select name="favourite_provider" required id="id_favourite_provider"> <option value="" selected>---------</option> <option value="1">AWS</option> </select> As you can see the second select doesn't have the class attribute despite that I precised that here 'favourite_provider': forms.Select(attrs={'class': 'form-control'}). How to fix that ? -
All users see the same login input content online for different web application instances
I have React + Django app. The problem is when two different users in different machines tries to log in they are seeing the same input. It's like a magic singletone. One user prints email and in another PC in the same page it displays. That very strange because it's standard uwsgi Django with NO socket realization. -
Django Rest AttributeError at /api/v1/person 'ConfigurationSerializer' object has no attribute 'initial_data'
models.py class Configuration(mongoengine.DynamicEmbeddedDocument): storage = mongoengine.IntField(required=True) notify = mongoengine.BooleanField(required=True) class PolicyConfig(mongoengine.DynamicDocument): account_id = mongoengine.StringField(required=True) policy_id = mongoengine.StringField(required=True) configuration = mongoengine.EmbeddedDocumentListField(Configuration) serializers.py class ConfigurationSerializer(serializers.EmbeddedDocumentSerializer, serializers.DynamicDocumentSerializer): class Meta: model = Configuration fields = '__all__' class PolicyConfigurationSerializer(serializers.DynamicDocumentSerializer): configuration = ConfigurationSerializer(many=True) class Meta: model = PolicyConfig fields = '__all__' Here is what my typical document looks like: { "account_id": "11231354", "policy_id": "AAAABBBQAA", "configuration": [{"storage": 151, "notify": false}] } The requirements to it as follows: Both Configuration and PolicyConfig must be expandable (dynamic) documents meaning their fields may appear and disappear and it's fine but I would also like to verify some fields. The whole thing does work if I change configuration = mongoengine.EmbeddedDocumentListField(Configuration) to configuration = mongoengine.EmbeddedDocumentField(Configuration) and inside the PolicyConfigurationSerializer set configuration = ConfigurationSerializer(many=False). The object looks this way: { "account_id": "11231354", "policy_id": "AAAABBBQAA", "configuration": {"storage": 151, "notify": false} } This way it works but I have a problem trying to make the configuration field a list, not another document... I've tried to do it for too long, I've totally run out of any sane ideas what might be causing the issue. It yields the AttributeError at /api/v1/person 'ConfigurationSerializer' object has no attribute 'initial_data' error. -
'Listen()' value in socket not worked
Im need is limited quantity the connections, in listen is set s.listen(2), but I don't see any exception and I can created three new connections and more. Where is the mistake? def func(): global addr host = socket.gethostbyname(socket.gethostname()) port = 9000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(2) while True: conn, addr = s.accept() if addr not in clients_addr: addr.append([conn, addr]) current_addr = addr thread = Thread(conn, current_addr) thread.start() -
JavaScript list import in Django
I'm trying to implement a map in my website using Google v3 API. I'm trying to save the coordinates of a path in the server that the user generates by clicking on the map. I'm doing all this in JavaScript since the API is in JavaScript. For the backend I'm using Django. When I'm creating the path, everything gets stored in a JavaScript array. My question is, how do I store that array in a django model? My research until now has not been successful and most people suggest using geodjango for the project. But I personally found it very complicated so I only expect answers that are regarding the google map API. -
Linking Mulit User Profile Together
So i have this Accounts where I have two types of users example: intern, and HR Supervisor. So my models is class User(AbstractUser): is_intern = models.BooleanField(default=True) class InternProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='intern_profile') bio = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=30, blank=True) SuperVisor= models.ForeignKey(HRProfile, null=True, related_name='employee') class HRProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='hr_profile') company_name = models.CharField(max_length=100, blank=True) website = models.CharField(max_length=100, blank=True) Now lets suppose i have two HR managers name Alice and Bob. Both Alice and Bob have three interns underneath them working, lets say Sam, David, Katty works under Alice and Drake, Taylor and Nik works under Bob. Now I want to Bob to see only his intern and Alice can only see her intern not other way round, so guys i m new and learning django any advice related to this , cause i cant able to find the way around this. Thank you -
Django 2 make comment filed error
recently I decide to add a comment block to my template in my django app but when I add it to my app , I faced to this error : add_comment_to_post() got an unexpected keyword argument 'item_id' my template.html: {% block content %} <form action="#" method="post" novalidate="novalidate"> {% csrf_token %} {{ form.as_p }} <div class="row"> <div class="col-md-4"> <p><label>Name*</label><input type="text" name="your-name" value="" size="60" class="" aria-required="true" aria-invalid="false"></p> </div> <div class="col-md-4"> <p><label>Email*</label><input type="text" name="your-email" value="" size="60" class="" aria-required="true" aria-invalid="false"></p> </div> <div class="col-md-4"> <p><label>Website</label><input type="text" name="your-website" value="" size="60" class="" aria-required="true" aria-invalid="false"></p> </div> <div class="col-md-12"> <p><label>Message</label><textarea name="your-message" cols="60" rows="3" class="" aria-invalid="false"></textarea> </p> </div> </div> <div class="dividewhite2"></div> <p> <button type="button" href="{% url 'add_comment_to_post' pk=item.pk %}" class="btn btn-lg btn-darker">Post Comment </button> </p> </form> {% endblock %} my models.py : from django.db import models from datetime import date from django.utils import timezone # Create your models here. class Blogs(models.Model): main_image = models.ImageField(upload_to='Blogs/', help_text='This Image Is Gonna To Be Show At Blogs Page.', blank=False, default='') class Comment(models.Model): post = models.ForeignKey('Blog.Blogs', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text my form.py: from django.forms import ModelForm from .models import Blogs, Comment class CommentForm(ModelForm): class Meta: … -
Django's get_current_language always returns "en"
In my Django 2.0 site, I want to set the lang atribute of the html tag to the current locale's language. In my base.html which other templates extend, I use get_current_language in the following way {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}"> ... </html> The site has translations for multiple languages. If I switch the language in the browser, I see the correct translations, but the lang attribute will always contain en. In my settings.py I have USE_I18N = True. What else am I missing? -
django cannot delete audio file because it is used by audio player
I have created a django website in which users can upload music files and play them using the HTML5 audio player Those are my models from django.db import models from django.db.models.signals import post_delete from django.dispatch import receiver # Create your models here. class User(models.Model): id=models.AutoField(primary_key=True) email=models.CharField(max_length=30,unique=True,null=False,blank=False) password=models.CharField(max_length=30,unique=True,null=False,blank=False) name=models.CharField(unique=True,max_length=40,null=False,blank=False) def __str__(self): return self.name.title()+","+self.email class Song(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=100,null=False,blank=False) artist=models.CharField(max_length=100,null=False,blank=False) user=models.ForeignKey(User,null=False,blank=False) file = models.FileField(verbose_name="File",blank=True) def __str__(self): return self.artist+" - "+self.title # I can't delete the song file because it's used by the audio player in html @receiver(post_delete, sender=Song) def submission_delete(sender, instance, **kwargs): instance.file.delete(False) This the html code for displaying songs {% for song in songs %} <div class="card"> <div class="card-body"> <h5 class="card-title">{{song.artist}} - {{song.title}}</h5> <audio controls> <source src="/media/{{song.file}}" type="audio/ogg" /> </audio> <a href="/delete/{{song.id}}" onclick="confirm_delete_song('/delete/{{song.id}}')" class="delete" > <i class="material-icons" title="Supprimer">&#xE872;</i></a> </div> </div> {% endfor %} And the view that deletes the song def delete(request, song): if 'logged' not in request.session: return HttpResponseRedirect('/') else: try: Song.objects.get(id=song).delete() return HttpResponseRedirect('/') except: return HttpResponseRedirect('/') A screenshot of the page When I click on the delete button, the song is removed from the database but the file is not deleted even if I haven't played the audio yet Any help would be appreciated -
Django testing can't find existing database table
I have a Django project and I want to make a test using python manage.py test, but I get this error: File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/ db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "ReservationsManagerApp_reservation" does not exist The table does exist. In fact, the end-point that saves and retreives data from it works perfectly, and I can see the table en Postgres Admin tool. The error only raises when running test. Thanks for your help. -
How to solve the error : polls is not defined by django beginner tutorial
every time I run it to get polls application I get that it's not defined why?? and would you tell me please whats wrong with my code and whenever I put from . import views I don't know why it takes import the module, not the dot. Note: As well I tried to turn the Debug off or turn it to false and I still get the same error -
(Django) Is there a way to have a list on django that isn't separated by comma's
I am looking to get an array or list of some sort that can be appended to, sort of like this custom form I am using for a many to many field I have. form list example The reason I can't just make another table and use the same form is that each entry on this list may be different. I have found ArrayField, but we are trying to avoid just using commas. -
Will Django allow requests from multiple Ajax function with one AjaxSetup that contains csrf?
The title can't handle my question completely, sorry. I have three Ajax function in my Django template. First one sends comment requests, the second one updates a value to database and the third one manages login/register process. All of them are being triggered by a button. As you know, Django says that use CSRF on your Ajax requests too. So, I use like this: function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } var csrftoken = $('input[name=csrfmiddlewaretoken]').val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); Can this function handle all my Ajax requests in one template? Do I need to do extra stuff? -
Can't access all the Values from django MultiWidget, from request.POST?
I'm unsure why I cannot access both fields from the MutliWidget after the post request. I've tried various things such as request.POST.get('name'), which just returns 0 I've also tried accessing the values from value_from_datadict(self, data, files, name) with no luck. What confuses me the most is when I use print(request.POST) I can see that the form inside the post request does contain both values of the MultiWidget, however I can only access one for instance when I print request.POST, this is printed to the console: <QueryDict: {'total_travel_time': ['0', '0']}> however when I try: request.POST.get('total_travel_time') I only receive 0. What is going on here?????? This is driving my slightly crazy. This is my MutliWidget. class TotalTimeWidget(forms.widgets.MultiWidget): """ Total time Widget used in TotalTimeField """ CON_STYLE = "margin-left: 0.25in;" INPUT_STYLE = "width: .5in; display: inline; " \ "vertical-align: top; " \ "margin-left: 0.0675in; " \ "margin-right: 0.0675in;" hour_attrs = dict() min_attrs = dict() name = '' def value_from_datadict(self, data, files, name): data = super(TotalTimeWidget, self).value_from_datadict(data, files, name) print(data) return data def decompress(self, value): print("decompress_called", value) if value: return value else: return ['', ''] def __init__(self, name, attrs=None, hours=0, minutes=0): hour_attrs = {'min': 0, 'max': 12, 'class': "hour", 'value': hours} min_attrs = {'min': … -
I need to modify my Function based view "FBV" to be class based view "CBV"
i need to make some modifications on my code,as i have a function based view and need to change it to be class based view FBV: def Adress_Use_Prev(request): # print(request.POST) address_type=request.POST.get('address_type',"shipping") address_id=request.POST.get("Address-id") request.session[address_type+"_address_id"]=address_id next_ = request.GET.get("next") next_post = request.POST.get("next") redirected_path = next_ or next_post or None if is_safe_url(redirected_path, request.get_host()): return redirect(redirected_path) return redirect("/") what is the best solution to convert this fucntion to be CBV i tried on the following code, but i failed class UsePrevAddress(NextUrlMixin,FormView): # def get_success_url(self): # return self.get_next_url() def form_valid(self, form): print("test5") address_type = self.request.POST.get('address_type', "shipping") address_id = self.request.POST.get("Address-id") self.request.session[address_type + "_address_id"] = address_id return self.get_next_url() def form_invalid(self, form): super().form_invalid(form) the form.html: {% if address_qs %} <form method="POST" action="{% url "cart:checkout-Address-reuse" %}"> {% csrf_token %} {% for Address in address_qs %} <label for="address-{{ Address.id }}"> <input id="address-{{ Address.id }}" type="radio" name="Address-id" value="{{ Address.id }}"/> {{ Address.Address_line_1 }}, {% if Address.Address_line_2 %} Address.Address_line_2, {% endif %} {{ Address.State }},{{ Address.Postal_Code }},{{ Address.city }} </label><br/> {% endfor %} {% if next_url %} <input type="hidden" name="next" value="{{ next_url }}"> {% endif %} {% if address_type %} <input type="hidden" name="address_type" value="{{ address_type }}"> {% endif %} <button type="submit" class="btn btn-success">Use Address</button> </form> {% endif %} urls.py: url('^checkout/Address/reuse$',UsePrevAddress.as_view(),name="checkout-Address-reuse"), -
Exponential backoff in kubernetes?
I am new to kubernetes and I am having trouble tracking down an exponential backoff signal I am observing on my Jmeter load tests for response times. I have a kubernetes service that is running between 4-32 pods with horizontal pod autoscaling. Each pod is running a Gunicorn WSGI serving a django backend. All of the different k8s services are behind nginx reverse proxy, which redirects incoming traffic directly to Service’s VIP. Nginx sits behind Amazon ELB which is exposed to end-user web traffic. ELB ultimately times out a request after 60 secs. Each gunicorn server is running one worker with 3 greenlets and has a backlog limit of 1. So it can only server 4 requests at any given time and immediately returns an error response for any extra requests nginx tries to send its way. I am guessing that these error requests are then being caught and retried with exponential backoff, but I can’t quite make out where this is happening. As far as I know, nginx can’t be the source for the exponential retries, as it is serving only one upstream endpoint for a request. And I couldn’t find anything in the documentation that discusses exponentially timed … -
django-cors-headers dont work with DRF(Django Rest Framework)
I'm trying to add django-cors-headers to my django rest API to add the HTTP header Access-Control-Allow-Origin in the answer, but I have not managed to make it work. I have followed the instructions in the documentation but I can not get it to work. Here is the content of my settings.py file: ... INSTALLED_APPS = [ 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'hvad', 'rest_framework.authtoken', 'rest_framework_swagger', 'accounts.apps.AccountsConfig', 'rest_auth', ] ... MIDDLEWARE:[ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ... # CORS Config CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False I'm using: Django 1.11.14 django-cors-headers 2.4.0 djangorestframework 3.8.2 python 3.6.5 pip 10.0.1 Windows 10 -
Custom error page with django 2.0
here is my code : def handler500(request, exception): response = HttpResponseServerError('error.html', {}, context_instance=RequestContext(request)) response.status_code = 500 return response but i have a : TypeError: handler500() missing 1 required positional argument: 'exception' What am i missing ? -
Jinja2 "as" tag not working?
I have this code in index.html: {% url 'cronjobs:remove-job' as remove_job_url %} And I want to use it further down in the same HTML file multiple times, e.g.: <a href="{{ remove_job_url }}">Remove job</a> According to this answer, I think I got everything right. However, the variable remove_job_url is null. Nothing is printed to the anchor tag. I have loaded the Jinja2 into my settings.py -> TEMPLATES as described in the documentation, yet it does not seem to work. Any ideas what might be wrong? (this also happens when I use the {% trans ... as trans_var %} tag, the trans_var is again - empty) -
Django Save data inputted inn one model instance to another model
I have a model call Teacher that teaches classes which has ' rating' attribute. After each class each student in his class can comment and review his performance. They do so by creating a new object instance of OccurrenceRating. How do I make each new 'rating' from the OccurrenceRating instance save to the teacher instance 'rating' and make sure the average is correct. I've been able to display the average amount for each teacher by getting all the OcccurrenceRating objects with that teacher and the get the average for that but I've not been able to save that value. How do I do this? Models.py Teacher Model class ProfileTeacher(models.Model): created = models.DateTimeField(auto_now=False, auto_now_add=True, blank = False, null = False, verbose_name = 'Creation Date') user = models.OneToOneField(app_settings.USER_MODEL,blank=True, null=False) first_name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'First Name') last_name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Surname') phone_number = models.CharField(max_length = 15, null=True, blank = True, verbose_name = 'Phone Number') city = models.ForeignKey(City, null=True, blank = True, verbose_name = 'City') postal_code = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Postal Code') adress = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Address') …