Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reducing the number of queries in a Django app using a raw query
Objects of MyClass have associated history table that is populated by the database triggers, so not under control of the application. Current code has a method to query the history: class MyClass: @classmethod def history_query(cls, id): query = f'select * from history_table' if id: query = f"{query} where id='{id}'" def history(self): return MyClass.objects.raw(self.history_query(self.id)) The problem is when I list all the objects, the history table gets queried once for every object, creating thousands of queries... I'm trying to speed up the sluggish application by changing this to one query. Here's my current attempt: class MyClass: _full_history = None @classmethod def history_query(cls, id=None): query = f'select * from history_table' if id: query = f"{query} where id='{id}'" def history(self): if self._full_history: return self._full_history[self.id] return MyClass.objects.raw(self.history_query(self.id)) @classmethod def history_by_id(cls): if cls._full_history is None: history_list = MyClass.objects.raw(cls.history_query()) history_dict = {} for item in history_list: id = item.id history_dict[id] = history_dict.get(id, []) history_dict[id].append(item) cls._full_history = history_dict return cls._full_history Is there a better or more efficient way to do this? Would it be possible to do it with prefetch? -
how to rendering post form in django rest framework and some errors
from django.shortcuts import render from django.shortcuts import get_object_or_404 from .serializers import missionSerializer from .models import Mission_list from rest_framework.renderers import JSONRenderer from rest_framework.renderers import TemplateHTMLRenderer from rest_framework import viewsets from django.http import HttpRequest from rest_framework.views import APIView # Create your views here. class mission_list(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'mission_list/mission_list.php' def get(self, request, pk): mission = get_object_or_404(Mission_list, pk=pk) serializer = missionSerializer(mission) return Response({'serializer': serializer, 'mission': mission}) def post(self, request, pk): mission = get_object_or_404(Mission_list, pk=pk) serializer = missionSerializer(mission, data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer, 'mission': mission}) serializer.save() return redirect('mission-list') views.py in this code I got "init() takes 1 positional argument but 2 were given" error. how can I solve this error or have any other way to post data in D.R.F with html template? -
Nginx 1.18.0 | The plain HTTP request was sent to HTTPS port
I run Ubuntu 20.04 with Nginx 1.18.0 I have installed my Django app and everything works fine in http. I bought ssl certificate from GoGetSSL and installed it but I have this freaking issue. I tried every thing but nothing works, this is my Nginx Configurations: server { listen 443 default_server ssl; server_name www.elamanecc.com.dz elamanecc.com.dz; ssl_certificate /etc/nginx/ssl/www_elamanecc_com_dz/ssl-bundle.crt; ssl_certificate_key /etc/nginx/ssl/www_elamanecc_com_dz/www_elamanecc_com_dz.key; # Logs access_log /home/elamancc/logs/nginx_site1/access.log; error_log /home/elamancc/logs/nginx_site1/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/elamancc/commerce/pre/pre-elamanecc; } location /media/ { root /home/elamancc/commerce/pre/pre-elamanecc; } location / { proxy_set_header Host $host; #include proxy_params; proxy_pass http://unix:/run/ccenamale.sock; } client_max_body_size 7M; } If I set ssl off; as some mentioned in other solutions, then it will redirect me to http and display this message (I don't want http, I only want https works) : Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. -
Django ForeignKey.limit_choices_to with ForeignKey to ManyToMany scenario
I have a complex relation scenario as shown below. I'd like limit_choices_to Questions that are related to JobChecklistAnswer.job_checklist.checklist on JobChecklistAnswer.question. How can I filter those Questions as Q object (or callable as the docs say)? class Checklist(models.Model): name = models.CharField(_("name"), max_length=150) description = models.CharField(_("description"), max_length=150) class Question(models.Model): checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE) question = models.CharField(_("question"), max_length=200) class Job(models.Model): ... ... class JobChecklist(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE) class JobChecklistAnswer(models.Model): job_checklist = models.ForeignKey(JobChecklist, on_delete=models.CASCADE) # FIXME: Add limit_choices_to query question question = models.OneToOneField(ChecklistItem, on_delete=models.CASCADE) answer = models.TextField(_("answer")) -
speech recognition in multiple form fields in django
Im using localhost server for my website. I have integrated speech recognition in my form fields. As I needed speech recognizer in every field of form therefore I used different view function for that and rendering back to same page. The speech is working perfectly but the problem is When I submit the form The speech recognition starts working however it should save that data into database. When I donot use speech recognizer it is saving data perfectly but not with speech recognizer as it again starts to run speech algo. I really do not know what should be done at this point. Form code <form action="" method="POST" > {% csrf_token %} <div class="txtb" style="color:#022739"> <input type="text" name="" value="{{p}}" readonly style=" font-size: 15px;color:#022739;" > <input type="hidden" name="patientname" value="{{pid}}" readonly style=" font-size: 15px;color:#022739;" required=""> </div> <div class="txtb" style="color:#022739"> <input type="text" name="" value="{{doc}}" readonly style=" font-size: 15px; color:#022739;"> <input type="hidden" name="docname" value="{{docid}}" readonly style=" font-size: 15px;color:#022739;" required=""> </div> <div class="txtb" style="display:none;color:#022739"> <input type="hidden" name="date" value="{{d}}" readonly style=" font-size: 15px;color:#022739;" required=""> </div> <div class="txtb" style="color:#022739"> <input type="text" name="cal" value="{{sp}}" placeholder="Enter total calories" style=" font-size: 15px;color:#022739;" required="" pattern="[0-9]+" > <a href="/speechCal" style="font-family: FontAwesome" > <i class="fa fa-microphone" aria-hidden="true" style="margin-left:160px;"></i> </a> </div> <div class="txtb" > … -
DateField shows None in template, but correct date in Django Admin
I have this field in my model cancel_date = models.DateField(null=True, blank=True), but it's acting weirdly. In my admin it shows correctly with the date added, but when returning it in the template as {{subscription.cancel_date}}, it displays None instead. Is there a reason why that would be? model class Subscription(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) start_date = models.DateField(auto_now_add=True) renewal_day = models.IntegerField() next_renewal_date = models.DateField(null=True, blank=True) cancel_date = models.DateField(null=True, blank=True) view def subscription_index(request): title = "Subscriptions" current_date = datetime.date.today() sub_list = Subscription.objects.all().filter(cancel_date=None).order_by('-renewal_day') paginator = Paginator(sub_list, 10) page = request.GET.get('page') try: subscriptions = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. subscriptions = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. subscriptions = paginator.page(paginator.num_pages) context = { 'title' : title, 'subscriptions' : subscriptions } return render(request, 'accounts/subscriptions_index.html', context) template {% for subscription in subscriptions %} {{subscription.cancel_date}} {% endfor %} -
Django Redirect returns 200, but page does not redirect
I have a django project where I am doing google oauth2. I click on a google signin button, I receive a post request from Googles api, and then I interpret that request and want to redirect the user to a page where they can create their own account. Right now everything appears to work up until the redirect is suppose to happen. The terminal where my django project is running shows that it was successful (the print statements I wrote to confirm it reaches the render function work, and I see a 200 response also), but I remain on the login page. I am wondering if the redirect and render are happening on another website session, or otherwise somewhere besides where the user is currently on the website? Here is the code for my google webhook: token = request.POST.get('idtoken') print(token) try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), settings.GOOGLE_CLIENT_ID) print(idinfo) print('got past token') google_user_id = idinfo['sub'] google_email = idinfo['email'] try: # authenticates user who already exists as a google signed in user. user_from_sub = User.objects.get(google_sub_id=google_user_id) user = user_from_sub.get_user_object() if user.type == Types.BUSINESS: backend = 'user_accounts.auth_backends.BusinessAuthBackend' login(request, user, backend=backend) # TODO: add auth backend cred elif user.type == Types.CONSUMER: backend = 'user_accounts.auth_backends.ConsumerAuthBackend' login(request, user, … -
Restarting django-q qcluster gracefully
How can we restart qcluster gracefully for server changes? E.g. We use gunicorn to run django server which lets you gracefully restart workers without down time. How can you restart qcluster workers without disturbing any ongoing worker processing? Thanks. -
Aggregating a windowed annotation in Django
Background Suppose we have a set of questions, and a set of students that answered these questions. The answers have been reviewed, and scores have been assigned, on some unknown range. Now, we need to normalize the scores with respect to the extreme values within each question. For example, if question 1 has a minimum score of 4 and a maximum score of 12, those scores would be normalized to 0 and 1 respectively. Scores in between are interpolated linearly (as described e.g. in Normalization to bring in the range of [0,1]). Then, for each student, we would like to know the mean of the normalized scores for all questions combined. Minimal example Here's a very naive minimal implementation, just to illustrate what we would like to achieve: class Question(models.Model): pass class Student(models.Model): def mean_normalized_score(self): normalized_scores = [] for score in self.score_set.all(): normalized_scores.append(score.normalized_value()) return mean(normalized_scores) if normalized_scores else None class Score(models.Model): student = models.ForeignKey(to=Student, on_delete=models.CASCADE) question = models.ForeignKey(to=Question, on_delete=models.CASCADE) value = models.FloatField() def normalized_value(self): limits = Score.objects.filter(question=self.question).aggregate( min=models.Min('value'), max=models.Max('value')) return (self.value - limits['min']) / (limits['max'] - limits['min']) This works well, but it is quite inefficient in terms of database queries, etc. Goal Instead of the implementation above, I would prefer … -
HTML <input> tag vs <button> tag giving different behaviors in django
I'm testing an update button on my HTML form and have noticed that when I create it using this method it works just as expected: <form method="POST"> <input type ="submit" class="btn" value="Edit Data" name="edit_btn"> however when I try this method it doesn't work <div class ='form-group'> <button type="submit" class="btn btn-default" name="edit_btn"> Edit Data </button> </div> This is the function I'm calling when the button is clicked: def updatedata(request): form = FormShipmentForm(request.GET or None) if (request.POST.get('edit_btn')): selection = Shipment.objects.get(id=1) selection.booked_by = 'Dingus McDongles' selection.save(update_fields=['booked_by']) return redirect('/show') else: print('Something went wrong when updating db') context = {'form':form} return HttpResponse(render(request,'enterdata/shipmentform.html',context)) -
django url запрос на домен с пробелом [closed]
У меня есть url: .../home/<int>/bla bla как мне перенаправить пользователя на этот url с помощью {% url 'home' int.? %} -
lookup field in ModelViewSet django rest framework
I have an users endpoint in drf. I want the lookup_field for retrieving user to be something like @username not username. How can I implement this? -
django. view. testing. to check correct calculated values in view
I have a view to recalculate values (g -> kg). Quite simple. I did it just for self-education. There is a django form to add data inside of view and simple formula to re-calculate. Now, i want to test such view to give it the value and compare "output" with correct figure somehow in tests.py. Is it possible to do somehow? there is a code of view itself: def weight_converter(request): if request.method == 'POST': form = Adder(request.POST) if form.is_valid(): try: value_in_g = int(form.cleaned_data['added_data']) result_kg = value_in_g/1000 return render(request, 'weight_converter.html', {'result': result_kg, 'initial_value': value_in_g,}) except ValueError as e: e.message = 'Enter the number, not the string' return render(request, 'weight_converter.html', {'message': e.message}) else: form = Adder() return render(request, 'weight_converter.html', {'form': form}) https://pastebin.com/tUkzsUvR trying to do something like: def test_weightconverter_view_calculation(self): response = self.client.get('/weight_converter/', {'value_in_g': '1234'}) self.assertEqual(response.context['result'], 1.234) Thanks in advance for any advice! ) -
How to create an index that optimizes queries that involves 2 tables and ManyToManyFieldfield?
I want to query the below data models for Snapshots that are on a specific Branch and have one or more tags associated with the snapshot. It involves data from 3 tables, ManytoMayField, and a Foreign field. How do I define indexes that optimize this query to be fast? class Branch(models.Model): ''' Branch model One per branch ''' class Meta(object): ''' Override the default plural ''' verbose_name_plural = 'Branches' unique_together = ('branch_name', 'twig_name', 'team') branch_name = StringField("Branch Name", max_length=60) twig_name = StringField("Twig Name", max_length=60, blank=True, default='') created_at = models.DateTimeField('Created At') def __unicode__(self): return '%s:%s:%s' % (self.branch_name, self.twig_name, self.team) class Snapshot(models.Model): ''' Snapshot model One per Snapshot ''' class Meta(object): ''' Override the default plural ''' verbose_name_plural = ' Snapshots' snapshot_name = StringField("Snapshot Name", max_length=60, unique=False) branch = models.ForeignKey(Branch, related_name='branch_snapshots', on_delete=models.PROTECT, blank=True, null=True) created_at = models.DateTimeField('Created At') active = models.BooleanField("Active", default=False) def __unicode__(self): return '%s : %s: %s' % (self.snapshot_name, self.volume, self.branch) class SnapshotTag(models.Model): ''' Snapshot Tag model One per Snapshot Tag ''' class Meta(object): ''' Override the default plural ''' verbose_name_plural = ' Snapshot Tags' name = StringField("Snapshot Tag Name", max_length=60, unique=True) snapshots = models.ManyToManyField(Snapshot, related_name='snapshot_tags') def __unicode__(self): return '%s' % (self.name) -
Error in Django when I use createsuperuser command
When I use the command createsuperuser in Django, I got an error and I can execute this command, this is my traceback. Also, my Visual Studio Code give me warnings in the imports with the app "miapp". Thank you, very much. Traceback PS C:\xampp1\htdocs\Proyecto Python\AprendiendoDjango> python manage.py createsuperuser Traceback (most recent call last): File "C:\xampp1\htdocs\Proyecto Python\AprendiendoDjango\manage.py", line 21, in <module> main() File "C:\xampp1\htdocs\Proyecto Python\AprendiendoDjango\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Victor\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return … -
Using get_children runs into problems with custom Page model and Wagtail
I have a model for pages I want to make with Wagtail, befitting a blog post, so there are some extra fields. This works fine as far as creating and viewing pages, but when trying to iterate through them it becomes an issue. For example, when doing something like: {% for post in self.get_children %}{{ post.date }}</a><br />{% endfor %} This will return the error AttributeError at / 'Page' object has no attribute 'date' Except the child being referred to (there is only one) absoultey has a date attribute, and when viewing the page the date attribute works just as it should. How do I inform Wagtail about custom page models? -
Not saving the record into mongodb DB in Django, Actually I am trying explore multiple different DB (Postgresql, Mongodb) in a single app
I am trying to use multiple different DB in a single app(todo). I am using Djongo package for dealing mongodb. Settings.py DATABASES = { 'default':{}, 'sql_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'USER': '******', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '5432', }, 'mongodb':{ 'ENGINE': 'djongo', 'NAME': 'mongo_db' } } todo/models.py class Task(models.Model): todo = models.CharField(max_length=200) status = models.BooleanField(default=False) def __str__(self): return self.todo todo/serializers.py class TodoSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' todo/views.py @api_view(['POST']) def todoCreate(request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() serializer.save(using='mongodb') return Response(serializer.data) it successfully saved the record into 'sql_db' but not save in the 'mongodb'. -
Updating two fields at once with choices in django admin
I have x and y in my model as DecimalField. Something like this: class MyModel(models.Model): x = models.DecimalField() y = models.DecimalField() I want user to select these x and y from a list of dictionaries I have. It has to be selected together. As an example: [ { "x": 1, "y": 2, }, { "x": 3, "y": 4, }, ] We have two dictionaries in the example list so user should see two choices in a dropdown. Choice one with x: 1 and y: 2 Choice two with x: 3 and y: 4 Do I need to customize some widget or field for that? If I need how can I do that? -
Translation with variable is not working in django templates
I am using django translation to swith language. It is working fine but when get variable from database and try to translate in template, it's not working but it's working in views. example: msg = ugettext_noop('New van booking has been made - %(pk)d') % {'pk': booked.pk} Notification.objects.create(note_category='4', message=msg, role='Admin', booking=booked, van=van) I have also tried msg = gettext('New van booking has been made - %(pk)d') % {'pk': booked.pk} Notification.objects.create(note_category='4', message=msg, role='Admin', booking=booked, van=van) and message is as New van booking has been made - 8. I have also done makemessages and compilemessage #: .\van\views.py:563 #, python-format msgid "New van booking has been made - %(pk)d" msgstr "" "Une nouvelle réservation de van a été faite. Numéro de réservation - %(pk)d" but when I loop this in template, that does not work. {% for note in admin_note %} <span class="d-block">{% trans note.message noop %}</span> {% endfor %} it only shows New van booking has been made - 8 in all languages. But it's working in view fine. print(gettext('New van booking has been made - %(pk)d') % {'pk': 8}) Does anyone know how can I get translation in template. NOrmal translation is working fine. -
Autocomplete with API not working in Django
I am trying to autocomplete cities in Django and it is not working. I think something is wrong with my form. HTML: <form method="post"> <input id="search_city" name="city" value="{{ request.GET.city }}" type="text" class="form-control input-lg" onkeyup="searchOpen()" placeholder="Los Angeles, CA"/> ..... A bunch more form entries ..... </form> Then we have the javascript, ajax to call the API to do the Autocomplete: function searchOpen() { var search = $("#search_city").val() var data = { search: search }; $.ajax({ url: '/api/get_city_state/', data: data, dataType: 'jsonp', jsonpCallback: 'searchResult' }); function searchResult(data) { $( "#search_city" ).autocomplete ({ source: data }); }; Here is my api function in views.py: def get_city_state(request): if request.is_ajax(): q = request.GET.get('city', '') results = search.find_city(q, best_match=False) data = request.REQUEST['callback'] + '(' + simplejson.dumps(result) + ');' else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) -
Create or update django redt framework
Hi all I have a drf database and device but device can only read and write I need do when device is doing a post request django checks if it doesnt exist then post it but if it exists update old data.Thanks -
Django dynamically create not equal q objects
I'm working on creating dynamic filters using nested AND / OR logic, and would like to include NOT as an option. This leverages Q objects to create the nested AND / OR logic. The class takes in a json object like so: filters = { 'and': { "url__is": "www.test.com", "name__is": "test" } } This gets compiled down to .filter(Q(url__is='www.test.com') and Q(name__is='test') This works via a recursive function that really just does this on each level of the json tree. return source_queryset.filter(reduce(and_, filter_list)) and_ is from the python operator library and has been working great. I'd like to add NOT as an option as well though, and can't seem to find an equivalent option to reduce a list of Q objects to. Does anyone know a way to use reduce in a way that creates the idea of not equal to a list of q objects? -
Cannot import name 'RadioChoiceInput' from 'django.forms.widgets' (Django 1.19 to 3.2 migration)
I have the following widgets.py file from a Django 1.19 version to upgrade to Djando 3.2 version. I am getting the error: from django.forms.widgets import RadioSelect, RadioChoiceInput ImportError: cannot import name 'RadioChoiceInput' from 'django.forms.widgets' (my_env/lib/python3.9/site-packages/django/forms/widgets.py) This is the code: from django.forms.widgets import RadioFieldRenderer, RadioChoiceInput class RadioChoiceInput2(RadioChoiceInput): def render(self, name=None, value=None, attrs=None, choices=()): # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') if self.id_for_label: label_for = format_html(' for="{}"', self.id_for_label) else: label_for = '' attrs = dict(self.attrs, **attrs) if attrs else self.attrs try: self.choice_label = locale.format("%.2f", float(self.choice_label), grouping=True) except ValueError: pass return format_html( '<label class="radio" {}>{} <i></i> {}</label>', label_for, self.tag(attrs), self.choice_label ) class RadioFieldRenderer2(RadioFieldRenderer): outer_html = '{content}' inner_html = '<section class="col col-2">{choice_value}{sub_widgets}' \ '<i></i></section>' last_inner_html = '<section class="col col-1 last">{choice_value}{sub_widgets}' \ '<i></i></section>' choice_input_class = RadioChoiceInput2 def render(self): id_ = self.attrs.get('id') output = [] cc = len(self.choices) for i, choice in enumerate(self.choices): choice_value, choice_label = choice if isinstance(choice_label, (tuple, list)): attrs_plus = self.attrs.copy() if id_: attrs_plus['id'] += '_{}'.format(i) sub_ul_renderer = self.__class__( name=self.name, value=self.value, attrs=attrs_plus, choices=choice_label, ) ih = self.inner_html if i == 2: ih = self.last_inner_html sub_ul_renderer.choice_input_class = self.choice_input_class output.append(format_html(ih, choice_value=choice_value, sub_widgets=sub_ul_renderer.render())) else: ih = self.inner_html if i == cc-1: ih = self.last_inner_html w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i) output.append(ih.format( choice_value=force_text(w), sub_widgets='') ) return format_html(self.outer_html, id_attr=format_html(' id="{}"', id_) … -
DateField shows None in template, but correct date in Django Admin
I have this field in my model cancel_date = models.DateField(null=True, blank=True), but it's acting weirdly. In my admin it shows correctly with the date added, but when returning it in the template as {{model.cancel_date}}, it displays None instead. Is there a reason why that would be? -
Getting data via a glue table in Django
I have a relationship as such: dictionary table dictionary_child_char table dictionary table (same as first table) Here are my models: class Dictionary(models.Model): traditional = models.CharField(max_length=50) simplified = models.CharField(max_length=50) pinyin_numbers = models.CharField(max_length=75) pinyin_marks = models.CharField(max_length=75) translation = models.TextField() level = models.IntegerField() frequency = models.IntegerField() idiom = models.BooleanField() child_char = models.ManyToManyField('Dictionary', through='DictionaryChildChar', null=True) disabled = models.BooleanField() simptradsame = models.BooleanField() class Meta: db_table = 'dictionary' indexes = [ models.Index(fields=['simplified', ]), models.Index(fields=['traditional', ]), ] class DictionaryChildChar(models.Model): class Meta: db_table = 'dictionary_child_char' from_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="from_dictionary") to_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="to_dictionary") word_order = models.IntegerField() Each dictionary item has a potential many to many relationship to another dictionary item (it's Chinese characters, so each word might be made up of several constituent characters) I am trying to see these relationships, and actually grab the dictionary entry for each: dictionary = Dictionary.objects.filter(Q(simplified=char) | Q(traditional=char)).prefetch_related('child_char__to_dictionary')[:1] item = dictionary[0] item.to_dictionary.all().values() However when I do this: print(item.to_dictionary.all().values()) I get this: <QuerySet [{'id': 92661, 'from_dictionary_id': 37607, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92662, 'from_dictionary_id': 37608, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92663, 'from_dictionary_id': 37634, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92664, 'from_dictionary_id': 37635, 'to_dictionary_id': 37589, 'word_order': 0}, {'id': 92665, 'from_dictionary_id': 58861, 'to_dictionary_id': 37589, 'word_order': 1}]> How, instead of the to_dictionary_id, do I actually …