Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GET http://localhost:8000/add/ Page not found
I've been working on this application using my localhost:8000 for a while now and everything had been working smoothly. However now that I have tried to add a new url: /add/. For some reason it doesn't recognise the URL. I believe maybe there's something wrong with how I've wrote my code but I haven't quite found it. Any help would be great! To provide context I started of in my urls.py file where I created a new path: path('add', views.ProjectCreateView.as_view(), name='add'), I then moved over to my views.py file and imported the CreateView as so: from django.views.generic import CreateView. From there I then created a class for the view: class ProjectCreateView(CreateView): model = Project template_name = 'budget/add-project.html' fields = ('name', 'budget') Following this I then created another file within my budget folder nested in my templates folder. The file name add-project.html. I don't think there's anything wrong with this file but just to guarantee this is how I linked my html file: {% extends 'budget/base.html' %} {% load static %} {% block content %} This is the exact message I get when I run http://localhost:8000/add/ "No Project matches the given query." -
Running celeryd-worker on elastic-beanstalk
I am trying to get celery set up on elastic-beanstalk to run periodic-tasks. I have gotten everything running except for the celeryd-worker on elastic-beanstalk. It deploys fine and it is registering tasks but when I set up a periodic task either in celery.py or through django-celery-beat it doesn't execute. I pulled the logs from EB and got /opt/python/log/supervisord.log ------------------------------------- 2019-09-20 16:32:50,831 INFO spawned: 'celeryd-worker' with pid 712 2019-09-20 16:32:53,929 INFO exited: celeryd-worker (exit status 1; not expected) 2019-09-20 16:32:54,930 INFO gave up: celeryd-worker entered FATAL state, too many start retries too quickly 2019-09-20 16:41:43,327 INFO stopped: celeryd-beat (exit status 0) 2019-09-20 16:41:44,333 INFO spawned: 'celeryd-beat' with pid 1664 2019-09-20 16:41:54,442 INFO success: celeryd-beat entered RUNNING state, process has stayed up for > than 10 seconds (startsecs) 2019-09-20 16:41:54,689 INFO spawned: 'celeryd-worker' with pid 1670 2019-09-20 16:41:57,844 INFO exited: celeryd-worker (exit status 1; not expected) 2019-09-20 16:41:58,847 INFO spawned: 'celeryd-worker' with pid 1676 2019-09-20 16:42:02,037 INFO exited: celeryd-worker (exit status 1; not expected) 2019-09-20 16:42:04,045 INFO spawned: 'celeryd-worker' with pid 1711 2019-09-20 16:42:05,271 INFO stopped: httpd (exit status 0) 2019-09-20 16:42:05,275 INFO spawned: 'httpd' with pid 1717 2019-09-20 16:42:07,241 INFO success: httpd entered RUNNING state, process has stayed up for > … -
How to load master data (stored in DB) in client pages effectively?
I have a web application (built in Angular1.X and Django) that displays 6 product information (master data) stored in database. This information does not change by any transaction or action in my application, but will be referred in processing user actions. In order to increase the speed of my application page load, I’m trying to find an effective method to quickly access these information in different pages. I know the following are a few of the options to access this information every time. 1) Store the product details in local or session storage at client side for every page load and refer those values from that storage memory 2) Make a call to server to get these information as and when required at client side Is there any other option to store these master data at client side file or other means once at the time of production server start up and use that information for every time page loading? -
Django View: Return Queryset in JSON Format
i am trying to make the following view with return JsonResponse() at the end work correctly: def get_data(request): full_data = Fund.objects.all() data = { "test2": full_data.values('investment_strategy').annotate(sum=Sum('commitment')), } return JsonResponse(data) However, I get an error message saying "Object of type QuerySet is not JSON serializable". When I put the above Queryset in a view with return render() at the end: def get_more_data(request): full_data = Fund.objects.all() data = {"test2": full_data.values('investment_strategy').annotate(sum=Sum('commitment'))} return render (request, 'test.html', data) I get the the following result: <QuerySet [{'investment_strategy': 'Buyout', 'sum': 29}, {'investment_strategy': 'Growth', 'sum': 13}, {'investment_strategy': 'Miscellaneous', 'sum': 14}, {'investment_strategy': 'Venture Capital', 'sum': 23}, {'investment_strategy': 'n/a', 'sum': 36}]> So the queryset works fine, I just have no clue how to return the data in proper Json format (which I would need to use the data charts.js) I looked through answers for similar questions such as: TypeError: object is not JSON serializable in DJango 1.8 Python 3.4 Output Django queryset as JSON etc. but could not find a meaningful solution for my problem. Any help would be much appreciated! -
How to fix 'min() arg is an empty sequence' python+couchdb error
I have to do mosaic application in Python using Django and Couchdb, which are kind of new to me, for my studies. In part where I'm trying to do the mosaic, I got ValueError at 'min' function. However I run out of ideas why it is not working. I read the couchdb docs, reach some friends who already know a little python. rgb_of_tile = list(tile.getdata()) rgb_of_tile_list = utils.get_average_rgb_as_list(rgb_of_tile) returned_tiles = get_tiles(rgb_of_tile_list) closest = min(returned_tiles, key=lambda c: ( (rgb_of_tile_list[0] - c['key'][0]) ** 2 +(rgb_of_tile_list[1] - c['key'][1]) ** 2 + ( rgb_of_tile_list[2] - c['key'][2]) ** 2)) Error occurs on variable 'closest', but when I looked at the error I saw that 'returned_tiles'=[ ]. Below is code for that variable. I don't really know why it is not working, as the CouchDB reference-'tiles_url' should work properly def get_tiles(rgb_of_tile_list): rgb_of_tile_start = [x.__sub__(10) for x in rgb_of_tile_list] rgb_of_tile_finish = [x.__add__(10) for x in rgb_of_tile_list] tiles_url = "http://images_db_user:pass@localhost:5984/images/_design/view/_view/new-view?start_key=" + str( rgb_of_tile_start) + "&end_key=" + str(rgb_of_tile_finish) + "&include_docs=true" response = requests.get(tiles_url).json() returned_tiles = response['rows'] return returned_tiles -
Django/DRF - REST API endpoint with query parameter that goes queries multiple endpoints
Hey guys I'm having some trouble trying to architect how this endpoint would work. Currently I would like this endpoint "/nba/players?date=01012016" to work by going two different endpoints for results. Currently my GameDates endpoint returns something similar to {id: 1, home_team_id: 1, away_team_id: 2, date: "1/1/2016"}, {id: 4, home_team_id: 2, away_team_id: 3, date: "1/2/2016"} I want to grab that GameDate_id or it's primary key (in this case id:1) which then gets passed on to a another PlayerStatistic endpoint which will return something like this - {id: 1, game_id: 1, player_id: 1, team_id: 1, points: 20, assists: 10, rebounds: 2}, {id: 2, game_id: 1, player_id: 2, team_id: 1, points: 15, assists: 2, rebounds: 2}, {id: 3, game_id: 1, player_id: 3, team_id: 2, points: 10, assists: 2, rebounds: 20}, {id: 4, game_id: 1, player_id: 4, team_id: 2, points: 5, assists: 1, rebounds: 2} My initial endpoint with the date query would return these four JSON since a player had a game on that date (game_id = 1) from the GameDate endpoint, then that game_id gets used to query the PlayerStatistic endpoint and returns. I know the right method of say overriding the get_queryset function something like - def get_queryset(self): date = self.request.query_params.get('date') … -
Django check if server is already running
I am on Windows, and run my Django server via manage.py runserver 8001. When I have already running server and enter the mentioned command again, it starts another server listening the same (8001) port. What I would like to do is to determine if server is already running and stop the execution of the command, or stop the running server and then run the new server. -
Django cannot get Django user model to work with send_mail
This line in the view breaks: email = User.objects.filter(user=request.user).values_list('email', flat=True) send_mail('subject', 'message','info@site.com', [email[0]]) Here is the error: During handling of the above exception (Cannot resolve keyword 'user' into field. Choices are: email, first_name, last_name, username), another exception occurred: This used to work, but has now broken and have no idea why. The user has been created. This is the base Django model. -
Django and DocxTemplate with MailMerge
How do you pass a document stored in a FileField to DocxTemplate of the mailmerge package when it is hosted externally such as S3 etc. The DocxTemplate takes a path which then passes it to Document object of the python-docx package.... I need to to edit a file stored as a template on S3 with mailmerge to insert content into the merge fields. -
AH01630: client denied by server configuration - Django - Linux
My website is working but it is unable to access the static folder in my project folder. Here is a the configuration for static in my .conf file: Alias static /home/ubuntu/tasktracker/static <Directory /home/ubuntu/tasktracter/static> AllowOverride none Require all granted </Directory> My other sites are up and running using same configuration. But this one is causing the error. Any ideas? -
Django model save operation is truncating decimal field
Django model save operation is truncating decimal field. Sqlite table schema sqlite> .schema core_stock CREATE TABLE "core_stock" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(255) NOT NULL, "code" varchar(20) NOT NULL, "price" decimal NOT NULL, "diff" decimal NOT NULL, "open_price" decimal NOT NULL, "previous_close" decimal NOT NULL, "low52" decimal NOT NULL, "high52" decimal NOT NULL, "last_updated" datetime NOT NULL); CREATE INDEX "core_stock_code_8719e588" ON "core_stock" ("code"); Model class Stock(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=20, db_index=True) price = models.DecimalField(max_digits=19, decimal_places=2) diff = models.DecimalField(max_digits=19, decimal_places=5) open_price = models.DecimalField(max_digits=19, decimal_places=2) previous_close = models.DecimalField(max_digits=19, decimal_places=2) low52 = models.DecimalField(max_digits=19, decimal_places=2) high52 = models.DecimalField(max_digits=19, decimal_places=2) last_updated = models.DateTimeField() objects = DataFrameManager() def save(self, *args, **kwargs): ''' On save, update timestamps ''' self.last_updated = timezone.now() return super(Stock, self).save(*args, **kwargs) def __str__(self): return str(self.code) When I save stock with stock.diff = 2.45478 it saves it as 2.45. How can I store all 5 digits after decimal correctly in DB? -
django 2.2.5 import url from one app to another app
I would like to use the url from products app (products/urls.py) inside of search app url (search/urls.py) to search for items/products using search bar. I've attempted this example on django docs but it's importing a view to url in the same app, and I've also attempted this example but it looks to be a solution for an older version of django but i am using the latest version of django at time time 2.2.5. The error message I am receiving in terminal is coming from search/urls.py: path('', views.ProductListView.as_view(), name='list'), AttributeError: module 'search.views' has no attribute 'ProductListView' I understand search.views does not have an attribute "ProductListView" but, products.views does, which is why i'm trying to import products.views in search/urls.py. products/urls.py from django.urls import path, re_path from .import views app_name = "products" urlpatterns = [ path('', views.ProductListView.as_view(), name='list'), re_path(r'^products/(?P<slug>[\w-]+)/$', views.ProductDetailSlugView.as_view(), name='detail'), ] search/urls.py from django.urls import path from .import views from products.views import ProductListView urlpatterns = [ path('', views.ProductListView.as_view(), name='list'), ] ecommerce/urls.py (main app) from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include, re_path # from products.views import ProductDetailView from .views import home, about, contact urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('about/', … -
How to return an image object in django http response?
I am sending emails containing images. I am using html templates for these emails. I want the images to be generated on the fly. Hence, the 'src' in the image tag is a url that makes a REST api call to my app. The images are dynamically created, a publicly accessible URL is created. I want this image to be displayed in the email. But I am not able to figure out how to return this image. -
How to turn off superfluous headers in Django?
I have a Django application running with a WSGI server. Things are working fine, but my responses are coming back with lots of headers like - { 'Date': 'Fri, 20 Sep 2019 15:11:34 GMT', 'Server': 'WSGIServer/0.2 CPython/3.7.3', 'Content-Type': 'application/json', 'TERM_PROGRAM': 'iTerm.app', 'PYENV_ROOT': '/Users/siddharth.saha/.pyenv', 'TERM': 'xterm-256color', 'SHELL': '/bin/zsh', 'TMPDIR': '/var/folders/r1/v5jp8l016j9b3nb97tk224qs07cp6s/T/', 'Apple_PubSub_Socket_Render': '/private/tmp/com.apple.launchd.jAa5tsZccM/Render', 'TERM_PROGRAM_VERSION': '3.3.0', 'TERM_SESSION_ID': 'w0t2p0:EB83BE59-190F-4819-BE37-618016E6C685', 'PYENV_VERSION': 'hodor_env', 'ZSH': '/Users/siddharth.saha/.oh-my-zsh', 'USER': 'siddharth.saha', 'COMMAND_MODE': 'unix2003', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.FB43X5s2aG/Listeners', 'PYENV_DIR': '/Users/siddharth.saha/src/hodor/hodor_app', '__CF_USER_TEXT_ENCODING': '0x407658D9:0x0:0x0', 'VIRTUAL_ENV': '/Users/siddharth.saha/.pyenv/versions/3.7.3/envs/hodor_env', 'PAGER': 'less', 'PYENV_VIRTUAL_ENV': '/Users/siddharth.saha/.pyenv/versions/3.7.3/envs/hodor_env', 'LSCOLORS': 'Gxfxcxdxbxegedabagacad', 'PATH': '/Users/siddharth.saha/.pyenv/versions/hodor_env/bin:/usr/local/Cellar/pyenv/1.2.13/libexec:/Users/siddharth.saha/.pyenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Users/siddharth.saha/src/go_parsers/vendor/bin', 'PWD': '/Users/siddharth.saha/src/hodor/hodor_app', 'ITERM_PROFILE': 'Default', 'PYENV_HOOK_PATH': '/Users/siddharth.saha/.pyenv/pyenv.d:/usr/local/Cellar/pyenv/1.2.13/pyenv.d:/usr/local/etc/pyenv.d:/etc/pyenv.d:/usr/lib/pyenv/hooks', '_OLD_VIRTUAL_PS1': '${ret_status} %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)', 'XPC_FLAGS': '0x0', 'XPC_SERVICE_NAME': '0', 'PYENV_SHELL': 'zsh', 'SHLVL': '1', 'HOME': '/Users/siddharth.saha', 'COLORFGBG': '7;0', 'GOROOT': '/usr/local/go', 'LC_TERMINAL_VERSION': '3.3.0', 'ITERM_SESSION_ID': 'w0t2p0:EB83BE59-190F-4819-BE37-618016E6C685', 'HODOR_BUILD_ENV': 'dev', 'LESS': '-R', 'LOGNAME': 'siddharth.saha', 'LC_CTYPE': 'UTF-8', 'GOPATH': '/Users/siddharth.saha/src/go_parsers/vendor:/Users/siddharth.saha', 'LC_TERMINAL': 'iTerm2', 'PYENV_ACTIVATE_SHELL': '1', 'SECURITYSESSIONID': '186a9', 'COLORTERM': 'truecolor', 'DJANGO_SETTINGS_MODULE': 'api.settings', 'TZ': 'UTC', 'RUN_MAIN': 'true', 'SERVER_NAME': '1.0.0.127.in-addr.arpa', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '8000', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/ping', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'CONTENT_TYPE': 'application/json', 'HTTP_HOST': 'localhost:8000', 'HTTP_USER_AGENT': 'python-requests/2.18.1', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT': '*/*', 'HTTP_CONNECTION': 'keep-alive', 'wsgi.input': '<_io.BufferedReader name=4>', 'wsgi.errors': "<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>", 'wsgi.version': '(1, 0)', 'wsgi.run_once': 'False', 'wsgi.url_scheme': 'http', 'wsgi.multithread': 'True', 'wsgi.multiprocess': 'False', 'wsgi.file_wrapper': "<class 'wsgiref.util.FileWrapper'>", 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '36' } As you can see lots … -
Django read frame returning decimal fields value after rounding or truncating
Django read frame is returning decimal fields value after rounding or truncating. How can this be prevented? My Django Model class Stock(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=20, db_index=True) price = models.DecimalField(max_digits=19, decimal_places=2) diff = models.DecimalField(max_digits=19, decimal_places=5) open_price = models.DecimalField(max_digits=19, decimal_places=2) previous_close = models.DecimalField(max_digits=19, decimal_places=2) low52 = models.DecimalField(max_digits=19, decimal_places=2) high52 = models.DecimalField(max_digits=19, decimal_places=2) last_updated = models.DateTimeField() objects = DataFrameManager() def save(self, *args, **kwargs): ''' On save, update timestamps ''' self.last_updated = timezone.now() return super(Stock, self).save(*args, **kwargs) def __str__(self): return str(self.code) enter image description here But when I read data using django readframe then I see In [41]: read_frame(Stock.objects.filter(code='ABB')) Out[41]: id name code price diff open_price previous_close low52 high52 last_updated 0 1 ABB India Ltd. ABB 1400.00 5.02 1328.60 1325.45 1190.00 1670.00 2019-09-20 14:51:28.666744+00:00 -
Django-crispy-forms: set css for individual field and inputs
Is there a way to specify the css for an individual field and input in django crispy forms? I am using bootstrap4 and would like to use a horizontal form for a few fields in my form. I know you can use a self.helper to set label.class and field.class but I presume that applies to all field. I only want to change the label and field class on a few of my fields. -
What is the command to search a content in all the model fields at once?
I am developing an app with Django. I have developed a search bar to filter the database contents. I want that, when the user clicks on the search button, the indicated content is searched in all the model fields. My model has 16 fields, so my filter command will be a very long line, like: selected_entries = glossary_entry.objects.filter(Q(field1__icontains=query) | Q(field2__icontains=query)) | ...ETC ETC... | Q(field16__icontains=query)) Here you can see this line in my view function, in views.py: def glossario(request): query = request.GET.get('q') template = "glossario.html" # query applied if query: query = request.GET.get('q') selected_entries = glossary_entry.objects.filter(Q(field1__icontains=query) | Q(field2__icontains=query)) | ...ETC ETC... | Q(field16__icontains=query)) return render(request, template, {'all_entries':selected_entries}) # no query else: all_entries = glossary_entry.objects.all return render(request, template, {'all_entries':all_entries}) Is there a shorter command to do the same? Like: selected_entries = glossary_entry.objects.filter(Q(ALL_MODEL_FIELDS_ICONTAINS(model=MyModel)=query)) Note: ALL_MODEL_FIELDS_ICONTAINS is my invention -
How to display and save mutiple instances of a django form based on variable amount?
I've been looking around the site and can't seem to find an answer. Same for the django docs. The issue is I can't seem to save multiple instances of the same form. I'm trying to have a user set up a weekly calendar for a sports club. They land on a page with check boxes of each day they have activities. So if they click monday, tuesday, wednesday. Three instances of the DAY model are created created. Which works fine. Then, on the next page. Based on the amount of Days they have chosen, I would like a PeriodsForm (for this example let's just say they have one period each day). Then they can set what time each day starts and finises. I just can't seem to save the data. I was hoping someone has come across this before. Many thanks. I've tried using the modelformset_factory() but it's far too rigid. I also tried prefixes but I can't seem to loop through the forms on the POST. ### views.py def create_timetable_days(request): club = request.user.club form = TimetableCreateForm(request.POST or None) if len(list(Day.objects.filter(club=club))) > 0: return redirect('/timetables/create_timetable_times') if form.is_valid(): for item in form['Days']: if item.data['selected']: day = Day(name=item.data['label'], club=club) day.save() return redirect('/timetables/create_timetable_times') … -
Send mail in Django from Yandex
I want to send mail with Yandex. I got data from my serializer class and send with EmailMessage. When ı tried to send data ı got an error on DigitaOcean cloud server. Settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.xxxx.com.tr' EMAIL_PORT = 587 EMAIL_HOST_USER = 'info@xxxx.com.tr' EMAIL_HOST_PASSWORD = 'EN//7798' DEFAULT_FROM_EMAIL = 'info@xxxx.com.tr' EMAIL_USE_TLS = True Serializers.py: from django.core.mail import EmailMessage class InvoiceSerializer(ModelSerializer): # program = CharField(source='program.name', read_only=True) class Meta: model = Invoice fields = '__all__' def create(self, validated_data): # message = validated_data.pop('context') message_obj = super().create(validated_data) email = EmailMessage(message_obj.full_name, message_obj.email, to=['example@gmail.com']) email.send() return message_obj Where is my fault? -
How to allow tabulators when displaying string on website?
I pass the string named 'data' to a html page. With the following command i can generate linebreaks with '\n' in the string: {{ data | linebreaks}} The sting also contains tabs '\t' which are ignored and not displayed. So i look for some filter allowing tabs, something like: {{ data | linebreaks | tabulators}} But 'tabulators' is not a predefined filter. Does someone know what command i am looking for? -
Django Rest Framework - Group data by dynamic Key
I'm trying to format data when querying my API. I can retrieve my data like that : "results": [ { "Cat1": [ { "job": String, "position": Integer } ] }, { "Cat1": [ { "job": String, "position": Integer } ] }, { "Cat2": [ { "job": String, "position": Integer } ] } ] But I want something like that: "results": [ { "Cat1": [ { "job": String, "position": Integer }, { "job": String, "position": Integer } ] }, { "Cat2": [ { "job": String, "position": Integer } ] } ] I use a serializer like this: class CustomSerializer(serializers.ModelSerializer): cat = CatSerializer() job = JobSerializer() class Meta: model = MyModel fields = '__all__' def to_representation(self, value): return { value.cat.name: [{"job": value.job.name, "position": value.position, }] cat1 and cat2 are dynamics, they are from another table. I don't understand how to create my arrays properly using those serializers. The category is a @Property field in my model who's a foreign key of job. How should I deal with serializers to format my data properly ? -
TypeError: 'str' object is not callable -- on request to API
I am trying to run a minimal Django server but I get this error when I send a get request to the /api/v1/ endpoint. I realize similar questions have been asked before, and I believe this is occurring because of an invalid import reference, but I am unable to see where the mistake I made is. The filesystem (minus cache + migrations folders): . ├── api │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── blog_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── Pipfile ├── Pipfile.lock └── posts ├── admin.py ├── apps.py ├── __init__.py ├── models.py ├── tests.py └── views.py api/views.py from django.shortcuts import render # Create your views here. from rest_framework import generics from posts import models from .serializers import PostSerializer class PostList(generics.ListCreateAPIView): queryset = models.Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Post.objects.all() serializer_class = PostSerializer api/serializers.py from rest_framework import serializers from posts import models class PostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'author', 'title', 'body', 'created_at',) model = models.Post api/urls.py from django.urls import path from .views import PostList, PostDetail urlpatterns = [ … -
slack: challenge_failed using ngrok
I'm trying to test slack through ngrok. But the link does not pass in any way https://a333d0d4.ngrok.io/events/ class Events(APIView): def post(self, request, *args, **kwargs): slack_message = request.data if not 'token' in slack_message: parse_message.delay(slack_message) return Response(status=status.HTTP_200_OK) -
Change admin URLs in django
I want to change basic admin urls, for example I have the following URL: http://127.0.0.1:8000/admin/EmailSend/contact/1/change/ and I want to change URL to http://127.0.0.1:8000/admin/EmailSend/contact/{self.Name}/change/ -
Filter/order django rest api on a property=value but property is a value instead of a field
Consider an object that has multiple properties. class Object(models.Model): name= Charfield(max_length=80) class Property(models.Model): object= ForeignKey(Object, related_name='properties') name= Charfield(max_length=80) value= Charfield(max_length=80) I would like to provide an api accessible listview for the Object model, but I'm failing at ordering the ObjectList by property value as well as at sorting the the ObjectList by property value. To make the example more tangible you can imagine that Object has as type book, and an object of book has, among other properties, a property with name title and a value such as 20,000 Leagues Under the Sea. I would like to be able to be able to specify ?order_by=title and to be able to filter ?title__contains=League (or at least ?title="20,000 Leagues Under the Sea". I already did try to annotate Object with title="20,000 Leagues Under the Sea" and I'm able to show the title in the ObjectSerializer as if it was a field, but then ordering by this field does not work.