Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comment model has replies, but reply cannot have replies
I am creating comments. Each comment can have replies, but replies cannot have replies. I have tried to perform this on serializer and views level, but nothing works. model: class Comment(models.Model): reply_to = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='replies') Serializer: class CommentSerializer(serializers.ModelSerializer): episode = serializers.PrimaryKeyRelatedField(read_only=True) user = serializers.StringRelatedField() class Meta: model = Comment fields = '__all__' def validate_reply_to(self, value): if value: comment = Comment.objects.get(pk=value) if comment.reply_to: raise serializers.ValidationError('Cannot reply to reply') Viewset: class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer def perform_create(self, serializer): try: episode = Episode.objects.get(id=self.kwargs.get('episode_id')) except Episode.DoesNotExist: raise NotFound serializer.save(episode=episode, user=self.request.user) -
HTML/Jinja2: Calendar getting displayed below meetings
I am making a web app in Python/Django and I am trying to display a calendar above some meetings on the Dashboard page of the app. I have made a calendar using the HTMLCalendar class, and I have passed both the list of meetings and the calendar as variables to the HTML template to be rendered. These variables are called meetings and calendar respectively. I have the following code for dashboard.html, which has the code for displaying the meetings and the calendar: {% extends 'Project/base.html' %} {% load static %} {% block title %}Dashboard{% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static "css/calendar.css" %}"> {% endblock %} {% block content %} <body style="width:100%; height:100%"> {% if calendar %} <div id="calendar"> {{ calendar }} </div> {% endif %} {% if meetings|length > 0 %} <div id="gallery" style="width:80%; height: 100%; margin-left:12.5%; margin-top: 3%; padding: 2%;"> {% for meeting in meetings %} <div style="width: 38.5%; height: 400px; border: solid 2px #f4b955; display:inline-block; border-radius: 10px; padding:2%; margin-right: 3%; margin-bottom: 2%; box-shadow: 2px 4px #f4b955"> <div id = "left" style="height: 100%; width: 50%; display: inline-block"> <div id="top-left" style="height: 100%"> <img src="{{meeting.image}}" style="height: 100%; width:100%; object-fit: contain; display: block"> </div> </div> <a href="{% url … -
Unit test failing due to migration error caused by loaddata in django
My unit test are failing with the following error django.db.utils.OperationalError: Problem installing fixture '/Users/vivekmunjal/chargepoint/code/Installer/api/installer/fixtures/country.json': Could not load installer.Country(pk=1): (1054, "Unknown column 'display_order' in 'field list'") Basically one of my migrations is loading data in country model from a fixture, but the model has added some extra fields in them, so when the migrations runs it try to insert a column which is not yet created and fails. Can anyone suggest any remedy for the same? -
I'm not able to run sonnarqube on my project
I've installed both sonarqube server as well as scanner and chnaged the properties file also.But still it's giving the below issue. ERROR: Error during SonarQube Scanner execution java.lang.IllegalStateException: Project home must be an existing directory: C:\Django\webapplication\webapplication\Djangowebapplication I've my project in the C:\Django\webapplication directory.Below is my configuration file for sonar-project.properties file sonar.projectKey=devsonarqube sonar.projectName=webapplication sonar.projectVersion=1.0 sonar.projectBaseDir=C:\Django\webapplication sonar.sources=C:\Django\webapplication -
Post JSON data via API and create a related model in Django Rest Framework
I am performing an API project with the Django Rest Framework. I have a Django model defined in the following way: class Profile(CreatedUpdatedModel, models.Model): owner = models.ForeignKey(Owner, models.CASCADE) start_date = models.DateField(gettext_lazy("Start"), help_text=gettext_lazy("YYYY-MM-DD format")) end_date = models.DateField(gettext_lazy("End"), help_text=gettext_lazy("YYYY-MM-DD format")) category = models.ManyToManyField(OwnerCategory) tags = models.ManyToManyField(OwnerTag) I perform a POST API call from the web page that pass a JSON data like the following : {start_date: '2019-11-20' , end_date: '2019-11-21', owner: '65', category: '[20, 21, 22]', tags: '[]' } I would like to save on the database the model with the parameter I passed with JSON Here is my REST view in views.py: @permission_required() class ProfileViewSet(ViewSet): @action(detail=False, methods=['post']) def new_profile(self, request, pk=None): serializer = serializers.ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and here it is my REST serializer in serializers.py class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = ('owner', 'start_date', 'end_date', 'categories', 'tags', ) The problem is that the statement serializer.is_valid() is False. Where I am wrong with this code ? Can someone help me ? -
How to use sphinx to document django: blacklisting and whitelisting modules in settings?
I am running a django project with multiple apps. I am trying to document it using sphinx. I installed sphinx and configured everything (-I think correctly-). To produce documentation I run sphinx-apidoc -o . .. and then make html. Now what happens is that sphinx creates modules for all my migrations but it doesn't include any views (which I guess is most important). Problem could be all the import errors: (I don't want to install all the imports in my virtual env) WARNING: autodoc: failed to import module 'adapters' from module 'myapp.users'; the following exception was raised: No module named 'allauth' WARNING: autodoc: failed to import module 'admin' from module 'myapp.users'; the following exception was raised: Traceback (most recent call last): .....this keeps going for a while like this WARNING: autodoc: failed to import module 'merge_production_dotenvs_in_dotenv'; the following exception was raised: No module named 'pytest' WARNING: autodoc: failed to import module 'admin' from module 'myapp'; the following exception was raised: No module named 'psycopg2' WARNING: autodoc: failed to import module 'models' from module 'myapp'; the following exception was raised: No module named 'psycopg2' WARNING: autodoc: failed to import module 'urls' from module 'myapp'; the following exception was raised: No module … -
Add ajaxresponse inside a textarea
I have made an ajax call to backend using the following code: <script > var frm = $('#identity'); var textare = $('#textare'); textare.keyup(function() { $.ajax({ type: frm.attr('method'), url: "{% url 'creatd-new' %}", data: frm.serialize(), success: function (data) { $('#some_div').html(data.is_true); }, }); return false; }); </script> backend dumps a "is_true" in the JsonResponse which successfully gets printed but when I try to print the same value of "is_true" inside a text area,it is not working. I have tried the following: $('#some_div').html( <textarea rows="4" cols="50">data.is_true</textarea> ); $('#some_div').val( <textarea rows="4" cols="50">data.is_true</textarea> ); $('#some_div').append( <textarea rows="4" cols="50">data.is_true</textarea> ); but these are not working. -
pyodbc session error when django project is downloaded from gitlab
i have a django project which works fine when not uploaded i have uploaded it to gitlab with following command: 1. git clone ssh://git@gitlab****dcms-api.git 2. git checkout dcms_sso 3.git add . then i took the same code from git lab: 1. git clone ssh://git@gitlab****dcms-api.git 2. git checkout dcms_sso just changed the application name in manifest file. when i tried to run it throws following error: File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect ERR self.connection = self.get_new_connection(conn_params) ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/sql_server/pyodbc/base.py", line 307, in get_new_connection ERR timeout=timeout) ERR pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") ERR The above exception was the direct cause of the following exception: ERR Traceback (most recent call last): ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner ERR response = get_response(request) ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__ ERR response = self.process_response(request, response) ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/middleware.py", line 58, in process_response ERR request.session.save() ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/backends/db.py", line 81, in save ERR return self.create() ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/backends/db.py", line 51, in create ERR self._session_key = self._get_new_session_key() please let me know if more log to be uploaded or if my backend.py should be uploaded -
Error db.sqlite3 locked when deploying Django using option Continuous deployment in Azure App Service
When i'm deploying a Django project (tried two of them) in Azure App Services (Linux), i always get the error SQLite3 database locked: OperationalError: database is locked,when trying to log in. Has someone an idea or workaround to resolve the problem without changing to another database? I changed the default timeout as mentioned by the official django documentation: https://docs.djangoproject.com/en/2.2/ref/databases/#sqlite-notes, but the problem remain. I want to keep using sqlite database! Thanks for your help. -
Return some variables from a function in views.py to a js file with render and POST - Django
Since some days I'm trying to execute a python function from my js file. I'm doing it with Ajax. For now, I'm executing the function and passing some values with POST but I can recover this info. This is my function inside views.py def vista_sumar(request): ctx = 'none' if request.method == 'POST': a = request.POST['a'] b = request.POST['b'] c = int(a) + int(b) ctx = {'Result':c} print('sss',ctx) return render(request,'main.html',ctx) I know the call to this function is working because in the js file a=3 and b=1 and it always print sss {'Result': 4} but then it never comes back to the js. I try it too with return HttpResponse(c) and the behaviour is better because arrive something to the js but it is undefined. Can't I use render in this situations? Can somebody help me, please? My js is: $('#prueba').click(function() { alert('boton pulsado'); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); alert(csrftoken) a =1; b =3; $.ajax({ url: '/../../prueba/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'a': a, 'b': b, }, dataType: "json", cache: true, success: function(response) { console.log(response.Result); alert(response.Result); } }); alert('fin') }); With return HttpResponse(c) the console.log and the alert show undefined. Thank you very much. -
Django templates lookup through list nested in dictionary
I have nested json response, which i have to render in template, but not full output, just selected items. The problem with lookup is that this list have dictionary with another list inside and i need to get value from there. json [ { "type": "part", "id": "TESTA_SSL", "attributes": { "commut": "YES", "imaxtime": "23595999", "imintime": "00000000", "prot": [ "PESITSSL" ], "rauth": "*", "sap": [ "6666" ], "state": "ACTIVEBOTH", "trk": "UNDEFINED", "syst": "UNIX", "tcp": [ { "type": "cfttcp", "id": "1", "attributes": { "cnxin": "2", "cnxinout": "4", "cnxout": "2", "retryw": "7", "host": [ "testa.net" ], "verify": "0" } } ] }, "links": { "self": "https://testa.net:6666/api" } }, { "type": "part", "id": "TESTB_SSL", "attributes": { "commut": "YES", "imaxtime": "23595999", "imintime": "00000000", "prot": [ "PESITSSL" ], "rauth": "*", "sap": [ "6666" ], "state": "ACTIVEBOTH", "trk": "UNDEFINED", "syst": "UNIX", "tcp": [ { "type": "cfttcp", "id": "1", "attributes": { "cnxin": "2", "cnxinout": "4", "cnxout": "2", "retryw": "7", "host": [ "testb.net" ], "verify": "0" } } ] }, "links": { "self": "https://testb.net:6666/api" } }, ] i need to lookup for TESTA_SSL, testa.net and TESTB_SSL, testb.net value from template level. How can I do that? Or is there a possibility to "flatten" lil bit this json? for now … -
Django throwing "app not ready" while calling function in it's AppConfig.ready
I am using django v2.2.6. I am trying to implement my own system checks. I followed the documentation and even StackOverflow: Register system checks in appconfigs-ready. I am still getting an django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. According to the stack trace, it goes back to the first Model declared before calling self.checks_app_ready() and throwing the previous exception. I have only one App, so I do not understand why it is not ready when I try to register a check in my AppConfig.ready(self). -
Django include app urls in my main url.py
I have a django site with 3 application. in my urls.py i try to include the specific app's url in this fashion: url(r'^oferty/', include('oferty.urls', namespace='oferty')), but when i start or migrate my app i get this error: ../site-packages/django/urls/conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. How can i include apps urls in my main url.py file? I use django 2.2 so many thanks in advance -
Django Move Project from Windows Host to Linux Host (and Deploy)
I'm trying to Move my Django App to a real Server (or deploy it there, self-hosted) but everything, I have tried so far, does nothing except displaying errors. For Example: If I try to deploy the app on my Windows machine I get security errors he won't pass. py -3 manage.py check --deploy System check identified some issues: WARNINGS: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SS L connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. ?: (security.W018) You should not have DEBUG set to True in deployment. System check identified 3 issues (0 silenced). Even if I set Debug to False he won't pass the last two Security Checks. AND in Debug State False the Website even does not load … -
How to execute multiple conditions in 1 view in Django
I have 2 if else conditions within the 1 function based view. When the page renders it executes the first condition and return but do not execute the second condition. Please take a look on code. View: Def Dashboadr(request): '''Birthday Slider''' today = date.today() DoBworkers = CoWorker_Data.objects.filter(dob__day=today.day, dob__month=today.month).all() if DoBworkers.exists(): return render(request, 'dashboard/Dashboard.html', {'DoBworkers': DoBworkers}) else: messages.success(request, 'There is no birthday today.') return render(request, 'dashboard/Dashboard.html') '''Payment Slider''' today = date.today() three_days_before = today - timedelta(days=4) #start_date = end_date - timedelta() paymentNotification = CoWorker_Data.objects.filter(joiningDate__day__lt=three_days_before.day).all() if paymentNotification.exists(): c = context = ({ 'paymentNotification': paymentNotification }) return render(request, 'dashboard/Dashboard.html', c) else: messages.success(request, 'No record found.') return render(request, 'dashboard/Dashboard.html') return render(request, 'dashboard/Dashboard.html', c ) Ignore indentation.. -
Django Server: python manage.py runserver - Not Found: /url/
Hi I am a newbie when it comes to Django and am getting stuck on what seems a very basic issue. When I create a new Django project in the conda prompt and then start the django server, it always seems to try redirect to a url that doesn't exist. Steps taken in conda prompt: django-admin startproject mysite cd mysite python manage.py runserver This will start the server with the usual http://127.0.0.1:8000/ local site however when loading this up in my chrome browser it always redirects to http://127.0.0.1:8000/blog/ I see in the conda prompt that Not Found: /blog/ is shown screenshot ## I haven't changed any code in the project, so the urls.py haven't set a redirect in the url pattern or anything like that. How do I stop this redirect from happening? Note: if I do the following python manage.py runserver 7000 to change the port this redirect doesn't happen, but I am trying to solve for why its happening on 8000 Many thanks! -
Issue in django 1.7.2 version while doing makemigrations
when created new model and executing makemigrations in django 1.7.2 version django.core.exceptions.FieldError: Local field u'id' in class 'PhotoFeatureImage' clashes with field of similar name from base class 'PhotoFeature' -
How to add a select to filter table with JQuery dataTable
I am newbie and develop an app on Django I use for the first time the DataTable with bootstrap 4 and it works but I would like to add select with 3 options that enable user to filter table on a specific column I read options in documentation but did not found what I need is it possible to do it? thanks, -
my django query: how to improve the speed of list view
List page is paginated and displaying only 10 journal posts. Despite this, there are 95 queries being performed. It's affecting the page load speed. Instead of loading <1 second it's taking around 4-5 seconds. Here are my code, please check and let me know how to optimize. views.py class PostListView(LoginRequiredMixin,ListView): model = Post paginate_by = 10 def get_queryset(self): qs = super(PostListView, self).get_queryset().filter(Q( Q(language_id__in=self.request.user.native_language), ~Q(user_id__in=self.request.user.forbidden_user_list))).order_by('-created') return qs def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['list_type'] = 'all' models.py class Post(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=60) text = models.TextField() native_text = models.TextField(blank=True) created = models.DateTimeField(default=timezone.now, db_index=True) # updated = models.DateTimeField(auto_now=True) # is_corrected = models.BooleanField(default=False) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='posts_liked', blank=True) language = models.ForeignKey('account.Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.text def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) @property def get_correctors(self): from account.models import Profile as User result = list(set(User.objects.all().filter((Q(correctedrows__post_id=self.id) | Q(perfectrows__post_id=self.id) | Q(comment__post_id=self.id))))) return result -
How to validate username and password in dajngo rest framework?
Here I am trying to register users.But the validate_username is not working.With this function I am trying to make username between 6 and 15 characters long.The username is unique but my custom validation is not working. And also default AUTH_PASSWORD_VALIDATORS is also not working.It is returning message if only the two password fields doesn't match with this function def validate(self, data) but the numeric,common password validator is not working. How can I validate username and password in a right way ? class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) class Meta: model = get_user_model() fields = ['first_name','last_name','username','email','password1','password2','profile'] def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def validate_username(self, value): data = self.get_initial() username = data.get("username") if len(username) < 6 and len(username) >15: raise ValidationError('Username must be between 6 and 15 characters long') return value def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], ) -
How can I override many to many field's intermediary model's object name
When I delete a data which contain a many-to-many field on django-admin, the below alert message pops up. Summary Owners: 1 Owner-salesman relationships: 2 Objects Owner: Chief Telecom (Own. fe311e..) Owner-salesman relationship: Owner_related_salesman object (7) Owner-salesman relationship: Owner_related_salesman object (8) I want to override the string "Owner_related_salesman object (7)" which I guess is in the intermediary model's definition. What should I do? Here's my code. class Owner(models.Model): # PK field id = models.AutoField( verbose_name='Serial Number', primary_key=True, ) # name fields name = models.CharField( verbose_name='Name', max_length=100, blank=True, # many to many fields related_salesman = models.ManyToManyField( verbose_name='Related Salesman', to='Salesman', blank=True, ) class Salesman(models.Model): # PK field id = models.AutoField( verbose_name='Serial Number', primary_key=True, ) # name fields name = models.CharField( verbose_name='Name', max_length=100, blank=True, # many to many fields related_owner = models.ManyToManyField( verbose_name='Related Owner', to='Owner', blank=True, through=Owner.related_salesman.through, ) By the way, I don't want to create a custom intermediary model because when I use it, I can't use the default many-to-many field widget (pic: https://i.stack.imgur.com/aqbhn.png) on django-admin, instead I could only use the inline which I think is bad to use. -
i want an upvote button that when clicked increment the value of a field(integer) in database
my html for button is <td> <a href="{% url 'minor:upvote' %}"> <button type="button" class="likes" style="text-align:center;border-radius:40px;width: 100px;height: 40px">upvote</button> </a> </td> url is.. path('',view=views.upv,name='upvote'), view is def upv(request,id): reporter = Logg.objects.get(id=id) reporter.upvote = reporter.upvote+1 reporter.save() return redirect('/') but the upvote field i.e an integer field with default value 0 is not getting incremented. -
Django timezone not working: doesn't change from UTC
I've checked now the time in ET/New York time and it's 04:39 AM using google search problem is I've set the timezone for new york on the backend and it's not set to this. In [1]: from django.conf import settings In [3]: import datetime In [4]: datetime.datetime.now() Out[4]: datetime.datetime(2019, 11, 21, 4, 38, 4, 124263) In [5]: from django.utils import timezone In [6]: timezone.now() Out[6]: datetime.datetime(2019, 11, 21, 9, 38, 25, 662909, tzinfo=<UTC>) In [7]: settings.TIME_ZONE Out[7]: 'America/New_York' In [8]: settings.USE_TZ Out[8]: True here you can see using django's timezone it's still using UTC timezone. Even though I've set it to NewYork on the backend. -
Django - from _sqlite3 import * - DLL load failed: Modul not found
I get this error when I try to run the local server on a windows machine. Im using the Anaconda 3 Python Distribution (64-bit). Dont know what happened, it worked before. Traceback: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\Myusername\appdata\local\continuum\anaconda3\Lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\Myusername\appdata\local\continuum\anaconda3\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\accounts\models.py", line 10, in <module> class UserProfile(models.Model): File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\db\models\base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) … -
Using Context to pass a variable to a template
Having issues getting a variable to pass to the template, example below: def confirm(request, reference): c = {'return_reference': reference} msg_plain = render_to_string('mail.txt', c) msg_html = render_to_string('mail.html') send_mail( 'Return - Ready for Collection', msg_plain, 'some@sender.com', ['some@receiver.com'], html_message=msg_html, ) And my HTML template: <p>Return reference <strong>{{ return_reference }}</strong>.... Anyway, the result of this is always a blank / null in the return reference... Any assistance would be appreciated.