Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How a search inside a website works?
Assume I have a website which contains articles, or blog, whatever. How can I create a search engine for the content in the site? I know that many Wordpress, Drupal and many other CMSs has such a feature. How it works and how it should be implemented in django? -
Form Validation Not Working Django
I'm not sure where I'm going wrong with the form validation... I also want to display error messages wether the for was submitted successfully or not. Currently, I'm using a DetailView, where a person can fill in a BookingForm() forms.py from django.core.validators import RegexValidator class BookingForm(forms.Form): Name = forms.CharField() Postcode = forms.CharField(max_length=8,label='Postcode') phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") Phone = forms.CharField(max_length=15,validators=[phone_regex],label='Phone') Date = forms.CharField(max_length=30,label='Date') Time = forms.CharField(max_length=10,label='Time') In my views.py I defined def post to allow post requests. def post(self,request,**kwargs): # put your own credentials here form = BookingForm(self.request.POST) if form.is_valid(): user_phone = form.cleaned_data['Phone'] postcode = form.cleaned_data['Postcode'] date = form.cleaned_data['Date'] account_sid = "***" auth_token = "***" found = Model.objects.get(id=self.kwargs['pk']) client = Client(account_sid, auth_token) client.messages.create( to=Model.phone_number, from_="+442033225719", body="You have a new booking." + "Call phone number:{}. Address: {}. Date:{}" .format(user_phone,postcode,date)) messages.success(request, 'Your booking was reserved.') else: messages.error(request, 'Error occurred.') return redirect('users:detail', pk=self.kwargs['pk']) And my model_detail.html which handles the form. <form action="" method="post"> {% csrf_token %} <input name="Name" type="text" id="name" placeholder="Name"> <input name="Postcode" type="text" id="location" placeholder="Postcode"> <input name="Phone" id="name" placeholder="07576258829"> <input name="Date" type="text" id="booking-date" data-lang="en" data-large-mode="true" data-min-year="2017" data-max-year="2020"> <input name="Time" type="text" id="booking-time" value="9:00 am"> <button type="submit" class="progress-button button fullwidth margin-top-5"><span>Book Now</span></button> … -
How to get a single object from a related model in django template
I have two models (Item and Album). Album has a foreign key pointing to Item like this class Item(models.Model): name = models.CharField(max_length=50) price = models.IntegerField() and class Album(models.Model): photo = ImageField(upload_to=item_directory_path) caption = models.CharField(max_length=100, blank=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) In my template {% for item in item_tags %} <div class="item-dock"> <a href="{{item.name}}"> <img src="{{item.album_set.photo.filter()}}" class="img-responsive"> <p class="item-name text-center">{{item.name|capfirst}}</p> </a> Now the real issue is. Given that querying on a related model will always return a queryset. How can I retrieve a single object(in this case, a single photo from this queryset) from the Album model for an Item in my template. I know about queryset and related manager! Any help, suggestions will be much appreciated -
Slow response in django
Currently I am inspecting a django queries(django-rest-framework) with django debug toolbar. The postgres database query time is about 100ms which is ok. But the response time took about 6 sec., which is slow. I found that the slowest(takes about 4 sec.) function is this: @transaction.atomic def create(self, *args, **kwargs): response = super(PersonView, self).create(*args, **kwargs) data = response.data product_data = data['packages'][0]['product'] person = Person.objects.get(pk=data['id']) if not person.info: product = Product.objects.get(pk=product_data['id']) PersonItem.objects.create(person=person, product=product) response.data = PersonSerializer(person).data return response Any ideas why the response is so slow or why this function takes so long ? -
How can I get Taggable field values separately in django?
First of all, I take one input from user(Ex: Symptom=fever). Symptoms are stored in database with taggable field and I have also one more taggable field called medicine. Taggable field is not iterable,so,how can I compare user input with database value. If one or more "disease" has symptom(fever) then I want all Other symptoms(stored with fever) with related disease name. example(Disease database): Disease_ | Symptoms | medicine......(other fields) dengue__ | Fever, Headache, Muscle pain, Joint pain, Bone pain, Pain behind Eyes |... flu______ | Fever, Muscles ache, Headache, Dry cough, Fatigue, Weakness, Chills, Sweats |... chickenpox| Fever, loss of appetite, headache, tiredness |... models.py class Disease(models.Model): did = models.AutoField(verbose_name='Disease Id', primary_key=True,auto_created=True) dName = models.CharField(max_length=100,unique=True) symptoms = TaggableManager(verbose_name='symptoms list', through=TaggedSymptoms) symptoms.rel.related_name = "+" medicine = TaggableManager(verbose_name='medicine list',through=TaggedMedicine) medicine.rel.related_name = "+" views.py def patfirst(request): if request.method == "GET": return render(request, 'personal/patfirst.html') if request.POST.get('Next'): newSymp = request.POST.get('newSymptom') args = {'newSymp' : newSymp,'didata':didata} #,'tagdata':tagdata} return render(request, 'personal/patfirst.html',args) patfirst.html <form method="post" action="#"> {% csrf_token %} Enter Symptom: <input type="text" name="newSymptom"/><br><br> <input type="submit" value="Next" name="Next"/> <input type="submit" value="None of these" name="NoneOfThese"/> </form> <div> {% for object in didata %} <ul> {% for tag in object.symptoms.all %} {% comment %} here i got all the symptoms stored … -
Tools for creating migrations without blocking django
I'm wondering - is where some tools for rewriting Django migrations so they will be without large downtime due to locks. I know how to do it by hand, but maybe where are tools for doing this automatically? Example: I add a column testff = models.BooleanField(default=False) By default django will generate sql which looks: BEGIN; ALTER TABLE "table" ADD COLUMN "testff" boolean DEFAULT false NOT NULL; ALTER TABLE "table" ALTER COLUMN "testff" DROP DEFAULT; COMMIT; which cause long blocking time on large tables, i want to get something like: BEGIN; ALTER TABLE "table" ADD COLUMN "testff" boolean; ALTER TABLE "table" ALTER COLUMN "testff" SET DEFAULT false; COMMIT; BEGIN; -- update existings rows, maybe not all together but in batches UPDATE "table" set testff=false ALTER TABLE "table" ALTER COLUMN "testff" DROP DEFAULT; ALTER TABLE "table" ALTER COLUMN "testff" NOT NULL; COMMIT; -
Django append domain name after localhost
I created a django project. when i start server and open 127.0.0.1:8000/admin. I redirect to http://127.0.0.1:8000/www.pxxx-xxxx.com/order/success/admin/ then django show error " Page Not Found(404) why django append url (www.pxxx-xxxx.com/order/success/) after 127.0.0.1:8000. Thanks in advance -
django get value from template.html
I really need help...i ve been asking a lot of times for help and looked on google and i haven't found anything.... I want when the I click on the Table name i want to get the ID and number and obtain the details about the that table. table_base.html {% extends 'base.html' %} {% block content %} <br> <div class="container"> <div class="jumbotron"> <h1> {{ table_name }} List</h1> {% if list_tables %} <table> <thead> <th>Id</th> <th>Name</th> <th>Date</th> </thead> {% for list in list_tables %} <tr> <td><pre>{{ list.id }}</pre></td> <td><pre><a class="btn-link" href="{% url 'tables:details' list.id %}">{{ list.name }}</a></pre></td> <td> <pre>{{ list.date }}</pre></td> </tr> {% endfor %} </table> {% else %} <p> No Records Found</p> {% endif %} </div> </div> {% endblock %} views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: return Crawledtables.objects.get(id=self.kwargs['table_id']) class Details(ListView): model = AllTables template_name = 'tables/table_list.html' context_object_name = 'details' paginate_by = 15 queryset = AllTables.objects.all() tables/urls.py urlpatterns = [ url(r'^$', views.table_base, name='tables'), url(r'^(?P<table_id>\d+)$', views.AboutDetail.as_view(), name='id-details'), url(r'^(?P<table_id>\d+)/details$', views.Details.as_view(), name='details'),] Basically i want to get the … -
Apache mod_wsgi better configuration
I am deploying my django-based web apps using apache mod_wsgi. This is my virtualhost: <VirtualHost _default_:*> ServerAdmin my_email@emails.com DocumentRoot /var/www/appWSGI/gestioner/gestioner/ Alias /static /var/www/appWSGI/gestioner/static/ <Directory /var/www/appWSGI/gestioner/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess gestioner python-path=/var/www/appWSGI/gestioner python-home=/var/www/appWSGI/env WSGIProcessGroup gestioner WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/appWSGI/gestioner/gestioner/wsgi.py WSGIPassAuthorization On </VirtualHost> This basic configuration is working fine. I would like to know if it is possible to improve this maybe there are other directives that i don't know about.. It is possible to have another configuration that boots performance ? thank you all in advance!! -
TypeError: __init__() got multiple values for keyword argument 'choices'
class StatisticsBaseForm(forms.Form): type_choice = forms.ChoiceField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0) period = forms.ChoiceField("Period", max_length=20, choices=settings.PERIODS, default='week') # product = models.IntegerField("Product", choices=) def __init__(self, *args, **kwargs): super(StatisticsBaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Statistics fields = '__all__' The traceback is the following File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/urls.py", line 6, in <module> from loanwolf.statistics.views import StatisticsIndexView File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/views.py", line 8, in <module> from loanwolf.statistics.forms import StatisticsBaseForm File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/forms.py", line 17, in <module> class StatisticsBaseForm(forms.Form): File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/forms.py", line 18, in StatisticsBaseForm type_choice = forms.ChoiceField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0) TypeError: __init__() got multiple values for keyword argument 'choices' I have this error, but I didn't manage to fix it. How could I go ahead on the error? -
Django admin returning whole object not just the FK field
I have searched and found a few answers however all the questions relate to the use of str etc... Im using the django admin module as it is interesting to play with and saves times, im having slight issues with my foreign keys in the sense they are returning all the field values not just the foreign key value. relevant models: class Order(models.Model): Order_ID =models.AutoField(primary_key=True) Dept_ID =models.ForeignKey(Department) Status =models.ForeignKey(Order_Statu) Order_Total =models.DecimalField(decimal_places=2, max_digits=5) def __str__(self): return '%s %s %s %s' % (self.Order_ID, self.Dept_ID, self.Status, self.Order_Total) class Order_Item(models.Model): Order_ID =models.ForeignKey(Order) Itm_Name =models.ForeignKey(Item) Quantity =models.IntegerField() def __str__(self): return '%s %s %s' % (self.Order_ID, self.Itm_Name, self.Quantity) and an example of what i mean: Screenshot im willing to admit that it is probably something i have overlooked in the documentation or it is something simple and obvious. -
How to query fields through an intermediate many to many field?
I use django 1.8 and python 2. What I have I have a model similar to this: from django.db.models import Model class Person(Model): name = models.CharField() class Unit(Model): unit_name = models.CharField() class PersonUnitRelType(Model): relation=models.CharField() class PersonUnitRelation(Model): person = models.ForeignKey(Person) unit = models.ForeignKey(Unit) I have a form similar to this: from django import forms from ceres.persons.models import Person, PersonUnitRelType, Unit class MForm(forms.Form): persons = forms.ModelMultipleChoiceField(Person.objects) units = forms.ModelMultipleChoiceField(Unit.objects) relations = forms.ModelMultipleChoiceField(PersonUnitRelType.objects) I have a view similar to this: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import MessageForm from ceres.persons.models import Person, PersonUnitRelType, Unit def messages(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): persons = form.cleaned_data['persons'] persons_list = [p.name for p in persons] relations = form.cleaned_data['relations'] for relation in relations: #TODO: Add all persons in 'relation' to persons_list units = form.cleaned_data['units'] for unit in units: #TODO: Add all persons in a unit witch have a 'relation' to persons_list. return HttpResponseRedirect("./") else: form = MForm() context = { 'form': form } return render(request, 'foo.html', context) What I want I want to add all names of persons to a list, whether they are selected direct, by a relation, or by a unit witch has a relation. How can I … -
Django admin add_view - prefill data with pk passed through URL
How to pre-fill Django NestedModelAdmin(inheriting from this class , not admin.ModelAdmin ) add_view with a model Object, I am passing Pk of that object in url. I can fetch the model object and prefill the fields but problem is ManyToManyRel and ManyToOneRel and OneToOneRel, some one please help me how I can solve this. I am using nested_inline Package for managing the Admin . No where it is mentioned how to handle these cases. I am using Django 1.9 and Python 2.7 -
Is there a way to exclude template url keyword arguments from view function definition?
I have a url in my template that's routed in this way: workoutcal/templates/calendar.html: <a href="{% url 'workoutcal:add' year=table.0 month=table.1 day=element.0 %}" class="add">Add workout</a> workoutcal/urls.py: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.add, name = 'add'), #Adding a workout for the date in question. workoutcal/views.py: def add(request,year,month,day): return HttpResponse("This is the add page) If I replace add() with this: def add(request): return HttpResponse("This is the add page) I get an error: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: add() got an unexpected keyword argument 'year' Meaning views.add had an unexpected keyword argument sent to it. Let's say that I want to pass these keyword arguments to the url in calendar.html because they're needed to get the correct url, but that I don't want to use these arguments in my view. Is there a way to exclude the arguments from the view function definition without getting this error? -
Type Error when using date from a Django form, I get: combine() argument 1 must be datetime.date, not tuple
I send a data dictionary to an external SOAP API using Zeep. I did this, and it was working: my_date = (form.cleaned_data['my_date']) #This comes from a Django form data2 = { "CashBookEntryData": { "Type" : "FinanceVoucher", "CashBookHandle" : { "Number" : 1 }, "AccountHandle" : { "Number" : 5820 }, "Date" : my_date, "VoucherNumber" : 100, "Text" : "Dagenssalg", "AmountDefaultCurrency" : 0, "CurrencyHandle" : { "Code" : "DKK" }, "Amount" : beloeb_salg, "DepartmentHandle" : { "Number" : 1 } } } To be able to better control how the dict is constructed, I have changed it to this: data1 =collections.OrderedDict() data1["CashBookEntryData"] = {} data1["CashBookEntryData"]["Type"] = "FinanceVoucher" data1["CashBookEntryData"]["CashBookHandle"] = { "Number" : 1 } data1["CashBookEntryData"]["AccountHandle"] = { "Number" : 5820 }, data1["CashBookEntryData"]["Date"] = my_date, data1["CashBookEntryData"]["VoucherNumber"] = 100, data1["CashBookEntryData"]["Text"] = "Dagenssalg", data1["CashBookEntryData"]["AmountDefaultCurrency"] = 0, data1["CashBookEntryData"]["CurrencyHandle"] = { "Code" : "DKK" }, data1["CashBookEntryData"]["Amount"] = 9999, data1["CashBookEntryData"]["DepartmentHandle"] = { "Number" : 1 } But now I get a Type Error: combine() argument 1 must be datetime.date, not tuple Any help is very appreciated! Best Regards Kresten Buch -
How to let a User upload an image in Django
Hi Guys I started coding in Django and i just wanted to make an 9gag-Clone. I followed some Tutorials and acctualy made a Blog. But when i "upload" Images it allways take the default value. So here is my Html: {% extends "posts/post_base.html" %} {% load bootstrap3 %} {% block post_content %} <h3 class="title">Poste Some Memes here</h3> <form action="{% url 'posts:create' %}" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="posten" class="btn btn-primary btn-large"> </form> {% endblock %} Here is my Views.py: class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('title','picture','group') model = models.Post def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) and at least my models.py: class Post(models.Model): user = models.ForeignKey(User,related_name='posts') created_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=30,default='Titel') picture= models.ImageField(upload_to=settings.MEDIA_ROOT, default='/static/img/default.png') title_html = models.CharField(max_length=30,default='Titel', editable = False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True) def __str__(self): return self.title def save(self,*args,**kwargs): self.title_html =misaka.html(self.title) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] #unique_together = ['user','title','bild'] urls.py and other htmlfiles work correctly. everything was makemigrated and migrated I just need to know why it dont save the Images, or dont upload it. -
How can I access 'user_id' is in model?
I got an error ,KeyError: 'user_id'. I wrote from app.models import User class UserPropriety(): def __init__(self, sheet_path): self.file = glob.glob(sheet_path) self.user_propriety = {} def read(self): for x in self.file: if "$" not in x: book = xlrd.open_workbook(x) sheet = book.sheet_by_index(0) cells = [ ('corporation_id', 0, 4), ('name', 5, 3), ('age', 6, 3), ('work', 7, 3), ] user_propriety_origin = OrderedDict() for key, rowy, colx in cells: try: user_propriety_origin[key] = sheet.cell_value(rowy, colx) except IndexError: user_propriety_origin[key] = None if user_propriety_origin['corporation_id'] in self.user_propriety: self.user_propriety[user_propriety_origin['user_id']].update(user_propriety_origin) continue self.user_propriety[user_propriety_origin['user_id']] = user_propriety_origin def save(self): for row_number, row_data in self.user_propriety.items(): user = User.objects.filter(user_id=self.user_propriety['user_id']) ) is_work = self.convert_symbol_to_int(self.user_propriety[row_number]['job']) is_age = self.convert_symbol_to_int(self.user[row_number]['age']) if user: user.update( work=is_work, age=is_age, ) def convert_symbol_to_int(self, arg): if arg == '△': return 2 elif arg == '○': return 1 elif arg == '×': return 0 else: return -1 y = UserPropriety('./data/*.xlsx') y.read() y.save() I really cannot understand why I cannot access 'user_id' because I imported from app.models import User,so I think 'user_id can be used.How can I fix this?What should I write it?Is this caused the way of calling value? -
TypeError: list indices must be integers, not str (the for loop method works, the lambda expression method doesnt)
Hey I have a working code which is this : # two_days_ago_chatted_visitors = None # yesterdays_chatted_visitors = None # chat_count = None # for x in apichat_data_bydate: # if x["date"] == two_days_ago.strftime("%Y-%m-%d"): # two_days_ago_chatted_visitors = x['visitors_with_conversation_count'] # else: # yesterdays_chatted_visitors = x['visitors_with_conversation_count'] # chat_count = x['conversation_count'] But I have been instructed to make my code simpler, and use something like this: two_days_ago_str = two_days_ago.strftime("%Y-%m-%d") data_for_two_days_ago = filter(lambda data_for_day: data_for_day['date'] == two_days_ago_str, apichat_data_bydate) two_days_ago_chatted_visitors = data_for_two_days_ago['visitors_with_conversation_count'] yesterday_str = two_days_ago.strftime("%Y-%m-%d") data_for_yesterday = filter(lambda data_for_day: data_for_day['date'] == yesterday_str, apichat_data_bydate) yesterdays_chatted_visitors = data_for_yesterday['visitors_with_conversation_count'] chat_count = data_for_yesterday['conversation_count'] But now the new code does not work and gives an error. TypeError: list indices must be integers, not str -
Type error field_contents_foreign_linked in django suit
I have django 1.8 project where I'm using django-suit==0.2.25. When I want to add a new item, I get an error: TypeError at /admin/tours/tour/add/ unsupported operand type(s) for -: 'NoneType' and 'int' This code is highlighted in path ...venv/lib/python3.5/site-packages/suit/templates/admin/includes/fieldset.html, error at line 44: <span class="readonly"> {{ field|field_contents_foreign_linked }} </span> Please for any hint. I tried already this: https://github.com/darklow/django-suit/issues/638 but without success. -
How to build a system to handle MQTT broker and Django
I am planning to build a home automation system where IoT devices communicate with the MQTT broker.The system also involves a Django web server that serves API for ios/android devices. I will describe an example of what I want to implement. An API call is made from mobile app to Django server to turn ON a device. When such API request is made to Django, it should psuh 'Turn ON' data to IoT device via MQTT protocol. Also, IoT devices send some real time data to the MQTT broker. Upon receiving such data I want to send push notifications to a mobile app via apns/fcm. How can I implement this?. Will Django channels serve the purpose or should I code my Django server to act as an MQTT client?. Or is there any other methods to implement this. Any advice will be helpful. -
location settings for Django Uwsgi Nginx Configuration for production
Django settings STATICFILES_DIRS = [STATIC_DIR, ] STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = '/home/sandyman/production/django_project/assets/' STATIC_URL = '/assets/' local machine example file /home/sandyman/development/django_project/css/bootstrap.min.css Template {% load staticfiles %} href="{% static "css/bootstrap.min.css" %}" Production environment ran python manage.py collectstatic this succesfully created all files in sub directories of **/home/sandyman/production/django_project/assets/** e.g. /home/sandyman/production/django_project/assets/css/bootstrap.min.css ** NGING configuration **server { server_name sandyman.xyz www.sandyman.xyz ; location /static { alias /home/sandyman/production/django_project/assets/; } }** ** GET Request ** Request URL:http://www.sandyman.xyz/static/css/bootstrap.min.css Request Method:GET **Status Code:404 NOT FOUND** file bootstrap is located in /home/sandyman/production/django_project/assets/css/bootstrap.min.css Please assist me .. Ive tried many iterations of values for nginx location but no success -
How to query the bilaminar data in Django ORM?
I have two models: class AddressRegion(models.Model): name = models.CharField(max_length=8) class AvailableArea(models.Model): name = models.CharField(max_length=8) addressregion = models.ForeignKey(AddressRegion, default=1) In the template I want expediently to use the query models. If now I query the datas I only knows use a for-loop: addressRegions = models.AddressRegion.objects.all() for ar in addressRegions: availableArea = models.AvailableArea.objects.filter(availablearea = ar) Then do some method to gather them. Is there some simple method to do that? because I believe Django is kind to users. -
Model itself and nested Meta use the same list
Django 1.11.5 The problem with this code is that I have already created a list in the model (comment "Field list created"). Then in Meta nested class I'd like to use the same list. Is it possible not to create the list twice? utils.py def get_distinctive_fields(): """ By these fields a people can be distinguished from one another. """ field_list = ['last_name_ru', 'premarital_surname_ru', 'first_name_ru', 'patronymic_name_ru', 'nickname_ru', 'year_of_birth', ] return field_list models.py class Person(LoginRequiredMixin, models.Model): def get_composed_string(self): composed_string = "" field_list = get_distinctive_fields() # Field list created. for field in field_list: composed_string += value def __str__(self): return self.get_composed_string() class Meta: unique_together = get_distinctive_fields() # Failed to use already created list. -
Pycharm Debugger - Django - Frames Not Available
If I run the Debugger without running the server everything looks ok. If I connect to the server, in the window I have the message "Connected" . If I run an url in the browser it works as usual, ignoring the breaking points. I followed the steps from the Pycharm video: https://blog.jetbrains.com/pycharm/2017/08/develop-django-under-the-debugger/ -
How to Filter in DRF Serializer using a Self Referencing Recursive Field
Using Python 3.x and the Django Rest Framework. I have a serializer with a Recursive Field (on self) which works as expected. However, I need a way to initially filter the nested children it returns by active = True. I've tried different ways to filter children by active=True, but I'm unable to get this working on the nested children that are returned in the serializer. Here is what I have. class MenuListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='menu_detail') children = RecursiveField(many=True, required=False) class RecursiveField(serializers.Serializer): """ Self-referential field for MPTT. """ def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data Model class Menu(MPTTModel, TimeStampedModel): name = models.CharField(max_length=100) active = models.BooleanField(default=1) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') This is what I have tried with ListSerializer' object has no attribute 'queryset' However, I'm not even sure this would work. class MenuListSerializer(serializers.ModelSerializer): def __init__(self, *args, request_user=None, **kwargs): # try and filter active in chrildrend before query set is passed super(CatalogueListSerializer, self).__init__(*args, **kwargs) # print(self.fields['children'].parent) self.fields['children'].queryset = self.fields['children'].queryset.filter(active=True) url = serializers.HyperlinkedIdentityField(view_name='menu_detail') children = RecursiveField(many=True, required=False) 2nd, I have also tried filtering on the view changing the query set method, but this does not seem to take when it's a child! It runs on the parent only! def get_queryset(self, …