Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST how to display extra data from other models in json response
I have a Task_worker model, which is a through table for 2 models - Worker and Task. Currently GET /task-worker returns the following json: { "count": 3, "next": null, "previous": null, "results": [ { "task": 21, "worker": 1, "created": "" }, { "task": 20, "worker": 1, "created": "" }, ... ] } There is no information about the worker and task, and hence I will need to do extra queries to get information I need to display what I need. For example, GET /tasks/21 returns: { "url": "http://127.0.0.1:8000/api/tasks/21/", "workers": [ { "task": 21, "worker": 1, "created": "2018-01-24T16:47:34.657800Z" } ], "user": "username", "created": "2018-01-24T16:31:33.597255Z", "title": "Help me with Django", } So I would like to return the following in my json from GET /task-worker/ { "count": 3, "next": null, "previous": null, "results": [..., { "id":2, "task": {"title": "Help me with Django"}, "worker": { 'Worker Info' }, "created": "" }, ... ] } CODE SETUP models.py class Task_worker(models.Model): worker = models.ForeignKey(Worker) task = models.ForeignKey(Task) created = models.DateTimeField(auto_now_add=True, blank=True) class Meta: unique_together = ('worker', 'task') serializers.py class TaskWorkerSerializer(serializers.ModelSerializer): task = serializers.ReadOnlyField(source='task.id') #TRIED #task = TaskSerializer(source = task_worker_task, read_only=True) worker = serializers.ReadOnlyField(source='worker.id') class Meta: model = Task_worker fields = ('id', 'task', 'worker', 'created', ) … -
Django Rest Framework API Authentication Test
I'm writing tests to check if the Authenticated users have access to the API Endpoints. On my test settings, I have set the defaults for Rest Framework Authentication and Permissions Classes. The default setting is that everyone has to be authenticated to access the API. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', )} This is the function which is failing (and all others). Here, I create a user object with a custom UserFactory which is setting a default email and password for each user created. Then I use the APIClient with basic authentication to log in. I'm following the official Django Rest Framework Documentation def test_retrieve(self): user = UserFactory.create() client = APIClient() client.login(email=user.email, password=user.password) entity = AttributeChoiceFactory.create() response = self.get(retrieve=entity.pk) self.assertEqual(response.status_code, status.HTTP_200_OK) item = json.loads(response.content) self.assertEqual(type(item), dict) self.assertEqual(item['pk'], entity.pk) self.assertItemsEqual(AttributeChoiceSerializer.Meta.fields, item.keys()) The test fails with Not Authorized Status Code AssertionError: 401 != 200 -
Forms save. Date time discover interval
I need to discover interval for begin_date and end_date fields of my model class Reserved(models.Model): begin_date = models.DateTimeField() end_date = models.DateTimeField() In short when user is saving some data to the database in forms should be validation. Validation should to check is there reservation in interval begin_date and end_date and give error. I tried to to this but it does not work :( def save(self, commit=True): date_validation = Reserved.objects.filter(room=self.room).exists() and \ Reserved.objects.filter( begin_date__gte=datetime.date.today(), end_date__lte=datetime.date.today() ) if date_validation: raise RuntimeError('You can not reserve this room. Interval') super(ReserveRoomForm, self).save(commit) For example the there are reservation in begin date 23-January and end date 29-January but user trying to reserve in 25-January How to realize it? Thanks) -
Easiest strat to add a Subscribe module to a Mezzanine blog
I have a Mezzanine blog and I would like to add a little form to every page so users can type their email addresses and click 'subscribe' so, from that moment, an email will be sent to announce any new post to the blog. I don't see that built in or any existing module for that purpose... Should I program that from scratch? Any ideas? -
check changes before saving into database
I am using Django 1.11 and DRF 3.6.2 and just started developing an API... I am trying to check what are the changes to be performed in the database with the data being sent. class IndividualViewSet(viewsets.ModelViewSet): """Individual ViewSet.""" serializer_class = serializers.IndividualSerializer queryset = models.Individual.objects.all() def update(self, request, equipment_serial, pk=None): queryset = models.Individual.objects.get(pk=pk) serializer = serializers.IndividualSerializer(queryset, data=request.data["entities"][0]) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_200_OK) return Response(status.HTTP_400_BAD_REQUEST) def perform_update(self, serializer): old_obj = self.get_object() new_data_dict = serializer.validated_data if old_obj.name != new_data_dict['name']: # logic for different data # ... serializer.save() However, with the code as above, the perform_update function is never being called by serializer.save() on the update function. My questions surrounds on why it is happen and how should I do in order to accomplish the desired behaviour. -
how serve django media file in shared hosting?
im using django 1.11.4 and i want to serve django media file in a shared host my web server is apache i already set MEDIA_ROOT and MEDIA_URL and evreything is fine when Debug = True i alread try HelioHost wiki and Django serving media files (user uploaded files ) in openshift but it dosnt work -
python-django-restframwork deserializer
I have a list like this form. [{'XPos': {'$': 128.604314661}, 'YPos': {'$': 35.8662354972}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 545}, 'estbDd': {'$': 19100907} }, {'XPos': {'$': 128.096026987}, 'YPos': {'$': 35.1753899647}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 326}, }, {'XPos': {'$': 127.050741243}, 'YPos': {'$': 37.5937747637}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 412}, 'estbDd': {'$': 19711005} }, {'XPos': {'$': 128.582521394}, 'YPos': {'$': 35.8701796577}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 427} }, {'XPos': {'$': 126.884639554}, 'YPos': {'$': 37.4911811753}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 498}, 'estbDd': {'$': 19830831} }, {'XPos': {'$': 126.824997324}, 'YPos': {'$': 37.3188581763}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 281}, 'estbDd': {'$': 19860101}, }] and using django-rest-framework deserializer, i want to insert that data into my database. BUT, i have some problems. I just only need 'XPos','YPos', 'estbDd' value. In converting xml to json, more nested structures have been created. (look '$') Some datas do not have 'estbDd' field values. How can i filter that datas and input to my database? http://www.django-rest-framework.org/api-guide/serializers/ i referenced that site. -
Django: customizing the Form does not deliver the instructions, input only numbers etc
I am in the forms.py file, and as you can see I am trying to customize the html that the template engine renders, but it is ignoring whatever I write. If I enter letters, it should show a dialog box on the fly as HTML5 by default does, indicating that only numbers. Also even if I write a number larger than 10, which is the limit, it sends it anyway. In other words, the customization on the forms.py page is not being effective like when you do it directly on the form. but I cannot write in the form because of the **** template that abstracts everything and you dont know what is going on behind doors. I include the form just for curiosity: class ReForm(forms.Form): count = forms.CharField(widget=forms.TextInput( attrs={'input type': 'number', 'pattern':'\d*', 'maxlength':'2', 'min': '1', 'max':'10','title':'Numbers only','placeholder':'Max value 10'})) FORM: <form method="GET" novalidate> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django DRF read json from POST?
When I try to send data from a jquery POST I can get them from both side, js client and python django-rest-framework sefializer create method from backend console.log says: { "wo_r": [ { "pk": "17635" }, { "pk": "17637" } ] } the form data show dict as: { "wo_r": [ { "pk": "17635" }, { "pk": "17637" } ] }: django shell read: <QueryDict: {'{\n "wo_r": [\n {\n "pk": "17635"\n },\n {\n "pk": "17637"\n }\n ]\n}': ['']}> Why the data sent get this ":" at the end? this is the javascript part: function creaol(indirizzo,val) { $.ajax({ url: indirizzo, type: 'POST', dataType:'json', global: false, data : val, // data : {'wo_r':[ // {"pk": "17629"}, {"pk": "17630"},{"pk": "17631"} // ]}, success: function(result) { // Do something with the result } }); } var dati = JSON.stringify(dict, null, 2); creaol(indirizzo, dati ); -
Language config for Django Rest Framework SearchFilter
I try to find out how to set LANGUAGE flag for Django REST Framework SearchFilter. So here is my code: class SearchViewSet(generics.ListAPIView): queryset = ServicePrice.objects.all() serializer_class = ServicePriceSerializer filter_backends = (filters.SearchFilter,) search_fields = ('@service__name',) I need to set (somewhere) that my language is Spanish, so the result should be something like this: SELECT to_tsvector('spanish', 'bla-bla-bla in spanish') @@ plainto_tsquery('spanish', 'bla'); Many thanks! P.S. I know about SearchVector('body_text', config='spanish') but the idea is that I use Django REST Framework SearchFilter and it will be great to use the native tools. -
Connect two foreign key linked tables to one queryset
I have three tables: class Variant(models.Model): variant = models.CharField(max_length=60, primary_key=True) gene = models.ForeignKey(Gene, on_delete=models.CASCADE, db_column='gene') var_type = models.CharField(max_length=60) consequence = models.CharField(max_length=60) cNomen = models.CharField(max_length=50) pNomen = models.CharField(max_length=50) class Meta: unique_together = (('variant', 'gene',)) def __str__(self): return str(self.variant) class VariantSampleRun(models.Model): sample = models.ForeignKey(Sample, on_delete=models.CASCADE, db_column='sample') gene = models.ForeignKey(Gene, on_delete=models.CASCADE, db_column='gene') variant = models.ForeignKey(Variant, on_delete=models.CASCADE, db_column='variant') hts_run = models.ForeignKey(HTSRun, on_delete=models.CASCADE, db_column='hts_run') vaf = models.DecimalField(max_digits=8, decimal_places=3) depth = models.IntegerField() added_manually = models.BooleanField(default=False) class Meta: unique_together = (('variant', 'gene', 'sample', 'hts_run'),) def __str__(self): return str(self.variant) + ' ' + str(self.sample) + ' ' + str(self.hts_run) class VariantAnnotation(models.Model): variant = models.ForeignKey(Variant, on_delete=models.CASCADE, db_column='variant') gene = models.ForeignKey(Gene, on_delete=models.CASCADE, db_column='gene') annotation_id = models.ForeignKey(Annotation, on_delete=models.CASCADE, db_column='annotation_id') cosmic_id = models.CharField(max_length=80) cosmic_haem = models.CharField(max_length=21) dbsnp = models.CharField(max_length=20) _1000g_AF = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) exac_AF = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) gnomad_AF = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) class Meta: unique_together = (('variant', 'gene', 'annotation_id'),) I want to query the VariantSampleRun table to obtain variant and VariantAnnotation information in one queryset. I can do this to get variant, but not VariantAnnotation information out using select_related(): self.var_obj = VariantSampleRun.objects.filter( sample=self.current_sample, hts_run=self.hts_run ).select_related('variant') This self.var_obj therefore allows me to obtain variant information - but i need the annotation as well. When I do: Variant.objects.all().prefetch_related('variantsamplerun', 'variantannotation') … -
python manage.py migrate (command not found)
Background: I'm taking a beginners Django course and I've run into an issue. The following command isn't working in Terminal. Running on Mac Virtual environment Taking UDEMY Course: try-django-v1-11-python-web-development Command: python manage.py migrate Terminal Output: (trydjango1-11) C02T74CKGTF1:src josh.frazier$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/josh.frazier/Dev/trydjango1-11/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/josh.frazier/Dev/trydjango1-11/lib/python3.6/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/Users/josh.frazier/Dev/trydjango1-11/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/josh.frazier/Dev/trydjango1-11/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/josh.frazier/Dev/trydjango1-11/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/josh.frazier/Dev/trydjango1-11/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/josh.frazier/Dev/trydjango1-11/src/muypicky/__init__.py", line 1, in <module> from .base import * ModuleNotFoundError: No module named 'muypicky.base' -
Why won't my django view use the template that I specified?
When I look a the "companies_by_x" view in my browser it renders with the "index.html" template and not the template I specified, which is "company_list.html" -- that template is specified for the "index" view. How can I get "companies_by_x" to use the "company_list.html" template? Each view has its own URL. Thank you. def companies_by_x(request): company_list = Company.objects.filter(locations__in=[1,2]).distinct() context = {'company_list':company_list} return render(request, 'companies/company_list.html', context) def index(request): company_list = Company.objects.order_by('-id')[:5] context = {'company_list':company_list} return render(request, 'companies/index.html', context) -
Django PDF with multipage template
I have a dynamic HTML file in Django. I want to be able to generate a PDF from it, with a footer and header (image). If the content exceeds 1 page, I need the footer and header to be on multiple pages as well. As far as I know, designing a page like this on CSS is impossible, hence needing a library like Reportlab. How would I achieve this? If I can do this in Reportlab or other libraries, it would be great if anyone could point me to a guide explaining the multipage PDF 'template' -
Django : Link Model field to another model field configuration name
Giving the following models in Django : class MyModel(models.Model): name = models.CharField('This is my name'),max_length=150) class AnotherModel(models.Model): my_model_field_name = [...] I'm tring to store in AnotherModel.my_model_field_name the name of MyModel.name field (so 'This is my name'). I would like it to be linked, so if tomorow I change the name of MyModel.name field by "This is my new name", I want that all my previous records of my AnotherModel.my_model_field_name automatically update. Model instances are able to link to other models instances, not models themselves, right ? Is it possible or just stupid ? -
How to implement Facebook signup to my web site?
I am implementing social signup on my website - Facebook and Google. I know I should use oauth here, but not sure how to implement it. I wanted to be clear how to implement social sign up - facebook and google. Is this something you can help me? Would you like to help me to provide me correct steps of social sign up? -
Django Page not found (404) Request Method: No Sales matches the given query
please help review below code for editing entry. It keeps returning below error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/geo_gas/edit_sale/ Raised by: geo_gas.views.edit_sale No Sales matches the given query. class Sales(models.Model): gas_qty = models.CharField(max_length=20) amount = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.gas_qty class Meta: verbose_name_plural = 'Sales' View.py def edit_sale(request): """Edit an existing sales record.""" entry = get_object_or_404(Sales, pk=1) if request.method != 'POST': form = SalesForm(instance=entry) else: form = SalesForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('geo_gas:sales')) context = {'entry': entry, 'form': form} return render(request, 'ht/edit_sale.html', context) Urls.py ....... # Page for editing a sale entry path('edit_sale/', views.edit_sale, name='edit_sale'), ....... ht/templates/ht/edit_sale.html Edit entry: <form action="{% url 'geo_gas:edit_entry' %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name="submit">save changes</button> </form> -
Updating existing Django app version
I was working through the tutorial for Django 2.0 when I had an earlier version of Django installed. I have now updated Django to 2.0.1 and Python to 3.6.4. I am part way through building my app and I am getting an error when I try to include paths like this: from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ # url(r'^$', views.index, name='index'), # ex: /polls/ path('', views.index, name='index'), # ex: /films/5/ path('<int:film_id>/', views.detail, name='detail'), # ex: /films/5/results/ path('<int:film_id>/results/', views.results, name='results'), # ex: /films/5/vote/ path('<int:film_id>/vote/', views.vote, name='vote'), ] The error I get is: ImportError: cannot import name path Paths are not supported in pre Django 2.0, but this error still occurs after updating. Is there a setting within my app files that I need to change? I don't want to have to start from scratch if I can avoid it. -
Django rest framework DateField format
I have drf model which is containe DateField. That field default format is "YYYY-MM-DD" just i want to convert "DD-MM-YYYY" how can is possible. models.py class Reminder(BaseModel): content = models.TextField() schedule_date = models.DateField() schedule_time = models.TimeField() is_release = models.BooleanField(default=True) serializer.py class ReminderSerializer(HyperlinkedModelSerializer): schedule_date = serializers.DateField(format="%d-%m-%Y") class Meta: model = Reminder fields = ('id','content','created_at','schedule_date','schedule_time','user_id','is_release','is_deleted',) in serializer.py i just give the format but that format convering only in List page. as you can see listing is okey but the POST action field is not converted. API please look at image -
Error updating Django
I get the following error when I type "pip install -U Django": Collecting Django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/tn/d7vg_zcd5pq0cq3sltw0j7pc0000gn/T/pip-build-xIsFov/Django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/tn/d7vg_zcd5pq0cq3sltw0j7pc0000gn/T/pip-build-xIsFov/Django/ I read that this relates to the version of python. But if I type python3 in terminal I get : Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin -
how to build datatables in react components?
i am using react, and while checking for datatables(jquery plugin) to work with react, i found gigatables-react. In documentation, it seems nice and screenshots are very cool. but while implementing gigatables, i followed the steps, -> npm i gigatables-react -> import React, { Component } from 'react'; import SideBar from './../account_upload/sidebar'; import { Reactables, Header } from 'gigatables-react'; var settings = { struct: {// all in search: ['top'], rowsSelector: ['asc', 'top', 'bottom'], pagination: ['bottom'] }, requestType: 'POST', ajax: '/domain_ip/', columns: [ {data: "id"}, {data: "desc"}, {data: "title"}, {data: "date"}, {data: "types"}, {data: "info"} ] }; class Accounts extends Component { render() { return ( <div style={{"display": "inline-flex"}}> <div className="custom_sidebar"> <SideBar /> </div> <div className="content"> <Reactables settings={settings}> <Header data="id">ID</Header> <Header data="desc">Description</Header> <Header data="title">Name</Header> <Header data="date">Date</Header> <Header data="types">Date</Header> <Header data="info">Info</Header> </Reactables>, </div> </div> ); } } export default Accounts; wts wrong in this?? am getting error in console as, accountsSet-ccb24f5e97f47f7e0ca9.js:sourcemap:29807 Uncaught TypeError: Cannot read property 'csv' of undefined at t.value (accountsSet-ccb24f5e97f47f7e0ca9.js:sourcemap:29807) at t.value (accountsSet-ccb24f5e97f47f7e0ca9.js:sourcemap:29807) how do i resolve this?? -
Adding paths in Django to create more views
I am following the tutorial on the Django website. I try and replicate this: My code is as follows: views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, film_id): return HttpResponse("You're looking at film %s." % film_id) def results(request, film_id): response = "You're looking at the results of film %s." return HttpResponse(response % question_id) def vote(request, film_id): return HttpResponse("You're commenting on film %s." % film_id) films/urls.py from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ # url(r'^$', views.index, name='index'), # ex: /polls/ path('', views.index, name='index'), # ex: /films/5/ path('<int:film_id>/', views.detail, name='detail'), # ex: /films/5/results/ path('<int:film_id>/results/', views.results, name='results'), # ex: /films/5/vote/ path('<int:film_id>/vote/', views.vote, name='vote'), ] With this I am getting ERR_CONNECTION_REFUSED. If I comment out all the paths leaving only the index url, and also comment out from django.urls import path a page displays, but that is where I was at before trying to add more views. -
Django admin panel missing management form
The following exception occurs on admin panel while trying to change an object type (say a product), but it only occurs on SOME of them. I can't seem to debug this, where should I be inspecting? I'm not instantiating custom forms and formsets so I don't know what I could be doing wrong. Do you have any ideas where I should be inspecting? How can I know if the management form is rendered at all? I've saved the HTML source of the product change form. Traceback: File "/website/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/website/venv/lib/python3.4/site-packages/newrelic-2.50.0.39/newrelic/hooks/framework_django.py" in wrapper 499. return wrapped(*args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper 544. return self.admin_site.admin_view(view)(*args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner 211. return view(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in change_view 1512. return self.changeform_view(request, object_id, form_url, extra_context) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python3.4/contextlib.py" in inner 30. return func(*args, **kwds) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in changeform_view 1448. if all_valid(formsets) and form_validated: File "/website/venv/lib/python3.4/site-packages/django/forms/formsets.py" in all_valid 456. … -
Get QuerySet in QuerySet Python
I have a basic question about Python hope your guys help me. Get QuerySet in QuerySet Python I have a queryset: qrs1 = [1, 3, 5, 6, 9, 11, 16, 22] I want to get first, second and third object in this queryset and put it on a queryset like this result. result = [1, 3, 5] -
How to use pre_save methods in rest_framework serializers?
I know this is a noob question about DRF. I use latest version of Django and DRF. In my Django , I create slugs in a method using pre_save signals. def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Article.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug = new_slug) return slug @receiver(pre_save, sender = Article) def pre_save_article_receiver(sender, instance, raw, using, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_article_receiver, sender=Article) Then I can manage to write my views and serializers using DRF from rest_framework import serializers from yogavidya.apps.articles.models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = [ "title", "user", "content", "excerpt", ] --views.py-- app_name = 'articles' class ArticleListView(generics.ListCreateAPIView): lookup_field = 'pk' serializer_class = ArticleSerializer queryset = Article.objects.all() def list(self, request): # Note the use of `get_queryset()` instead of `self.queryset` queryset = self.get_queryset() serializer = ArticleSerializer(queryset, many=True) print(serializer.data) return Response(serializer.data) def get_queryset(self): return Article.objects.all() def get_object(self): pk = self.kwargs.get("pk") return Article.objects.get(pk=pk) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) class ArticleViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Article.objects.all().order_by('-title') serializer_class = ArticleSerializer When I post my form I …