Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restrict access by group membership, roles, and ID in Django using class-based views
I'm a relative newbie, working on a Django directory-based app that serves many companies, and I want to know best practices/standards for restricting access by company-membership, user ID, and user role. The app is structured so that a company manager (CM) has superuser-like permissions for that company only, and then company team members (CTM) may or may not have restricted permissions to modify pages specific to that group/company only. The public user needs to be able to access the company's pages so companies are separated using their slug in the url. So company "A"'s home page is found by example.com/A/home. Using LoginRequiredMixin effectively restricts access to only logged-in users but logged-in users can be of the following types in this app: a public member, an app admin (like myself), a company manager, a company team member. I need to make sure of the following: 1) the logged-in user belongs to the company that is trying to be accessed (ie if I am a public user or belong to company "B" I cannot access company "A" restricted pages simply by being logged in and entering the slug in the url), 2) the logged in user has necessary permissions, even if the … -
How to correctly install django with pip in a virtualenv on windows?
Hi I am very new to python, I am trying to the django framework. However, I don't seem to be able to install django with pip on my venv. Whenever I enter pip install django on my venv file this happens. Unable to create process using 'c:\users\jason lo\appdata\local\programs\python\python39\python.exe "C:\Users\Jason Lo\desktop\learndjango\venv\Scripts\pip.exe" install django' Any help is greatly appreciated, thanks. -
Django TemplateDoesNotExist - moving working project from windows to linux
I am working to move a Django project from windows to linux. It works great in windows, but I am running into all sorts of errors trying to get it running on linux. The current issue I am facing is saying the template cannot be found. I have tried all the recommendations I can find online so I am looking for a little help. Furthermore, I am a little confused because one of the directories it says it is looking in which has the actual file, Django still does not see it. Here is part of the error in the picture showing which directory it looked at to find the file. The file is actually in this directory, so I am not sure what is going on. One thing I noticed is the back slash is incorrect, not sure where this directory is located in the code to fix this? django.template.loaders.filesystem.Loader: /home/pi/Desktop/MarketJungle/project_settings/templates/Website\base_template.html (Source does not exist) Settings.py Error -
Django BooleanField(default=False) Confusion
Can anyone help me out here? I am inserting data into my postgreSQL DB. admin_created is a booleanfield set to false by default. I've provided a true value for the first workout, but left the second workout blank for the booleanfield. Based on my understanding it should automatically be set to false, but i'm getting the error message below. Any ideas on why this is happening? #.sql INSERT INTO main_app_workout(name, description, admin_created) VALUES ('Yoga', 'Roll up your yoga mat and discover the combination of physical and mental exercises that have hooked yoga practitioners around the globe.', 'True'); INSERT INTO main_app_workout(name, description) VALUES ('Boxing', 'Ready to get your sweat on? Learn the six basic punches to build the foundation of an experienced boxer.'); #models.py class Workout(Model): name = models.CharField(max_length=40) description = models.TextField() exercises = ManyToManyField(Exercise, blank=True) admin_created = models.BooleanField(default=False) #Error code psql:db/create_main_exercises.sql:49: ERROR: 23502: null value in column "admin_created" of relation "main_app_workout" violates not-null constraint -
error[2] no such file found when using django with pipeline
I am editing a site on Python 3.9 with Django 2.0.13, and am having some issues getting the site up. The most current one seems to be caused by pipeline. The traceback is (and I apologize for the length....) Traceback: File "/project/lib/python3.9/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/project/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 158. response = self.process_exception_by_middleware(e, request) File "/project/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 156. response = response.render() File "/project/lib/python3.9/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/project/lib/python3.9/site-packages/django/template/response.py" in rendered_content 83. content = template.render(context, self._request) File "project/lib/python3.9/site-packages/django_jinja/backend.py" in render 106. return mark_safe(self.template.render(context)) File "/project/lib/python3.9/site-packages/jinja2/asyncsupport.py" in render 76. return original_render(self, *args, **kwargs) File "/project/lib/python3.9/site-packages/jinja2/environment.py" in render 1008. return self.environment.handle_exception(exc_info, True) File "/project/lib/python3.9/site-packages/jinja2/environment.py" in handle_exception 780. reraise(exc_type, exc_value, tb) File "/project/lib/python3.9/site-packages/jinja2/_compat.py" in reraise 37. raise value.with_traceback(tb) File "/project/src/apps/users/templates/users/login.html" in <module> 1. {% extends 'users/_layout.html' %} File "/project/lib/python3.9/site-packages/jinja2/environment.py" in render 1005. return concat(self.root_render_func(self.new_context(vars))) File "/project/src/apps/users/templates/users/login.html" in root 14. {{ error }} File "/project/src/apps/users/templates/users/_layout.html" in root File "/project/src/templates/layout.html" in root 20. {# === STYLES === #} File "/project/src/templates/layout.html" in block_critical_css 72. {% endblock static_js %} File "/project/src/libs/pipeline/templatetags/pipeline_plus.py" in _inline_stylesheet 110. return node.render_compressed(package, name, 'css') File "/project/lib/python3.9/site-packages/pipeline/templatetags/pipeline.py" in render_compressed 66. return self.render_compressed_output(package, package_name, File "/project/lib/python3.9/site-packages/pipeline/templatetags/pipeline.py" in render_compressed_output 80. return method(package, package.output_filename) File "/project/src/libs/pipeline/templatetags/pipeline_plus.py" in render_css 49. str(staticfiles_storage.get_modified_time(path).timestamp()), File … -
Object of type BoundField is not JSON serializable
A have a chain of OneToMany relations (one) Construction -> Camera -> Frame -> Event models.py def name_image(instance, filename): return '/'.join(['images', str(instance.name), filename]) class Construction(models.Model): """ Объект строительства""" developer = models.ForeignKey( Developer, related_name="constructions", on_delete=models.CASCADE ) name = models.CharField(max_length=100) plan_image = models.ImageField(upload_to=name_image, blank=True, null=True) address = models.CharField(max_length=100) coordinates = models.PointField(blank=True) deadline = models.DateTimeField(default=timezone.now, ) workers_number = models.IntegerField(default=0) machines_number = models.IntegerField(default=0) def __str__(self): return self.name class Camera(models.Model): building = models.ForeignKey( # not important Construction, related_name="cameras", on_delete=models.CASCADE ) name = models.CharField(max_length=100) url = models.CharField(max_length=100) ... class Frame(models.Model): """ Фото с камеры """ camera_id = models.ForeignKey( Camera, related_name="frames", on_delete=models.CASCADE ) ... class Event(models.Model): frame_id = models.ForeignKey( Frame, related_name="events", on_delete=models.CASCADE ) ... I want to output data about Camera in EventSerializer (GET method). I am using get_construction method I want to use ConstructionSerializer for Construction object ( <class 'api_buildings.models.Construction'>) But I have an error Object of type BoundField is not JSON serializable How can I fix this error (I know, that I can use model_to_dict, but I want to use ConstructionSerializer) class EventSerializer(serializers.ModelSerializer): time = serializers.DateTimeField(format=TIME_FORMAT) camera = serializers.SerializerMethodField() construction = serializers.SerializerMethodField() frame = serializers.SerializerMethodField() developer = serializers.SerializerMethodField() class Meta: model = Event fields = ( 'id', 'frame_id', 'frame', 'developer', 'camera', 'construction', 'type_of_event', 'class_name', 'grn', … -
Question: What is the best js, back-end frameworks together for big projects with Multi User Authentication?
I Have A Big Project And Want To Know What is The Best js And Back-end Frameworks And This website Contains a lot of Features Such As Multi User Authentication And Much More ... -
TypeError: data.map is not a function, even though the data is an array (i think)
Im using Django rest to send data to react: [ { "id": 1, "username": "Dewalian", "question": [ { "id": 5, "title": "how to cook?" }, { "id": 6, "title": "how to exercise?" } ] }, { "id": 2, "username": "Edward", "question": [] }, { "id": 3, "username": "Jeremy", "question": [] } ] and then fetch it using a custom hook from a video tutorial: import useFetch from "./UseFetch"; import DataList from "./DataList"; const MainContent = () => { const {data: question, isPending, error} = useFetch("http://127.0.0.1:8000/api/user/"); return ( <div className="main-content"> {error && <div>{error}</div>} {isPending && <div>Loading...</div>} {question && <DataList data={question} />} </div> ); }; export default MainContent; finally i map it on another component: const DataList = (data) => { return ( <div> {data.map(user => ( <div key={user.id}> <p>{user.username}</p> </div> ))} </div> ); } export default DataList; but i get "TypeError: data.map is not a function". Im pretty sure the problem is on the json, but i dont know what's wrong. so, what's wrong and how to fix this? thanks. -
get values from input and excute function django
I have two inputs in my HTML page and I want to send them to a function in Django views.py. so I have a table as shown : And I want to take the Quantity and disc values from the inputs + another value from the from and the HTML code is: <table id="table_id" class="table-wrapper table-sm"> <thead class="thead-light"><tr> <th>Item Description</th> <th>Quantity</th> <th>Disc %</th> <th></th> </tr></thead> <tbody> <tr > {% for Field in AllItemes %} <td>{{Field.Item_Code}}</td> <td> <input class="form-control mr-1" placeholder="1" name="select_date" type="number" min="0" pattern="\d*"/></td> <td> <input class="form-control mr-1" placeholder="0" name="select_Disc" type="number" min="0" pattern="\d*"/></td> <td><a href="{% url 'Up_InvoiceTACH' Field.Item_Code select_date select_Disc %}" class="btn btn-info btn-sm">Add</a></td> </tr> {% endfor %} </tbody> </table> my views.py is: def Up_InvoiceTACH(request, id_itm, id_itm2 , id_itm3): pass and the URL is like this: path('up_InvoceTACH/<int:id_itm>/<int:id_itm2>/<int:id_itm3>/', views.Up_InvoiceTACH, name='up_InvoceTACH'), So how do I send those three parameters especially from the inputs? -
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?