Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pre_save signals work when Model is saved but not ModelForm?
I created a pre_save signal to check if a field was updated before savings a model and shoot off a webhook if so. This works fine when I create the model from ./manage.py shell and save it, but if I create it on my site, which utilizes a form, it does not fire off the webhook. Why is this? apps.py from django.apps import AppConfig class ClientConfig(AppConfig): name = 'client' verbose_name = "Clients" label = 'client' def ready(self): import client.signals signals.py @receiver(pre_save, sender=ClientContact) def send_hook_on_roadmap_update(sender, instance, **kwargs): """Watches for ClientContacts to be saved and checks to see if the pipeline attribute has changed. """ try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed else: if not obj.pipeline == instance.pipeline: # Field has changed instance.pipeline_updated() models.py class ClientContact(models.Model): title = models.CharField(_("Title"), max_length=50, blank=True, null=True) first_name = models.CharField(_("First name"), max_length=30, ) last_name = models.CharField(_("Last name"), max_length=30, ) email = models.EmailField(_("Email"), blank=True, max_length=75) create_date = models.DateField(_("Creation date")) address = models.ForeignKey('AddressBook', blank=True, null=True, on_delete=models.SET_NULL) pipeline = models.ForeignKey(Pipeline, blank=True, null=True, on_delete=models.SET_NULL) forms.py class ContactModelForm(forms.ModelForm): def __init__(self, client, organization, *args, **kwargs): super(ContactModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'first_name', 'last_name', 'title', 'email', 'address', 'pipeline', ) self.helper.form_class = 'form-horizontal' … -
Reset Django Form
I would like to know How it's possible to clear (Reset) a Form when you are completing it ? I can submit the Form to my MySQL Database and I thought that Reset process was the same, but apparently no : <!--DOCTYPE html --> <html> <body> <h1 align="center"> Formulaire d'acte de naissance </h1> <form method='POST' action=''> {% csrf_token %} <h3> Partie contenant les informations de l'enfant</h3> {{ Cform.as_ul}} <!-- Display child part formulary --> {{ value|date:"%d/%m/%Y" }} {{ value|time:"H:M" }} <h3> Partie contenant les informations des parents </h3> {{ Pform.as_ul }} <!-- Display parent part formulary --> {{ value|date:"%d/%m/%Y" }} <br></br> <input type ="submit" value="Valider le formulaire" /> <input type ="reset" value="Reset" /> </form> </body> </html> This is my views.py file : #-*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.template import loader from .models import Child, Parent from .forms import ChildForm, ParentForm # Create your views here. def BirthCertificateAccueil(request) : # Fonction permettant de créer la page d'accueil de la rubrique Acte de Naissance #Cherche le fichier html accueil et le renvois template = loader.get_template('accueil.html') return HttpResponse(template.render(request)) def Formulary(request) : # Fonction permettant de créer le formulaire Acte de Naissance et le remplissage … -
filter objects using other model's objects
I have a Parent, Name, and Kid Models : models.py class Parent(models.Model): title = models.CharField(max_length=250) address = models.CharField(max_length=250) class Name(models.Model): title = models.CharField(max_length=250) class Kid(models.Model): family = models.ForeignKey(Parent) name = models.ForeignKey(Name) age = models.IntegerField() city = models.CharField(max_length=250) and I have a view function to display Parent objects only if Kid objects related to the Parent are all in the dictionary: views.py def index(request): patterns = [ {'name__title': 'samy', 'age__lt': 15, 'city': 'paris'}, {'name__title': 'sally', 'age__gt': 20, 'city': 'london'} ] filter_q = reduce(operator.or_, map(lambda p: Q(**p), patterns)) qs = Kid.objects.filter(filter_q).values_list('id', 'family_id') family_ids = set() child_ids = list() for child_id, family_id in qs: family_ids.add(family_id) child_ids.append(child_id) incomplete_family_ids = set(Kid.objects.exclude(id__in=child_ids).filter(family_id__in=family_ids).values_list('family_id', flat=True).distinct()) complete_family_ids = family_ids - incomplete_family_ids parents = Parent.objects.filter(id__in=complete_family_ids) template = 'index.html' context = {'parents': parents} return render(request, template, context) What if I want to replace the pattern dictionary with models objects, like: class Pattern(models.Model): title = models.CharField(max_length=250) class PatternItems(models.Model): name = models.ForeignKey(Name) age = models.integer() city = models.CharField(max_length=250) pattern = models.ForeignKey(Pattern) so instead of the dictionary. I wonder if its possible to to select a pattern from Pattern models to displays Parent objects if all it's related Kid objects are in PatternItems using a Pattern object. the whole idea is to make the … -
Which is better? city.state.id or city.state_id
I have to table with relation. State id name City id name state Which is better in performance? city.state.id or city.state_id -
django moving a OneToOneField to a ForeignKey while keeping data
I just took over a Django project from another developer and am trying to understand what he did. If someone could let me know if I understand correctly and point me in the right direction that would be great. At the moment the models look like this (simplified): class Address: street_name=models.CharField() class Provider: address=models.OneToOneField(Address) class User: address=models.OneToOneField(Address) But this means that each Address is unique, so no people living in the same house. For me (coming from a Symfony framework) I would add a OneToMany field in Provider and User but in Django that is a ForeignKey in Address. class Address: street_name=models.CharField() provider=models.ForeignKey(Provider) user=models.ForeignKey(User) class Provider: class User: But obviously I would like to keep the address information that is in the database. How should I do that? Should I look into Data migration (https://docs.djangoproject.com/en/1.8/topics/migrations/#data-migrations) -
Filtering on Django backreferences
I am trying to query all objects in a table without backreferences from another model. class A(models.Model): pass class B(models.Model): reference = models.ForeignKey(A) In order to get all A objects with no references from any B objects, I do A.objects.filter(b__isnull=True) The Django documentation on isnull does not mention backreferences at all. Can I get into trouble with this or is it just poorly documented? -
Pre-populate formset with a user saved data on revisit
I need to pre-populate a formset field with a user's saved data Here is my form.py EssayQuestionFormSetBase = modelformset_factory(models.EssayQuestion, extra=0, fields=('prompt',), widgets={ 'prompt': forms.TextInput( attrs={'readonly': True, 'class': 'borderless'}), }, ) class EssayQuestionFormSet(EssayQuestionFormSetBase): def add_fields(self, form, index): super(EssayQuestionFormSet, self).add_fields(form, index) form.fields['answer'] = forms.CharField(widget=forms.Textarea, label='') As you can see, I added a field to accept answers in the EssayQuestionFormSet My views.py looks like following: class QuizDetail(View): def get(self, request, **kwargs): step = models.Quiz.objects.get(pk=self.kwargs['step_pk']) eqs = models.EssayQuestion.objects.filter(quiz_id=self.kwargs['step_pk']) eqs_formset = forms.EssayQuestionFormSet(queryset=eqs, prefix='essay') def post(self, request, *args, **kwargs): step = models.Quiz.objects.get(pk=self.kwargs['step_pk']) eqs = models.EssayQuestion.objects.filter(quiz_id=self.kwargs['step_pk']) eqs_formset = forms.EssayQuestionFormSet(request.POST, queryset=eqs, prefix='essay') if eqs_formset.is_valid(): for form in eqs_formset: # create a NEW Answer for this form's associated question new_answer = models.Answer.objects.create(question=form.instance, eq_answer_text=form.cleaned_data.get('answer'), student=models.Student.objects.get(user=request.user.pk)) Currently, the view properly renders empty Textarea field for the answer field on the get and properly saves answers on the post. My question, however, how can I pre-populate the answer field with user's saved answer? Here is the Answer model class Answer(models.Model): date_answered = models.DateTimeField(default=timezone.now) student = models.ForeignKey(Student, blank=True, null=True, related_name='answers') question = models.ForeignKey(Question) eq_answer_text = models.TextField(blank=False, null=True) -
django: commit and raise inside transaction.atomic()
We are trying to migrate from commit_manually to atomic so we can upgrade Django to at least 1.8 in a legacy project. In most of cases we need to do something like that: with transaction.atomic(): obj = Entity.objects.select_for_update().get(pk=pk) try: obj.do_something() obj.set_some_status() obj.save() except SomeException: obj.set_failed_flag() obj.save() raise becuase the callee needs this exception information to continue with the certain flow. But in this case the transaction/savepoint will be rolled back and that's not what we want since we want obj.set_failed_flag() to be committed. Also it seems logical to set it inside the same atomic block since we already have a locked row for this object. Any ideas/patterns? Thanks in advance! P.S. It was so easy with old manual transaction management! P.P.S. We use exceptions also for "early-exit" and moving to some flags etc. would bring a log of mess and I personally would love to avoid it. -
Celery task always PENDING - but only sometimes
I have a Django app running on Heroku. For this, I have some Celery tasks set up, and am using Heroku Redis as a broker and result store as per the Heroku documentation. Everything seems to work fine - I can start tasks, and get their status by using task.myTask.AsyncResult(taskId). This correctly tells me when a task is complete and I'm able to use .get() on the task to get the output that I need. Except it seems to randomly stop working - after some amount of time (or maybe some number of tasks being started? Can't pinpoint either way), it starts returning that the task task.myTask.AsyncResult(taskId).state is permanently PENDING. Even though my logs indicate that the task successfully returned and generated the output I'm looking for, I'm unable to get this by querying AsyncResult. The only solution seems to be to restart my server (e.g. by pushing a new commit to Heroku and forcing it to restart), which then fixes the problem until it stops working again at a later stage. I would post logs, but am unsure what's even relevant here... -
How to adjust minimal difference in data points in linewithfocuschart django nvd3?
I have a model to display data for different parameters. I am trying to use django nvd3 linewithfocuschart. The model looks like : class CompanyData(models.Model): company = models.ForeignKey(Company) date = models.DateField() data1 = models.FloatField(null=True, blank=True) data2 = models.FloatField(null=True, blank=True) data3 = models.FloatField(null=True, blank=True) data4 = models.FloatField(null=True, blank=True) data5 = models.FloatField(null=True, blank=True) The values in these fields are in float points. For example : If 'c' is a company than c.data1 = 0.6 c.data2 = 0.7 c.data3 = 0.8. .... So, the data will be in float values. When plotted into the graph all the data points coincides in the same line. How can I adjust the floating point values while plotting so that the line will be distinct? In the graph, the data from all the fields data1,data2,data3... coincides with each other. How to make it clear? -
Can't get POST data in django rest framework
Here is my view, @api_view(['GET','POST']) def login(request): if request.method == 'GET': posts = Posts.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) elif request.method == 'POST': usr = request.data.get('username') print(request.data) pwd = request.data.get('password') try: user = Users.objects.get(username=usr) if user.password == pwd: return Response(UserSerializer(user).data) else: return Response({}) except Users.DoesNotExist: return Response({}) here is my serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = ('id','username','password') here is my model class Users(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) def __str__(self): # __unicode__ on Python 2 return self.username This is my call in angularjs controller $http.post("api/v1/login/",{"username":$scope.username,"password":$scope.password}) .then( function(response){ console.log('r',response.data) }, function(response){ console.log('e',response) } ); I am getting an empty object in my view.I also added $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; in angular config as suggested in some blog.the request.data is still empty.Where am I doing wrong please guide me properly.Thanks in advance. -
Django polls picture integration
I just finished django intro tutorials on voting app. I have added my outcome of default django tutorial project in this post. I have added the wanted result which you will understand better after reading trought this post. And I have added aftermath page of what happens when you click the first 'What's up' question. github.com/fribil/django-picture-poll-integration/tree/master/mysite/mysite Wanted result Current voting when 2nd question 'What's up?' is clicked Basically it is the - You need to put two questions which's content instead of text, consists of picture. You need to show result. Add another button to the first page like the one that says 'click to view the result'. Where in library I look for the code (filenames) that has to be edited and where in the world wide web I can look up for this code? -
Django Models: global name 'SomeModel' is not defined - same python file
class Employee(models.Model): name = models.CharField(max_length=80, db_column=u'NOME', verbose_name=_('Name')) def get_jobs(self): jobs_before=Itinerary.objects.select_related('job').\ filter(contract__employee=self.id).\ filter(start_date__lte=date.today()).order_by('-start_date') return jobs_before """ a few lines below """ class Itinerary(models.Model): contract=ForeignKey(Contract) ... some fields Well, I have some odd behavior here. 1 ) The app is runing ok in the development mode with (runsever) but crashes with nginx/guncorn/wsgi. global name 'Itinerary' is not defined 2) It was working ok for years until yesterday - no changes, just a restart in the server. 3) I can't change the position because Employee has a Contract and contract is a foreignKEy in Itinerary. Why is the app complaining about a class in the same .py file? -
Django middleware with login and password which hides all the website
I have written following middleware which renders form and asks user for login and password. The middleware should be applied to the whole website: class InviteLoginForWebsiteMiddleware(object): def process_request(self, request): if request.session.get('has_invite') == True: return None form = WebsiteLoginForm() extra_context = dict() extra_context['form'] = form template_name = 'websiteLogin.html' if request.method == "POST": form = WebsiteLoginForm(request.POST) if form.is_valid(): login = form.cleaned_data['login'] password = form.cleaned_data['password'] if login == "mylogin" and password == "mypassword": request.session['has_inv'] = True return None return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request) The problem with this solution is that when I am creating form inside process_request csrf token is missing in the form. I have looked for the answer and found that developers recommend to generate form and process form request in process_view After moving all the code into process_view like: def process_view(self, request, view_func, view_args, view_kwargs): if request.session.get('has_inv') == True: return None form = WebsiteLoginForm() extra_context = dict() extra_context['form'] = form template_name = 'websiteLogin.html' if request.method == "POST": form = WebsiteLoginForm(request.POST) if form.is_valid(): login = form.cleaned_data['login'] password = form.cleaned_data['password'] if login == "mylogin" and password == "mypassword": request.session['has_inv'] = True return None return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request) the code started to work, csrf token was generated and I was able to submit form with login … -
sqlite3 issues in Django
Im quite new in Django, I want to use sqlite3 as my database but Im getting some errors while, I try to use syncdb C:\Users\mmtbz\PycharmProjects\Web1>python manage.py syncdb The following is the error that I get: enter code here Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 316, in execute settings.INSTALLED_APPS File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__ self._setup(name) File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python34\lib\importlib\__init__.py", line 104, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2231, in _gcd_import File "<frozen importlib._bootstrap>", line 2214, in _find_and_load File "<frozen importlib._bootstrap>", line 2203, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1448, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "C:\Users\mmtbz\PycharmProjects\Web1\Web1\settings.py", line 81, in <module> 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), TypeError: unhashable type: 'dict' This is the code in my settings.py on line 81 : 77 DATABASES = { 78 # 'default': 79 { 80 'ENGINE': 'django.db.backends.sqlite3', 81 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 } 83 } Thanks for your help! -
Heroku: RabbitMQ Bigwig connection reset every 3 minutes
I'm trying to run a background celery broker on Heroku as part of a Django webapp. When running on Heroku with RabbitMQ Bigwig (free tier), systematically every 3 minutes I get the following connection reset: 2016-11-23T12:31:04.416209+00:00 app[worker.1]: [2016-11-23 12:31:04,415: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... 2016-11-23T12:31:04.416224+00:00 app[worker.1]: Traceback (most recent call last): 2016-11-23T12:31:04.416225+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/celery/worker/consumer.py", line 280, in start 2016-11-23T12:31:04.416227+00:00 app[worker.1]: blueprint.start(self) 2016-11-23T12:31:04.416228+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/celery/bootsteps.py", line 123, in start 2016-11-23T12:31:04.416228+00:00 app[worker.1]: step.start(parent) 2016-11-23T12:31:04.416229+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/celery/worker/consumer.py", line 884, in start 2016-11-23T12:31:04.416230+00:00 app[worker.1]: c.loop(*c.loop_args()) 2016-11-23T12:31:04.416230+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/celery/worker/loops.py", line 76, in asynloop 2016-11-23T12:31:04.416232+00:00 app[worker.1]: next(loop) 2016-11-23T12:31:04.416233+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/kombu/async/hub.py", line 279, in create_loop 2016-11-23T12:31:04.416234+00:00 app[worker.1]: item() 2016-11-23T12:31:04.416235+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/amqp/utils.py", line 42, in __call__ 2016-11-23T12:31:04.416236+00:00 app[worker.1]: self.set_error_state(exc) 2016-11-23T12:31:04.416236+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/amqp/utils.py", line 39, in __call__ 2016-11-23T12:31:04.416238+00:00 app[worker.1]: **dict(self.kwargs, **kwargs) if self.kwargs else kwargs 2016-11-23T12:31:04.416239+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/kombu/connection.py", line 288, in drain_events 2016-11-23T12:31:04.416240+00:00 app[worker.1]: return self.transport.drain_events(self.connection, **kwargs) 2016-11-23T12:31:04.416241+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/kombu/transport/pyamqp.py", line 95, in drain_events 2016-11-23T12:31:04.416242+00:00 app[worker.1]: return connection.drain_events(**kwargs) 2016-11-23T12:31:04.416242+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/amqp/connection.py", line 303, in drain_events 2016-11-23T12:31:04.416243+00:00 app[worker.1]: chanmap, None, timeout=timeout, 2016-11-23T12:31:04.416244+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/amqp/connection.py", line 366, in _wait_multiple 2016-11-23T12:31:04.416244+00:00 app[worker.1]: channel, method_sig, args, content = read_timeout(timeout) 2016-11-23T12:31:04.416245+00:00 app[worker.1]: File "/app/.heroku/python/lib/python2.7/site-packages/amqp/connection.py", line 330, in … -
Building user area and site admin - Django - CMS
I am a begginer with Django. I read a book and then I practiced building a real estate project which is working fine. Now I am going to create the admin area, for example, for the site editor to post articles, set posts as paid, edit layout texts ... I used Django 1.9.10 to build the project. I have been reading and looks like I will need do use Django CSM. Do I have to start a new project or is it possible to change my Django project using django cms? Thank you -
Can't get data out of serialized python object in JS/jQuery
It's continuation of that issue Internal error on AJAX call to a Django view (restframework endpoint) which was server side. Now there is frontend problem. (is_taken is replaced by notifications) $.ajax({ url: '/notify/', type:'GET', dataType: '', success: function (data) { if (data.notifications) { console.log(data.notifiications[1].fields); } } }); Get the following error in console: TypeError: undefined is not an object (evaluating 'data.notifications') On server side everything is correct, and I get whatever data I need. I supposed that I need to parse it first but when I'm trying to parse, it's already an object. Otherwise when I am trying to get something out 'TypeError: undefined is not an object'. I know, that now the structure must be like this -
How to send data about boolean field from template to django views by jQuery?
is there any possibility to send form values from template to db by jQuery? I want to change boolean value in checkbox and save it in model and sent this information by jQuery to view. In my template I've got this: <form id="foodForm" action="{% url 'foods:choose_diet' %}" method="post" role="form"> <div id="green-check" class="checkbox"> <input id="green_check" {% if diet.is_green %} checked {% endif %} type="checkbox" data-symbol="green-check"/> Diet choose is_green is a boolean field in Diet model with default = False. After check the checkbox it change on True, but how can do this in views? -
Create mongo db collection from csv in django
I have a situation here, I have to create mongodb collection in django by reading some csv. What will be the best possible solution for this? If you have knowledge of building tables/collections so that could be integrated with django-orm easily, please help me out here. -
read body form request in Django
I have a request url http://my_ip:8080 and I have my custom header and body body as {"test":"hello"} and I can't read body of the POST request. and my views module as, my views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.utils.decorators import method_decorator from django.db import connection import json import re from hinduja.models import Register # Register API for Hinduja @method_decorator(csrf_exempt) def hinduja_register(req): agent = is_valid_agent(req) if agent["result"] == True: try: body = get_body(req) except Exception as e: print("Exception as " + str(e)) json_data = {"result":"test"} else: json_data = error_message('invalid_client') return response_to_client(json_data) def is_valid_agent(req): regex_http_ = re.compile(r'^HTTP_.+$') regex_content_type = re.compile(r'^CONTENT_TYPE$') regex_content_length = re.compile(r'^CONTENT_LENGTH$') request_header = {} agent = {} for header in req.META: if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header): request_header[header] = req.META[header] try: user_agent = request_header['HTTP_USER_AGENT'] if user_agent == 'XXX': agent["result"] = True agent["user_agent"] = user_agent except Exception as e: agent["result"] = False return agent # Get the request body def get_body(req): body_unicode = req.body.decode('utf-8') body = json.loads(body_unicode) return body; # Return error response def error_message(message): return {"result":"error", "message": message} # Return to success response to client def response_to_client(json_data): data = json.dumps(json_data) return HttpResponse(data, content_type='application/json') while calling body_unicode = req.body.decode('utf-8') I got timeout error … -
Set Textarea size for all Textfields in ModelForm
I have a model with tons of fields, some of which are Textarea fields. All of the textare fields should have a certain size (which differs from the default). I could set them all using the widget dictionary in the Meta class, but then i'd have to set them one by one, which seems unnecessary redundant. Is there any better way to solve this? -
How to get the count of the many-to-many keys through a reverse relationship?
I hope I can get your advice on this. If I have a Pizza model with a many-to-many relationship to topping, I can easily get the count of the toppings on the pizza. # models.py class Pizza(models.Model): toppings = models.ManyToManyField(Topping) class Topping(models.Model): name = models.CharField(max_length=255, null=True, blank=True) # admin.py @admin.register(Pizza) class PizzaAdmin(admin.ModelAdmin): list_display = ['topping_count'] def topping_count(self, pizza): return pizza.toppings.count() However, if I move the many-to-many forward relationship to Topping, this all breaks. # models.py class Pizza(models.Model): pass class Topping(models.Model): pizzas = models.ManyToManyField(Pizza) How can I update topping_count in PizzaAdmin so I'm able to get the toppings count via the reverse relationship? Thank you. -
Django template and views
Hi I've placed a download link button in results.html as below filename = "support_automation_app//services//root_cause_analyser//NDS_AO//CC_LOGS//logs.txt" log File &nbsp&nbsp I need to download a log file which is in the below path while running the local server(127.0.0.1:8000) support_automation_app//services//root_cause_analyser//NDS_AO//CC_LOGS When I click Download it didn't download anything. -
Issues with view_name in HyperlinkedRelatedField DRF
In DRF to use HyperlinkedRelatedField you need to provide view_name as argument which normally is {model_name}-detail , if you are using standard routers. But what if you are not using standard routers, means I have defined custom routers so How this view name will work in that case ? My urls looks like this : # venue routers venue_detail = venues.VenueViewSet.as_view({ 'get': 'retrieve', }) venue_list = venues.VenueViewSet.as_view({ 'get': 'list', 'post': 'add_venue' }) urlpatterns = [ # venue urls url(r'^organization/(?P<organization_id>[0-9]+)/venue/$', venue_list, name='venue-list'), url(r'^organization/(?P<organization_id>[0-9]+)/venue/$', venue_list, name='venue-add'), url(r'^organization/(?P<organization_id>[0-9]+)/venue/(?P<pk>[0-9]+)/$', venue_detail, name='venue-detail'), ] Serializer : class MemberSerializer(serializers.HyperlinkedModelSerializer): venue = serializers.HyperlinkedRelatedField(queryset=Venue.objects.all(), view_name='venue-detail') class Meta: model = members.Members fields = ['id', 'venue', 'extra_info']