Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using bootstrap-vue <b-form-tags> as custom Django admin widget
I'm attempting add one of these cool bootstrap-vue tag inputs to my Django admin page and I'm having a difficult time getting it to render properly. Unfortunately there's a lot of customization on my part that I feel may be interfering with the rendering on the templates but I feel as though I haven't done anything too out of the ordinary. Such as: admin.py # I added custom models form reference and added all the required files to my Meta class class IngredientAdmin(models.ModelAdmin): form = IngredientListForm model = IngredientList class Media: js = [ 'tagwidget/js/polyfill.min.js', 'tagwidget/js/vue.min.js', 'tagwidget/js/bootstrap-vue.min.js' ] css = {'all':( 'tagwidget/css/tabbed_admin.css', 'tagwidget/css/bootstrap.min.css', 'tagwidget/css/bootstrap-vue.min.css', ) } forms.py #I added a custom widget, form, and added my template too the render method. Pretty sure this is where I'm lost. class TagWidget(forms.Widget): template_name = 'admin/chemicals/includes/tag_widget.html' def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) class IngredientListForm(forms.ModelForm): class Meta: model = IngredientList widgets = { 'cas_number': TagWidget(), } fields = '__all__' And then my tag_widget.html template, which renders the field as blank <div id="tagwidget"> <template> <b-form-tags v-model="value" no-outer-focus class="mb-2"> </b-form-tags> </template> </div> <script> Vue.config.devtools = true var tagwidget = new Vue({ delimiters: ['[[', ']]'], el: '#tagwidget', … -
Django Raw Query Insert
I am trying to use raw SQL query to speed up my Django app performance, I need to insert about 30k rows of data to my Postgres DB, this typically takes hours, How can use raw sql query to do this, so far I tried FIleData.objects.raw('''INSERT INTO user_host, host_link, linked_file, plugin_id, risk, host, protocol, port, banner, name, svc_type, description, first_identified, last_seen, synopsis, plugin_output, solution VALUES user_host, host_link_obj, file_obj, int(pluginid), risk, host, protocol, int(port), banner, pluginname, svcname, description, first_identified, last_seen, synopsis, plugin_output, solution''') but this doesn't work. I also tried this sql = """INSERT INTO blue_db(user_host, host_link, linked_file, plugin_id, risk, host, protocol, port, banner, name, svc_type, description, first_identified, last_seen, synopsis, plugin_output, solution) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""" with connection.cursor() as c: c.execute(sql, [user_host, host_link_obj, file_obj, int(pluginid), risk, host, protocol, int(port), banner, pluginname, svcname, description, first_identified, last_seen, synopsis, plugin_output, solution]) It also doesnt insert any data -
Exposing MoneyFields in Django REST Framework?
I have some Django models that use djmoney.models.fields.MoneyField. This stores data like "US$1,000.00". I'm trying to expose this via an API with Django REST Framework directly in Django's admin with a custom view like: from rest_framework import generics from rest_framework import serializers class MyModelAdmin(admin.ModelAdmin): def changelist_view_api(self, request, extra_context=None): cl = self.get_changelist_instance(request) base_queryset = cl.get_queryset(request) fieldsets = self.get_fieldsets(request) class ModelSerializer(serializers.ModelSerializer): class Meta: model = self.model fields = all_fields class ModelAdminListAPI(generics.ListCreateAPIView): queryset = base_queryset serializer_class = ModelSerializer name = '%s List API' % self.model._meta.verbose_name.title() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) view_handler = ModelAdminListAPI.as_view(queryset=base_queryset, serializer_class=ModelSerializer) return view_handler(request, extra_context, format=_format) This works well, with the only exception that it chokes on these special MoneyField instances. With one of these in the field list, this view returns the exception: File "~/.env/lib/python3.7/site-packages/rest_framework/mixins.py", line 43, in list return self.get_paginated_response(serializer.data) File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 761, in data ret = super().data File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 260, in data self._data = self.to_representation(self.instance) File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 679, in to_representation self.child.to_representation(item) for item in iterable File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 679, in <listcomp> self.child.to_representation(item) for item in iterable File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 530, in to_representation ret[field.field_name] = field.to_representation(attribute) File "~/.env/lib/python3.7/site-packages/rest_framework/fields.py", line 1148, in to_representation value = decimal.Decimal(str(value).strip()) decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] Digging into DRF's internals, … -
problems Deploying my python app to heroku
I have recently been trying to deploy my application to Heroku. I was following the documentation and everything but I'm getting this error now. 2020-03-12T21:46:36.154267+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=semsar-flask.herokuapp.com request_id=8c7e6604-97a5-4f5c-ae62-6c2edb73a4bb fwd="217.164.64.29" dyno= connect= service= status=503 bytes= protocol=https This is my Procfile: web: gunicorn wsgi: app Wsgi.py: from wbp import app Did I make a mistake filling in those two files or what? Please do explain since I'm relatively new to this. -
How to show different content depending on UserGroup in Django?
I have created a password_change_done template. But I need to to show a Back to Dashboard button for Employees and a Back to Profile for Customers. How can I achieve this through UserGroup checking, with messing with the views.py? -
How to use rabbitMQ as a broker for celery within a Django unittest
I am writing an integration test where I am creating a rabbitMQ container using - docker run -d --hostname localhost -p 5672:5672 --name rabbit-tox -e RABBITMQ_DEFAULT_USER=guest -e RABBITMQ_DEFAULT_PASS=guest rabbitmq:3 To test if I can connect to rabbitMQ from within the test, I created this test and it can send the data - def test_rmq(self): connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672)) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") connection.close() Now I want to use rabbitMQ container as celery backend, this is the code I am using - from celery import Celery broker_url = 'amqp://guest:guest@localhost:5672//' app = Celery('test', broker=broker_url, backend='amqp') from celery.contrib.testing.worker import start_worker from swordfish_app import tasks # Testing the consumer logic class ServiceAccountCeleryTestCase(TransactionTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.celery_worker = start_worker(app) cls.celery_worker.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() cls.celery_worker.__exit__(None, None, None) def setUp(self): super().setUp() self.task = tasks.delete_all_service_accounts_when_user_inactive() fake_obj_meta_del = V1ObjectMeta(self_link="deleted_service_account_link") self.delete_namespaced_service_account_fake_data = V1Status(metadata=fake_obj_meta_del) self.results = self.task.get() @patch('kubernetes.client.CoreV1Api.delete_namespaced_service_account') @patch('app.k8s.serviceaccount.get_inactive_serviceaccounts') def test_delete_all_service_accounts_when_user_inactive(self, k8s_get_inactive_patch, k8s_del_sa_patch): k8s_get_inactive_patch.return_value = ["sf-user-1", "sf-user-2"] k8s_del_sa_patch.return_value = self.delete_namespaced_service_account_fake_data assert self.task.state == "SUCCESS" When I execute the test I find this error -- Creating test database for alias 'default'... System check identified no issues (0 silenced). ...... [x] Sent 'Hello World!' .E ====================================================================== ERROR: setUpClass (tests.test_service_accounts.ServiceAccountCeleryTestCase) ---------------------------------------------------------------------- Traceback (most … -
Customize foreign key dropdown in Django Admin Site
I'm having trouble finding the best way to override and add custom html to an edit/add model form in my Django admin site. Here are the two models involved here: Icon model used to store "Font Awesome" Icons: class Icon(models.Model): name = models.CharField(max_length=100, null=False) style = models.CharField(max_length=10, choices=STYLE_CHOICES, null=False) retired = models.BooleanField(default=False) def delete(self): self.retired = True self.save() objects = NotRetiredManager() objects_deleted = DeletedManager() def __str__(self): return self.name Workbook model that holds foreign key reference to the above Icon model: class Workbook(models.Model): client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) icon = models.ForeignKey(Icon, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=100) workbookLink = models.CharField(max_length=1000) retired = models.BooleanField(default=False) def delete(self): self.retired = True self.save() objects = NotRetiredManager() objects_deleted = DeletedManager() def __str__(self): return self.name Here are the overridden admin models for the above models: class BaseAdmin(AdminImageMixin, admin.ModelAdmin): def delete_queryset(self, request, queryset): for obj in queryset: obj.delete() @admin.register(Workbook) class WorkbookAdmin(BaseAdmin): list_display = ("name", "client") list_filter = (NameFilter, ClientNameFilter) ordering = ("name", ) @admin.register(Icon) class IconAdmin(BaseAdmin): fields = ("name", "style", "icon_display") list_display = ("icon_display", "name", "style" ) list_display_links = ("icon_display", "name") list_filter = (NameFilter, ) ordering = ("name", ) def icon_display(self, obj): return mark_safe(f'<i class="{obj.style}{obj.name}"></i>') readonly_fields = ["icon_display"] Here is a list display of some Icons I have … -
Django Joining multiple tables
I'm working with an e-commerce website. I need to add multiple variations for a single product. ie. A shirt can be of multiple color and size. My models goes Here : Class Product (models.Model): product_name= models.CharField(max_length=150) .. .. .. def __str__(self): return self.product_name class Color(models.Model): product = models.Forignkey(Product, on_ delete = models.CASCADE) color_name = models.CharField(max_length=150) .. .. .. def __str__(self): return f'{self.product.product_name} |{self.color_name}' class Size(models.Model): product = models.Forignkey(Product, on_ delete = models.CASCADE) size_letter = models.CharField(max_length=150) .. .. .. def __str__(self): return f'{self.product.product_name} | {self.size_letter} class Productimage(models.Model): product = models.ForeignKey(Product, on_delete = models. CASCADE) image_1 = models.ImageField(default ='product.jpg', upload_to ='product_images') .. .. .. def __str__(self): return f'{self.product.product_name} - images' And my view Class ProductDetailView(ListView): template_name = 'customer/product_detail.html' model = Product How can I access all products on single page?? With its images on the template . I need to access to all of the above table while querying only to the Product table. I tried with Product.objects.filter(productimage__product=1) But this returns a singl row.. i need all objects I thinks its a kind of joining these tables using product_id. But idk how to join these tables. Really need help.. I'm stuck ..!! Thanks in advance.. 😃 -
How I can handle processing exporting huge number of records to excel file using django?
My problem is dealing with huge numbers of records(with simple relationship with user model) in django/mysql queryset (query optimization already applied) I want to generate excel file with around million of records That take a lot of time , to solve that I used celery background job to preventing user waiting But still that take a lot of time and consume server cpu and ram What you recommend In this case -
Django InlineFormSetFactory Add Button not appearing if the set has max set initially
So everything works fine except for the case when I try updating an object that has max_num of objects. Add button is not appearing initially (which is good), but neither is when deleting a single set. I've tried adding a button with a same class through Javascript, but it wasn't working.. class PlaceUpdateInline(InlineFormSetFactory): model = modelClass form_class = formClass factory_kwargs = {'extra': 0, 'max_num': 5, 'can_order': False, 'can_delete': True} def get_factory_kwargs(self): if logic here: kwargs['extra'] = 1 return kwargs kwargs['extra'] = 0 return kwargs -
django-filter not working with django pagination
I have a Class-based ListView that is working well with pagination. I added django-filter to that page for filtering. The problem is pagination is working well but django-filter is not working. Any help would be much appreciated. views.py class PokemonListView(ListView): model = Pokemon paginate_by = 25 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = PokemonFilter(self.request.GET, queryset=self.get_queryset()) return context filters.py import django_filters from django_filters import CharFilter from .models import * class PokemonFilter(django_filters.FilterSet): name = CharFilter(field_name="name", lookup_expr="icontains", label="Pokemon") class Meta: model = Pokemon fields = ['name', 'types'] template {% extends "base.html" %} {% block content %} <br><br> <form method="GET"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <div class="row"> <div class="col-md-8 mx-auto"> {% include "pokedex/paginate.html" %} <br> <table class="table table-striped"> <tr> <th>Pokedex ID</th> <th>Name</th> <th>Type</th> <th>Action</th> </tr> {% for object in object_list %} <tr> <td>{{ object.pokedex_id }}</td> <td>{{ object.name }}</td> <td> {% for type in object.types.all %} {{ type.name|capfirst }}{% if type != object.types.last %},{% endif %} {% endfor %} </td> <td> <a class="btn btn-sm btn-info" href="{% url 'pokemon_detail' object.slug %}"> Details </a> <a class="btn btn-sm btn-warning" href="{% url 'pokemon_update' object.slug %}"> Update </a> <a class="btn btn-sm btn-danger" href="{% url 'pokemon_delete' object.slug %}"> Delete </a> </td> </tr> {% endfor %} </table> {% include "pokedex/paginate.html" … -
Django model overwrites a record on my database instead of adding a new one
I have the following model: class myModel(models.Model): item_id = models.AutoField(primary_key=True) amount = models.FloatField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, editable=False) created = models.DateTimeField('Created', auto_now=True) def save(self): # ALL the signature super(myModel, self).save() And from a view, i'm trying to save some data to my database: model = myModel() model.user = request.user model.amount = amount When i open my database, i only see one record. Every time i try to add a new record, that record is overwritten with a new one. Instead, there should be one record every time i add some data, of course. Can someone help me find what am i doing wrong, please? -
Django updating multiple models from one template
This question is about the architecture of an app I have and what my options are to achieve my particular goal. I am trying to find a better way of creating the flow to a Quiz app I have. The site is built with Django 2.2, Vanilla JS and JQuery 3.4.1, as well as Bootstrap 4. The current flow of the app looks like this: User begins at a 'questions' page where they can Add a multiple-choice question or Add a true/false question to the pool of questions. This is a huge pool of questions after having only 10 quizzes. Multiple-choice questions utilize formsets for the answers which are linked to them (this was not fun to do and I enjoy coding). After the questions are added to the pool the user clicks Create a Quiz where they are taken to the 'quiz-create' page which allows them to create a quiz, select the options they want, and select all the questions they want in the quiz. What I would like the flow to be like: User starts at quiz-create page where they can create a quiz, select the options they want, as well as select to Add a multiple-choice question … -
Django order_by two fields, with first field nulls last
I want to sort a queryset by two fields, let's say timestamp and name. I will have a number of records where the timestamp is null, but all records will have a name. I want all of the records that have a timestamp to come first, sorted by timestamp, followed by all the records with null timestamps, but with a secondary sort by name. Example sorted results: Timestamp Name --------- ---------- 10:00 John 10:00 Kevin 10:00 Xavier 11:00 Arnold 12:00 Steve (null) Abe (null) Ben (null) Catherine (null) Zeke I know that I can put nulls last when sorting by a single field, like this: Person.objects.order_by(F('timestamp').asc(nulls_last=True)) I'm just not sure how to get the secondary sort field (name) in there. -
Django is taking a long time to load
For some reason, Django just started taking a really long time to load. When running python manage.py runserverit takes about 30 seconds for the server to run. But everything looks normal. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 12, 2020 - 19:59:26 Django version 3.0.3, using settings 'navio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. And after, every page takes about 22 seconds to load. Any clue about what is happening? The only thing I did before this happened was creating and then deleting a file called templatetags.py. -
Improve performance of writing Django queryset to manytomany
I have a Django 1.11 app. There is a model Campaign where I can specify parameters to select Users. When I run Campaign, I create a CampaignRun instance with FK compaign_id and M2M users. Each time a Campaign is run, different users can be in a resulting queryset so I'd like to keep a record about it. I do it as shown below: run = CampaignRun.objects.create(campaign=self, ...) (...) filtered_users = User.objects.filter(email__in=used_emails) run.users.add(*filtered_users) # I also tried run.users.set(filtered_users) run.save() However, it turns out that if the campaign is run from django-admin and the resulting number of users exceeds approximately 150, the process takes more than 30 seconds, which results in Error 502: Bad Gateway. It seems to me that 150 is ridiculously low number to get a timeout so I believe there must be a plenty of room for optimizing the process. What can I do to improve this process? What are my options in Django? Would you suggest using completely different approach (e.g. nosql)? -
Django with machine leaing gives this error Found array with 0 feature(s) (shape=(1, 0)) while a minimum of 1 is required
views.py from django.shortcuts import render from .models import questions from .serializers import approvalSerializers from django.http import JsonResponse from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.decorators import api_view import os from avasyu import settings import pickle import requests import numpy as np from django.core.cache import cache # Create your views here. data = [] def landing_views(request): return render(request, "avasyuapp/landing.html") def ques_views(request): cache.clear() return render(request, "avasyuapp/ques.html") def store_db(request): if request.method == "POST": ans1 = request.POST["answer1"] ans2 = request.POST["answer2"] ans3 = request.POST["answer3"] ans4 = request.POST["answer4"] ans5 = request.POST["answer5"] ans6 = request.POST["answer6"] ans7 = request.POST["answer7"] ans8 = request.POST["answer8"] ans9 = request.POST["answer9"] data.append(ans1) data.append(ans2) data.append(ans3) data.append(ans4) data.append(ans5) data.append(ans6) o1 = questions( ques='Have you motivated yourself to become a good communicator?', ans=ans1) o1.save() o2 = questions( ques='Can you speak in front of group without any nervousness?', ans=ans2) o2.save() o3 = questions( ques='Can you justify you as a good communicator?', ans=ans3) o3.save() o4 = questions( ques='Are you really happy to make communication as your future passion?', ans=ans4) o4.save() o5 = questions( ques='Is your english vocabulary and comprehension strong?', ans=ans5) o5.save() o6 = questions(ques='Are you good at grammar?', ans=ans6) o6.save() o7 = questions( ques='Have you achieved anything till date as a good … -
'ManyToManyDescriptor' object has no attribute 'add'
ranges = list(ranges) report.date_from = form.instance.date_from report.date_to = form.instance.date_to report.assigned_range.add(ranges) I am getting the error AttributeError at /create_stock_turnover_report 'ManyToManyDescriptor' object has no attribute 'add' But I can't understand why my database model is this assigned_range = models.ManyToManyField(to=assigned_range, blank=True, null=True) -
Is it possible to let users update their profile through a one time link in Django
I have tried all the techniques I could come up with, I couldn't find a way out. My question is, is it possible to let users update their profiles using a one time link in Django? If yes, can someone point me to a doc or maybe explainer which I can use as a guide? -
How to integrate a python script and execute it on Django
what I want to happen is: under some_list_of_contacts = [] will be the numbers from my django model. i will create a html template for this script that when I click the button it will execute this send_sms.py. under SMS_MESSAGEit will be the latest data coming from django model with timestamp. for example (As of {'timestamp'} the level is {'level'}). I'm a beginner on Django and Python, please how can I do these? Thanks! send_sms.py import boto3 AWS_ACCESS_KEY_ID = "<>" AWS_SECRET_ACCESS_KEY = "<>" AWS_REGION_NAME = "eu-west-1" SENDER_ID = "Test" SMS_MESSAGE = "Test" client = boto3.client( "sns", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION_NAME ) topic = client.create_topic(Name="notifications") topic_arn = topic['TopicArn'] some_list_of_contacts = [ '(must be numbers from django model)', ] for number in some_list_of_contacts: client.subscribe( TopicArn=topic_arn, Protocol='sms', Endpoint=number ) response = client.publish( Message=SMS_MESSAGE, TopicArn=topic_arn, MessageAttributes={ 'string': { 'DataType': 'String', 'StringValue': 'String', }, 'AWS.SNS.SMS.SenderID': { 'DataType': 'String', 'StringValue': SENDER_ID } } ) print(response) print("MessageId:" + response["MessageId"]) print("HTTPStatusCode:" + str(response["ResponseMetadata"]["HTTPStatusCode"])) -
How to set a default or add a Foreign Key in ModelForm?
Context: using Django 3.0.4. I have two models UserProfil a arbitrary UserModel automatically created by registering UserList more or less a simple list of lists Every registered User can create a new UserList entry in my model by giving a UserList.name in a form. If i put UserList.name and UserList.profile in the form my template generates the inputs and i can enter every value. it works so far. But it´s obvious Users should not allowed to choose the UserList.profile relation in the template, because if so, they could create a new list entry related to other users. so i need to set the value to the current user. My approach to save this relation was what u see in SingleListForm.save of my forms.py Unfortunately nothing is saving when i am entering a value for UserList.name in my Template Input. It only shows my form_invalidmessage: "Error something went wrong". additionally i also tried to removed the profilerfield from fields:in mySingleListForm and tried to save. but then i get the message The above exception (NOT NULL constraint failed: profil_userlist.profiler_id) was the direct cause of the following exception: Question How to set a default or add a Foreign Key in ModelForm? models.py class … -
Django edit default user group and add profile pictures
In django I want to edit the default user group so that I can the following attributes to all users, a description, a position, and a profile picture. I'm fairly new to django so if this question can be improved please let me know. -
image field with forms
i have a comment model in my django. i'm just using the content to submitting with the form but now i want to submit the iamge also.But its not working i"ve trying it many ways but its not working. views.py: def post_detail(request, pk): posts = get_object_or_404(post, pk=pk) comments = Comment.objects.filter(post=posts, reply=None,).order_by('-timestamp') #post=posts is the above post details posts its mean post for the exact corresponding posts is_liked = False if posts.likes.filter(id=request.user.id).exists(): is_liked = True if request.method == 'POST': comment_form = CommentForm(request.POST or None, request.FILES or None) if comment_form.is_valid(): content = request.POST.get('content') image = request.FILES['image'] reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=posts, user=request.user, content=content, image=image, reply=comment_qs,) comment.save() notify.send(request.user, recipient=posts.author, actor=request.user, verb='comment in your post', target=posts, nf_type='comment_by_one_user') else: comment_form = CommentForm() context = {'posts':posts, 'comments':comments, 'comment_form':comment_form, 'is_liked': is_liked, 'total_likes': posts.total_likes(),} if request.is_ajax(): html = render_to_string('blog/comments.html', context, request=request) return JsonResponse({'form': html}) return render(request, 'blog/post_detail.html', context) and my froms.py: class CommentForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here', 'rows': '4', 'cols': '10'})) class Meta: model = Comment fields = ('content', 'image',) the image is not submitting. -
UpdateView does not show existing data when using filter
I am quite new with Django and I need help. My problem is quite similar what Mike had in his case: UpdateView not populating form with existing data, but I have not found solution yet. My goal is to view owner dropdown selection list only those users who are members of the organization. models.py # organizations.models.py ... from accounts.models import User from core.models import TimeStampModel ... class Organization(TimeStampModel, models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField( verbose_name=_('Name'), max_length=255, unique=True ) code = models.CharField( verbose_name=_('Code'), max_length=255, null=True, blank=True ) owner = models.ForeignKey( User, on_delete=models.PROTECT, verbose_name=_('Owner'), related_name='owner', help_text=_('Organization Owner and Contact Person'), ) slug = models.SlugField(verbose_name=_('Organization key'), unique=True) ... class Meta: verbose_name = _('Organization') verbose_name_plural = _('Organization') ordering = ['name', 'code'] def __str__(self): return f'{self.name}, {self.code}' # Create automatically slug value from organization name field. # In case similar is exist then add extra count digit end of slug. def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Organization.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() self.next_update = timezone.now() + relativedelta( months=self.update_interval) super(Organization, self).save(*args, **kwargs) def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('organization_main_page', kwargs=kwargs) … -
Wagtail route still returns 404
I encountered a bit weird problem and not really sure why it happens. This is my model: class PostIndexPage(RoutablePage): max_count = 1 parent_page_types = [] intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] @route(r'^posts/$') def main(self, request): from django.shortcuts import render return render(request, self.get_template(request), self.get_context(request)) I defined route in that model but it seems to have no effect. http://127.0.0.1:8000/post-index-page/ - the old url is still working the old way http://127.0.0.1:8000/posts/ - but this one doesn't (404, not found). Do you have any idea what I'm doing wrong?