Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relationship field in Django
I have the following structure in my models.py document: class Player(Human): name = models.CharField(max_lenght=24) jersey_number = models.IntegerField() class Coach(Human): name = models.CharField(max_lenght=24) class Team(models.Model): name = models.CharField(max_length=24) players = models.SomethinToSomething(Player) coaches = models.SomethinToSomething(Coach) I would like in my admin section to create teams and inside each team add some players and some coaches, I want that a player is related only with the team where I created it, so if I'm in team A it has to be impossible for me see and adding player of other team. I tried OneToOne() but I can link only one player and only one coach to the team. I tried ManyToMany() but when I make the second team the players of the first team are shared with the first team. What should I use? -
Setting up Django with MySQL on macOS
I'm new to Django, and trying to setup a basic web-app connecting to MySQL on macOS. However, I can't seem to get mysqlclient to work on macOS. I'm running a virtual environment and the following versions: $ brew --version Homebrew 1.8.5 $ pip --version pip 18.1 $ python --version Python 3.7.1 $ mysql --version mysql Ver 8.0.12 for osx10.14 on x86_64 (Homebrew) When I try pip install mysqlclient (https://pypi.org/project/mysqlclient/) I get ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 According to the documentation "You may need to install the Python and MySQL development headers and libraries like so:" $ brew install mysql-connector-c This gives another error: Error: Cannot install mysql-connector-c because conflicting formulae are installed. mysql: because both install MySQL client libraries Please `brew unlink mysql` before continuing. $ brew unlink mysql $ brew install mysql-connector-c ==> Pouring mysql-connector-c-6.1.11.mojave.bottle.tar.gz 🍺 /usr/local/Cellar/mysql-connector-c/6.1.11: 79 files, 15.3MB brew link mysql Error: Could not symlink bin/my_print_defaults Target /usr/local/bin/my_print_defaults is a symlink belonging to mysql-connector-c $ brew link --overwrite mysql Now I can start mysql from console, but when I update django, mysite settings.py to … -
PyCharm: No manage.py file specified in Settings->Django Support after refactoring project name
How to configure Pycharm to detect manage.py correctly? I've modified my project name perfectcushion to llama-stickers, using Pycharm IDE refactor -> rename. However, now I get this error: No manage.py file specified in Settings->Django Support when trying to runserver from Pycharm IDE. I also notice that the project is called: llama-stickers**[perfectcushion]**, why is there the old name of the project? Is there something I miss to refactor? settings.py """ Django settings for llama-stickers project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^_67&#r+(c+%pu&n+a%&dmxql^i^_$0f69)mnhf@)zq-rbxe9z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop', 'search_app', 'cart', 'stripe', 'order', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'llama-stickers.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), … -
Custom field Choices error in Django rest framework
I currently have a problem with creating a Choice field field in the Django Rest Framework. At first, looking for solutions in google, I found the best practices to apply the solution in my project. However, I came across problems in the service remaining from the application, bring it the way to present the field. Since I need to manipulate information through fixed options, I had to follow the methodology of even creating a specific serializer for this. Before using the ChoiceField field of the DRF, I am able to correctly choose the option but cannot demonstrate the value by getting the name of the variable in the response. My wish is that the value and not the name of the variable to be displayed. For this I created the following structure: My script, called choices.py # Model custom using ENUM concept from enum import Enum from rest_framework import serializers class ChoiceEnum(Enum): @classmethod def choices(cls): return tuple((x.name, x.value) for x in cls) #Serializer custom ChoicesField class ChoicesField(serializers.Field): def __init__(self, choices, **kwargs): self._choices = choices super(ChoicesField, self).__init__(**kwargs) def to_representation(self, obj): return self._choices[obj] def to_internal_value(self, data): return getattr(self._choices, data) My Model class Discount(models.Model): class DiscountTypes(ChoiceEnum): VALUE = 'value_absolute' PERC = 'percentual' employee … -
Django REST Framework -- Many2Many/Through
In general, I am confused about my serializers for the following models. Would someone be willing to look at this code and see if it makes sense/if something needs to be changed in order for my serializers to work properly? Here is the models.py: from django.db import models from django.contrib.auth.models import User class Course(models.Model): prefix = models.CharField(max_length=100) course_num = models.CharField(max_length=100) lecture_hours = models.CharField(max_length=20) lab_hours = models.CharField(max_length=20) credit_hours = models.CharField(max_length=20) date = models.DateField(auto_now=False, auto_now_add=False) previous_version = models.ForeignKey('self', on_delete=models.DO_NOTHING, blank=True, null=True) class Meta: ordering = ('prefix') class Term(models.Model): semester = models.CharField(max_length=100) year = models.CharField(max_length=100) name = models.CharField(max_length=200) courses = models.ManyToManyField(Course, through='Offering', related_name='terms') def termCourses(self): term_courses = self.courses.all() return term_courses class Offering(models.Model): term = models.ForeignKey(Term, on_delete = models.CASCADE) course = models.ForeignKey(Course, on_delete = models.CASCADE) instructor = models.ForeignKey(User, on_delete = models.CASCADE) class TermPermission(models.Model): creator = models.ForeignKey(User, on_delete = models.CASCADE) term = models.ForeignKey(Term, on_delete = models.CASCADE) Here is the serializers.py from django.contrib.auth.models import User, Group from .models import Course, Term, Offering from rest_framework import serializers class CourseSerializer(serializers.ModelSerializer) class Meta: model = Course fields = ('prefix,', 'course_num', 'lecture_hours', 'lab_hours', 'credit_hours', 'date', 'previous_version', 'terms' ) class TermSerializer(serializers.ModelSerializer) courses = OfferingSerializer(source='offering_set', many=True) class Meta: model = Term fields = ('semester,', 'year', 'name', 'courses', ) class OfferingSerializer(serializers.ModelSerializer) offering_term = … -
Fail to Import View from main Django project folder into app views.py
I have a problem to import a view from the main Django project views.py into my app's views.py. This is what happens: ImportError: cannot import name 'index' from 'ebdjango.views' (/Users/iamsuccessful/ebdjango/ebdjango/views.py) Inside dailytask/views.py (app folder) from ebdjango.views import index Inside ebdjango/views.py (main Django project folder) @login_required(login_url="/login") def index(request): user = request.user if user.userprofile.daily_task_done is False: return render(request, 'home.html') elif user.userprofile.daily_task_done is True: return task_done(request, pk=user.userprofile.daily_task) What do I need to do to import the view Index into the app views.py? -
Unable to extend Django 2.1 password reset template
I'm trying to extend the password reset form like so: <!-- templates/registration/password_reset_form.html --> {% extends registration/password_reset_form.html %} {% block content %} <h1> hello </h1> {% endblock %} As far as I can tell, this should take the template from /usr/local/lib/python3.7/site-packages/django/contrib/admin/templates/registration/password_reset_template.html (which exists, I checked) and replace the block content with the one at templates/registration/password_reset_form.html. But this isn't happening. In fact, there is no change, nor is there an error. What am I doing wrong? -
can you update a model instance without calling save( )?
I am working on a project that requires unique slugs. The slugs are dynamically created in a custom save() method using the objects name. class SlugMixin(models.Model): def save(self, *args, **kwargs): slug = striptags(self.name) self.slug = slugify(slug) super(SlugMixin, self).save(*args, **kwargs) class Meta: abstract = True name is not unique so it's possible to have multiples of the same slug. So the solution i was working with is appending the id of the instance to it's slug in a post_save. The problem here is by attempting to update the slug with the id. save() needs to be called again. def ensure_unique_slug(sender, instance, created, **kwargs): if created and Person.objects.filter(slug=instance.slug).count() > 1: instance.slug = instance.slug + '-{}'.format(instance.id) instance.save() rendering the update useless. is there anyway to update the slug without calling save() -
In Django, what is a good example of static files ending up in a reference loop?
Per the Django-1.11 upgrade notes re: python manage.py collectstatic "Testing needs to be done to make sure that - Static files do not end up in a reference loop - Static files are not chained too deep (might not resolve)" I've been trying to figure out a good example of the situation to which this is referring. A quick example would be appreciated, thanks. -
Django Rest Framework get a lookup field as a list of hyperlinks
I have a model Album and a model Photo, which references the first one through a FireignKey field. I want the ModelSerializer for model Album to return a list of hyperlinks to relate entries in model Photo through a lookup field, but I only get it to return a list of ids. These are my models: class Album(models.Model): name = models.CharField(max_length=200, verbose_name=_("Name")) description = models.TextField(null=True, blank=True, verbose_name=_("Description")) company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='albums', verbose_name=_("Company")) access_code = models.CharField(max_length=30, default=_create_access_code, verbose_name=_("Internal Use")) class Meta: verbose_name = _("Album") verbose_name_plural = _("Albums") def __str__(self): return "[{}] {} ({})".format(self.pk, self.name, self.company.id) class Photo(models.Model): name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_("Name")) album = models.ForeignKey(Album, on_delete=models.PROTECT, related_name='photos', verbose_name=_("Album")) photo = models.ImageField(verbose_name=_("Photo")) class Meta: verbose_name = _("Photo") verbose_name_plural =_("Photos") def __str__(self): return "[{}] {}".format(self.pk, self.name) And this is my serializer: class AlbumSerializer(serializers.ModelSerializer): class Meta: model = proxies.AlbumProxy fields = ('id', 'name', 'description', 'company', 'access_code', 'photos') I want the field photos to return a list of hyperlinks, but I get a list of ids: "id": 1, "name": "Navidad 2018", "description": "La primera", "company": 1, "access_code": "xxxxxxxxxx", "photos": [ 11, 10, 7, 6 ] -
Django ModelForm Not Saving to DB
I'm new to Django and having a hard time figuring out how to get a model form to save to my db. I've been following some tutorials/books and spending a lot of time on SO and I just can't figure this piece out. The book examples i'm following is creating an IMDB type website where a user can vote movie quality (changed to games for my example). python v. 3.6.7, django v. 2.1.3, postgres v. 2.2.2 Here is the model i'm trying to store and the associated manager class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self, game, user): try: vote = Vote.objects.get(game=game, user=user) return vote except self.model.DoesNotExist: vote = Vote(game=game, user=user) return vote class Vote(models.Model): objects = VoteManager() value = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE,) voted_on = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'game') Now the model form I am trying using to try and store this class VoteForm(forms.ModelForm): user = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=get_user_model().objects.all(), disabled=True) game = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=Game.objects.all(), disabled=True) value = forms.FloatField() class Meta: model = Vote fields = ('user', 'game', 'value') Template i'm using to display this information. {% block main %} <h1>{{ object }}</h1> <p class="lead"> {{ object.summary }} </p> {% endblock %} {% block sidebar %} {# … -
Django Autocomplete-light dependant visibility
I have 2 autocomplete dropdown list using autocomplete-light I want that the visibility of the second dropdownlist (cars) be dependent on the value of the first dropdownlist(raste) but i dont know how can i find their id ? Forms.py : class StocksForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StocksForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['style']= 'width:60%' class Meta(): model=Stocks fields=('user','raste','car','stname','mark','description','pic','price') widgets = { 'raste': autocomplete.Select2(url='BallbearingSite:stock_autocomplete'), 'car': autocomplete.Select2(url='BallbearingSite:car_autocomplete'), } Html : <form enctype="multipart/form-data" method="post" > {% csrf_token %} {{ stocks_form.as_p }} <input id="savestocks" type="submit" name="" value="ثبت"> <input type="text" name="search" id="txtSearch" onkeyup="searchOpen()" /> <input type="text" id="id_input"> <div> <input type="text" id="contact_name_search_input" name="contact_name_search" /> </div> <div class="ui-widget"> <label for="places">Places: </label> <input id="places"> </div> </form> and these are the javascript codes which i wrote but it doesnt work ! <script> $(document).ready(function() { $('#select2-id_raste-container').change(function() { var selectedValue = $(this).val(); if(selectedValue === 'abc') { $('#select2-id_car-container').closest('span').hide(); } else if (selectedValue === 'bcd') { $('#select2-id_car-container').closest('span').show(); } }); }); </script> the html codes which are in the firefox consule : <label for="id_raste">Raste:</label> <select class="form-control select2-hidden-accessible" data-autocomplete-light-function="select2" data-autocomplete-light-url="/stock_autocomplete/" id="id_raste" name="raste" style="width:60%" tabindex="-1" aria-hidden="true"> </select> <span class="select2 select2-container select2-container--default" dir="ltr" style="width: 60%;"> <span class="selection"> <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-id_raste-container"> <span class="select2-selection__rendered" id="select2-id_raste-container"><span class="select2-selection__placeholder"> </span> </span> <span … -
Problem with ERR_TOO_MANY_REDIRECTS django 2.1
I started to create login module in django. Login module is ok but I have problem with logout. When i click Logout - we see "error -ERR_TOO_MANY_REDIRECTS" Probably something in this file is incorect: account/urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='account/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), path('dashboard/', views.dashboard, name='dashboard'), -
How to POST data to a Django Form that contains checkboxes
I have a problem when I am testing my registration form in Django. I am trying to make a POST request but I cannot select a checkbox field. self.response = self.client.post(url, { 'username': 'testuser', 'password': 'testuserpassword', 'first_name': 'testtt', 'last_name': 'userrr', 'image': '', 'email': 'testuser@gmail.com', 'gender': 'M', 'dob': '10/10/1996', 'hobby': 'Fishing' }) This is my line of code. The problem is at Hobby. The registration page is made of two forms. A profile form and a hobby form. There is a many-to-many relationship between Profile and Hobby models. When I make the above POST request, I get this (Select a valid choice): Thank you in advance! -
How can get minute_step=15 using TimeField in Django?
I created a form with two time fields. I would like to get only 00mn 15mn 30mn and 45mn in my minutes widgets. Thank you Here is my form: class JobForm(forms.ModelForm): start = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) end = forms.TimeField() class Meta: model = Job fields = ('start', 'end') here is my template: <div class="input-group clockpicker" data-placement="left" data-align="top" data-autoclose="true"> <form method="POST" class="post-form"> {% csrf_token %} <table class="table table-bordered table-fit" border="0" > {{ form }} </table> <button type="submit" class="save btn btn-default">OK</button> </form> </div> <script type="text/javascript"> $('#id_start').clockpicker({ donetext: 'OK'}); $('#id_end').clockpicker({donetext: 'OK'}); </script> -
It is possible to update db from web-page in Djano?
There is a django-site with models and db. It is possible to update/add to the db info from my models like a = Model() a.name = 'name' a.save() directly form site page, but not througth admin page? -
Django form action attribute is not working propely
I am working on app in django 1.11, on search feature. I installed elasticsearch - here all things are working. In base.html and under url 127.0.0.1:8000 - I have form to search and I would like to keep this form here. On another hand I have search app with view, url, template - under url 127.0.0.1:8000/search/ - search is working here. To solve this problem - search on main page and redirect on site with results I was trying to use action attribute in django form. form in base.html <form action="{% url 'search:search' %}" method="post"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" id="q" {% if request.GET.q %}value="{{ request.GET.q }}"{% endif %} name="q" placeholder="Search"> <div class="input-group-append"> <button class="btn btn-outline-primary" type="button">GO</button> </div> </div> </form> view in search app def search(request): q = request.GET.get('q') if q: posts = PostDocument.search().query('match', title=q) else: posts = '' return render(request, 'search/search.html', {'posts': posts}) template with results {% extends 'base.html' %} {% block content %} {% for p in posts %} <a href="#">{{ p.title }}</a> {% endfor %} {% endblock content %} {% block sidebar %}{% endblock sidebar %} -
No module named django, but django is installed - miniconda has interfered with path?
So to clarify, I had already got Django to work. The main thing I had done between installing Django and having this problem is that I installed miniconda3 and MySQLdb. I'm running Python 3.7.1, pip 18.1 and as far as I know should have Django 2.1.4. From /Users/me I run: python3 -m django --version and I get: /Users/me/miniconda3/bin/python3: No module named django From this I can see that the path seems to have been changed to miniconda, and I'm not sure how that has happened. If I run: pip3 install Django It then tells me: Requirement already satisfied: Django in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (2.1.4) Does anyone have either any idea of what could have happened and how to rectify it? -
Django:Guide regarding OTP to use in Django app
I am so much confused about OTP function in Django app.help me understand to get it in my project.I searched about many Django_otp ,Twilio etc.But i get confused in all this option.so i want a clear step guide about it. -
Thumbnails wont show up in the table using sorl-thumbnail within if tags
I try to show images as thumbnails with sorl-thumbnail, but they won't show up... If I use the sorl tag outside of the table, withouth the if tags, they will show up, but as shown below, it doesn't. I see some empty images and when I right-click and view the image I get this message: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>FB1B90D61EDDABFB</RequestId> <HostId>kNOYKLZhcN0N7cgfEfD+bNOs3u4UU2E86gGISMySkNJhobrIA9yFLBh9rgJUbQw+gbyonys5lt8=</HostId> </Error> When I use the {% thumbnail %} tags outside the table/if statement tags, they will show up... I can't find out what might be the cause of this... I work local and have some AWS setup for the live app Here's the code from the template: {% if list.parent.parent_image %} {% if list.image_is_parent %} <td> {% thumbnail list.parent.parent_image "40x40" as im %} <img src="{{ im.url }}"> {% endthumbnail %} </td> {% else %} <td><img src="/media/products/assets/no-image.png" class="img-fluid"></td> {% endif %} {% else %} {% if list.image %} <td> {% thumbnail list.image "40x40" as im2 %} <img src="{{ im2.url }}"> {% endthumbnail %} </td> {% else %} <td><img src="/media/products/assets/no-image.png" class="img-fluid"></td> {% endif %} {% endif %} -
How to return DateTime in different timezone from Django Rest Framework serializer
What is the pythonic way to return DateTimeField of some Django model using an arbitrary timezone in Django Rest Framework? At the moment my view returns DateTime in UTC, because as far as I know Django stores timezone-aware datetimes as datetimes in UTC timezone. Models: class TimezoneMixin(models.Model): TIMEZONES = [(i, i) for i in country_timezones['ru']] timezone = models.CharField(choices=TIMEZONES, ...) class Meta: abstract = True def get_timezone(self): if self.timezone: return timezone(self.timezone) return get_current_timezone() class Organization(TimezoneMixin, models.Model): ... class Event(models.Model): organization = models.ForeignKey(Organization, ...) date_created = models.DateTimeField(auto_now_add=True, ...) ... Serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('organization', 'date_created', ...) In the ViewSet I populate data as follows organization_id = ... # Some logic to get required organization_id data = { 'date_created': timezone.now(), # django.utils.timezone 'organization': organization_id, ... } serializer = EventSerializer(data=data) if serializer.is_valid(): serializer.save() response_data = serializer.data.copy() # Some logic to rename one of the keys in response data ... return Response(response_data, ...) # rest_framework.response.Response Even if I replace timezone.now() with something like timezone.now().astimezone(organization.get_timezone()) I still receive UTC DateTime in response. Am I correct that it is not a good idea to parse date_created string from response_data, create a DateTime object from it, convert to different timezone and format … -
Django: ModelForm doesn't submmit
I've a 2 steps form. Actually these are 2 forms. The first one lets me capture size and quantity variables from rendered ChoiceFields and save them in session. 2nd Form: renders a FileField and a CharField; and on submit is supposed to retrieve the size and quantity stored in session. So at the end I'm submitting a record of SizeQuantity model with 5 fields: product (ForeignKey to Product model), size, quantity, image (making this optional - null True / blank True to discard its causing any troubles), comment (optional). However, my when I click on the form submit button, on StepTwoForm (2nd form and final) my form doesn't submit -and therefore does not save a record in DB, I don't see any entering by the admin (model is registered). models.py class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('shop:products_by_category', args=[self.slug]) def __str__(self): return '{}'.format(self.name) class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField() available = models.BooleanField(default=True) created = … -
Django endpoint slow, nested serializer with too many results
I have the following models model_A, model_B, model_c. model_B has a foreign key on model_A model_C has a foreign key on model_B With the below code I am able to get the c__objects from the endpoint /a/<a_id> as a nested property on the list results for the a_id given. Example response { "id": 2, "name": "A record in model C", "email": "example@email.com", "c__objects": [ { "id": 54, . . more-stuff-here . } ], . . . } models.py class model_A(models.Model): name = models.CharField(max_length=200, db_index=True) email = models.EmailField(blank=True) description = models.CharField(max_length=300, null=True, blank=True) class Meta: ordering = ["-id"] def c__objects(self): return C.objects.filter(b__a=self).filter(end_date__gte=now()) class model_B(models.Model): a = models.ForeignKey(A, related_name="a") description = models.CharField(max_length=200) class Meta: ordering = ['-id'] . . . class model_C(models.Model): b = models.ForeignKey(B, related_name="b") description = models.CharField(max_length=2000) end_date = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ['-id'] . . . views.py class A_ViewSet(viewsets.ReadOnlyModelViewSet): def retrieve(self, request, pk=None): queryset = model_A.objects.all() queryset = get_object_or_404(queryset, pk=pk) serializer_context = {'request': request} serializer = A_Details_Serializer(queryset, context=serializer_context) return Response(serializer.data) serializers.py class VenueDetailsSerializer(serializers.ModelSerializer): c__objects = YetAnotherSerializer(many=True) class Meta: model = A fields = ('id', 'name', 'email', 'description', 'c__objects') Now all of these are fine it works when the nested c__objects aren't much, however let's say the c__objects … -
What is the use of Class Meta in django? [duplicate]
This question already has an answer here: How does Django's Meta class work? 4 answers Please explain in easy terms as I have just started to learn django. -
Python to search for complete text in database
Hi guys i'm developing my project and i'm having some trouble. I want my system to search the database for the query; if the input doesnot match with the database then the system should be able to retrieve the correct value of my query. The system is searching The Quran . For example Query:ملكيوم الدين Result:ملك يوم الدين If you guys have any suggestion do let me know what to do currenty i'm using "pyquran" library but unfortunately it doesnot support this feature.