Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import Django QuerySet to python list
I am trying to export my Django QuerySet to a python list but I couldn't achieve it. My data structure: [{'time_stamp': datetime.datetime(2017, 9, 30, 22, 0, 37, tzinfo=<UTC>), 'num': 1}, {'time_stamp': datetime.datetime(2017, 9, 31, 22, 0, 37, tzinfo=<UTC>), 'num': 2}] My attempt is: my_query=MyModell.objects.all().filter(time_stamp__range=('2017-10-01', '2017-10-02')).values('time_stamp').annotate(num_avg=Avg('number')).order_by('time_stamp') data=[i.num_avg for i in my_query] Unfortunately I got this error message when I tried to retrieve the num. AttributeError: 'dict' object has no attribute 'num_avg' My aim is to get a list like this a=[1,2] Thank you in advance! -
Disqus universal code for Django
I try to install disqus in my site, but nothing is displayed on the page. Site url - djaway.net This is my code: views.py def detail(request, slug): url = (reverse('content:detail', args=[slug])) content_info = Post.objects.get(slug = slug) return render(request, 'detail.html', {'content_info':content_info, 'url':url}) template.html <script> var disqus_config = function () { this.page.url = 'djaway.net{{ url }}'; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = '{{ url }}'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'djaway.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> Tag {{ url }} return right links, for example - /content/slug/ -
How can I randomize csrf token for django admin
I've just got vulnerability report that came from pentesters for my Django project. The report says my Django app is vulnerable to the BREACH ATTACK. SSL is active, cookies are flagged as a secure, session cookies are set as a secure. HTTP Compressions closed by the sysadmin it is controlled from the Nginx that I have no access. So gzip is close. Now I want to randomize csrf token for per client-side request for the django admin, especially for the login page. Is there a way to do this in settings.py in a simple way or do I have to write custom admin view? What is the best practice for this issue? -
How to add mouse click event in python nvd3?
I'm beginner to Data visualization in python, I'm trying to plot barchart (multibarchart) using python-nvd3 and django, It's working fine but my requirement is need to add click event to Barchart to get the data if user click the chart.I searched quite a lot but i couldn't found any reference or solution due to lack of documentation.Below i mentioned my code.Thanks in advance! In view.py: from django.shortcuts import render_to_response import random import datetime import time def demo_multibarchart(request): nb_element = 10 xdata = range(nb_element) ydata = [random.randint(1, 10) for i in range(nb_element)] ydata2 = map(lambda x: x * 2, ydata) ydata3 = map(lambda x: x * 3, ydata) ydata4 = map(lambda x: x * 4, ydata) extra_serie = {"tooltip": {"y_start": "There are ", "y_end": " calls"}} chartdata = { 'x': xdata, 'name1': 'series 1', 'y1': ydata, 'extra1': extra_serie, 'name2': 'series 2', 'y2': ydata2, 'extra2': extra_serie, 'name3': 'series 3', 'y3': ydata3, 'extra3': extra_serie, 'name4': 'series 4', 'y4': ydata4, 'extra4': extra_serie } charttype = "multiBarChart" data = { 'charttype': charttype, 'chartdata': chartdata } return render_to_response('multibarchart.html', data) in template page: {% load static %} {% load nvd3_tags %} <head> {% load_chart charttype chartdata "multibarchart_container" %} </head> <body> {% include_container "multibarchart_container" 400 600 %} </body> -
Django: using ConTeXT mkiv to output PDF
i have a small Django app to manage my patients data, and use LaTeX to output reports. It consists un a parent model called Patients and child models Consultation , StressEcho and so on. With LaTex this works without problems def courrier_pdf(request, pk2, pk1): entry = Courrier.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) context = dict({'courrier': entry, 'patient': source}) #buffer = BytesIO() template = get_template('courrier/courrier.tex') rendered_tpl = template.render(context, request).encode('utf-8') #Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r i tried with this view in order to use ConTeXT but without success def courrier_mkiv(request, pk2, pk1): entry = Courrier.objects.get(pk=pk2) cource = Patient.objects.get(pk=pk1) context = dict({'courrier': entry, 'patient': cource}) # buffer = BytesIO() template = get_template('courrier/courrier.mkiv') rendered_tpl = template.render(context, request).encode('utf-8') with tempfile.TemporaryDirectory() as tempdir: process = Popen(['context', '--result', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'textput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r My feeling … -
django pagination can not direct to next page
I want to use pagination to list data from database,but when I click next page button,it shows “local variable 'context' referenced before assignment” I use filter to searching data from database first ,and use "REQUSET.POST" to get the data back。then send the data to another html。I think when I click next page,it will do all these again ,but I don't know how to code it。 Please help me to find out the problem,thank you! Below is my code: view.py from django.template.loader import get_template from django.template import RequestContext from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render,render_to_response from datetime import datetime from .form import DateRangeForm from .models import Post import tkinter.messagebox from tkinter import * from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger # Create your views here. def answer(): showerror("Answer", "Sorry, no answer available") def homepage(request): posts = Post.objects.all() now = datetime.now() context = {'posts':posts,'now':now} return render(request,'jishi.html',context) def showpost(request,times): template=get_template('post.html') ##posts=Post.objects.all().values('customer') posts=Post.objects.filter(pub_date__year=2018) now = datetime.now() html = template.render(locals()) return HttpResponse(html) def foobar(request): date_sel1 = request.POST.get('datetime1',None) date_sel2 = request.POST.get('datetime2',None) if date_sel1!=None: posts = Post.objects.filter(pub_date__range=(date_sel1,date_sel2)).order_by("pub_date","time") paginator = Paginator(posts,6,1) page = request.GET.get('page') try: customer = paginator.page(page) except PageNotAnInteger: customer = paginator.page(1) except EmptyPage: customer = paginator.page(paginator.num_pages) context={'posts':customer} return render(request,'sheet.html',context) html: {% extends 'balance.html' %} … -
django-filter for Boolean
I am a beginner to Django and doing a learning project which is a booking system. Can anyone recommend me an open source django project where I can check the source code for best practices. Thanks in advance When I use the code below, get method gets "on" or "off". How can it be "True"/"False"? Model.py class Mymodel(models.Model): ... is_xxx_approved = models.BooleanField(default=False,blank=False,null=False) is_contracted_by_yy= models.BooleanField(default=False,blank=False,null=False) is_zz_approved = models.BooleanField(default=False,blank=False,null=False) Filter.py class MymodelFilter(django_filters.FilterSet): class Meta: model = Mymodel fields = ['is_xxx_approved', 'is_contracted_by_yy', 'is_zz_approved'] exclude = [ 'name', 'address', 'phone', 'email',] filter_overrides = { models.BooleanField: { 'filter_class': django_filters.BooleanFilter, 'extra': lambda f: { 'widget': forms.CheckboxInput, }, }, } Template <div class="filter_index"> {% with field=filter.form.is_xxx_approved %} {{ field.label_tag }} {{ field }} {% endwith %} </div> <div class="filter_index"> {% with field=filter.form.is_contracted_by_yy %} {{ field.label_tag }} {{ field }} {% endwith %} </div> <div class="filter_index"> {% with field=filter.form.is_zz_approved %} {{ field.label_tag }} {{ field }} {% endwith %} </div> -
Django ORM: List of Foreign Key values
I have a table which has a column which stores a list of values. These values are basically Foreign key values of another table. This is the query I had written in SQL: SELECT COUNT(g.*) AS match_count, TEXT(g.created_at::DATE) AS created_at FROM groups g JOIN users u ON u.username = ANY (g.winner) WHERE g.created_at::DATE >= '2018-01-01' AND g.created_at::DATE <= '2018-01-20' AND g.winnings = 0 AND g.group_type = 'random' AND u.type = 'u' AND g.winner IS NOT NULL GROUP BY g.created_at::DATE I need to migrate this query into Django's ORM. How can I do a join with this array field (winner)? -
string Validation with xlsxwriter python
I am trying to put validations on excel file. I field should only accept characters or character with '_' symbol. The following code is only redistricting user to enter values more than length 10. import xlsxwriter wb = xlsxwriter.Workbook('staff.xlsx') ws = workbook.add_worksheet() ws.data_validation(1, 1, 10, 0, {'validate': 'length', 'input_title': 'Enter value', 'criteria': '<', 'value': firstname_max_length, 'error_message': 'Max Length is {0}'.format(10)}) Help me to validate values that should only except characters. Thanks. -
Custom django user registration
I am doing a user registration function this is viewsenter image description here this is formsenter image description here this is htmlenter image description here I found that if I change the name of the clean_password2 method in the views file to clean_password, I can not get the value of password2 in the form This is the wrong messageenter image description here My English is not very good I hope someone can help me Thank Thank Thank -
ValueError - Invalid literal for int() with base 10: 'add' Error Python 3.6
Here is my urls.py code, from django.contrib import admin from django.urls import path from . import views app_name = 'stories' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<pk>', views.DetailView.as_view(), name='detail'), # path('<story_id>/ratings', views.rating, name='rating'), path('add', views.CreateStory.as_view(), name='add-story'), ] I get above error when click the link, <li><a href="{% url 'stories:add-story' %}">Click me</a></li> I have no idea about this issue. Please help. -
celery + rabbitMQ - Cannot connect to broker
after successfully testing celery with the message broker (rabbitmq) installed locally (BROKER_URL = 'amqp://localhost') in a django app, i'm experiencing issues while connecting to broker: (projenv_py36) ➜ proj_pop_app (dev) celery -A proj worker --app=config.celery:app -l info [config] .> app: celeryProj:0x1068e7cc0 .> transport: amqp://rabbit:**@mq0.stg.eu-west-1.internal.my-company.eu:5672/vhost_proj_pop .> results: rpc:// .> concurrency: 8 (prefork) .> task events: OFF (enable -E to monitor tasks in this worker) [queues] .> celery exchange=celery(direct) key=celery [tasks] . config.celery.debug_task . process_session_task . sum_two_nrs [2018-01-24 11:30:08,197: ERROR/MainProcess] consumer: Cannot connect to amqp://rabbit:**@mq0.stg.eu-west-1.internal.my-company.eu:5672/vhost_proj_pop: [Errno 8] nodename nor servname provided, or not known. Trying again in 2.00 seconds... [2018-01-24 11:30:10,215: ERROR/MainProcess] consumer: Cannot connect to amqp://rabbit:**@mq0.stg.eu-west-1.internal.my-company.eu:5672/vhost_proj_pop: [Errno 8] nodename nor servname provided, or not known. Trying again in 4.00 seconds... note: the BROKER_URL value has been provided to me by my company devops team. I'm new to celery. Is there something that I can check to determine if is a celery configuration issue or if it's the broker not working properly? Thanks -
Django: Deleting query filters with button in template
I have a listview that displays a list of objects ('Speakers') that has a simple filter on top. In the template I've put the following code <form class="col-md-5" method="get"> <div class="input-group"> <select name="type" class="selectpicker" multiple> {% for type in types %} <option><a href="#">{{ type.name }}</a></option> {% endfor %} </select> <span class="input-group-btn"><button class="btn btn-gray" type="submit">Search</button></span> </div> </form> The types are supplied by the 'get_context_data' method from the listview, like so def get_context_data(self, **kwargs): data = super(SpeakerList, self).get_context_data(**kwargs) typelist = [x for x in Type.objects.all()] data['types'] = typelist return data The filters are handles in the 'get_queryset' method like so def get_queryset(self, **kwargs): qs = super(SpeakerList,self).get_queryset().filter(status=STATE_ACTIVE) types = self.request.GET.getlist('type', None) categories = self.request.GET.getlist('category', None) if types: qs = qs.filter(type__in=types) if categories: qs = categories.filter(categories__in=categories) return qs So far, so good. However, I want to display all of the selected filters in the template, with a 'remove' button behind them so users can remove specific filters. The template would then look something like this [ Type select dropdown ] . [ Day-speaker 'X'] . [Weekend-speaker 'X'] Object list Supplying the filters that are used is easy, I've added the following code to the get_context_data types_query = self.request.GET.getlist('type', None) data['types_query'] and used the following … -
DRF query the foreign key value with filter
How to query the foreign key value with filter condition in django rest framework. I'm retrieving the value by DRF StringRelatedField method, but i don't have any idea how to filter while query itself -
Angular JS 1 - Error when add framework
I already use Angular JS 1 in my projects and always works. But I recieved one project that is using python and django and some pages are using angular, the page that I need to work have no angular code, then I put the call for the main script: <script src="/static/angular/1.5.5/angular.min.js"></script> And I get the following error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=public&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.5%2F%24injector%2Fnomod%3Fp0%3Dpublic%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A6%3A412%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A25%3A235%0A%20%20%20%20at%20b%20(http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A24%3A282)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A25%3A20%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A39%3A374%0A%20%20%20%20at%20q%20(http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A7%3A355)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A39%3A222)%0A%20%20%20%20at%20bb%20(http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A43%3A246)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A21%3A19)%0A%20%20%20%20at%20yc%20(http%3A%2F%2Flocalhost%3A8000%2Fstatic%2Fangular%2F1.5.5%2Fangular.min.js%3A21%3A332) Note: And I no created nothing yet, no app.js neither controller.js Thanks for any suggestion -
Apply a function to individual fields in a dynamic formset
I have a Django template which has two formsets. Each form in one of these formsets consists of two select elements. They in turn are populated by different data sets so I have given them each a unique identifying class. Each formset is also dynamic, so it is possible to add or delete forms from the formset (apart from the first form). I am doing this with a relatively simple jQuery script, and when a form is added I give it a class with an increasing number so I can differentiate between the added forms (I have only recently added this as I tried to fix the problem mentioned below). My problem is that I am trying to apply a function to the select elements in the added forms but I can't seem to get my selectors to capture the elements. Previously I had been applying the function globally and then differentiating between the select elements by using the class. However, I ran into problems as there was no way to tell one form from another so when more than one form was added, the function was called twice. So, basically I would appreciate some help in finding the right … -
When I am trying to run django development server (using command line),I get following error traceback:
My system is: Ubuntu16.04. Python version: 3.5.2 Django version: 2.0.2 root@nanlyvm:/home/mydj/mysite# python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fbb791cd1e0> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/mydj/mysite/mysite/urls.py", line 22, in <module> url(r'^blog/',include('blog.urls', namespace='blog', app_name='blog')), TypeError: include() got an unexpected keyword argument … -
Passing field from extended user model to template in Django
I am having an issue passing a field from an extended user model to a template in Django. I defined the extended user fields in a model in a new app called user_management: #user_management/models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class lab_user(models.Model): user = models.OneToOneField(User) personal_order_list_url = models.URLField("Personal order list URL", max_length=255, blank=False, unique=True) abbreviation_code = models.CharField("Abbreviation code", max_length=3, blank=False, unique=True) def save(self, force_insert=False, force_update=False): self.personal_order_list_url = self.personal_order_list_url.lower() self.abbreviation_code = self.abbreviation_code.upper() super(lab_user, self).save(force_insert, force_update) I then registered the new fields in admin.py: #user_management/admin.py from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import lab_user class lab_user_inline(admin.StackedInline): model = lab_user can_delete = False verbose_name_plural = 'Additional Fields' class UserAdmin(BaseUserAdmin): inlines = (lab_user_inline, ) admin.site.unregister(User) admin.site.register(User, UserAdmin) I can see the new fields in "Authentication and Authorization", which I guess means I've done everything "right". When I try to call fields from a template using {{ request.user.x }} where x could be first_name, personal_order_list_url or abbreviation_code, I can retrieve the desired value for first_name and personal_order_list_url, but not for abbreviation_code. If request.user.personal_order_list_url works, request.user.abbreviation_code should work too, shouldn't it? -
Language Option in Django Html
i am developing A web application using (Django ,Html5,css)in pycharm.i want to add language option top of my webpage where three link shown (ENG FI SVK).user can click on of these and page will translate into that language.like this website:https://danskebank.fi .how can i do that...i am very new in django ,trying to learn thanks -
Django : AttributeError: 'str' object has no attribute 'strftime'
This is my code: signals.py from record.models import Record person1Age = record.person1Age person1AgeFormat = person1Age.strftime('%d-%m-%Y') print(person1AgeFormat) Result in Django Console: person1AgeFormat = person1Age.strftime('%d-%m-%Y') AttributeError: 'str' object has no attribute 'strftime' The same code works fine in the python3 shell. This problem only occurs in my Django Signal. Should I import something else specific to Django? -
Django :There is no unique constraint matching given keys for referenced table"
There are countless questions related to this error, but after over a month I've still not been able to solve this problem, since in my setup there is in fact a unique constraint. I have already asked this question before, but the answer was to add a unique field to my model which IS already present. I'm running an older django version, 1.7.11, and circumstances do not allow me to upgrade. I have a Photo class, which contains multiple foreign keys to other classes. class Photo(UserBase): """ Photograph """ scene_category = models.ForeignKey( SceneCategory, related_name='photos', null=True, blank=True) artist = models.ForeignKey( Artist, related_name='photos', null=True, blank=True) gallery = models.ForeignKey( Gallery, related_name='photos', null=True, blank=True) The inheritance for UserBase class UserBase(ModelBase): #: User that created this object user = models.ForeignKey(UserProfile) class Meta: abstract = True ordering = ['-id'] class ModelBase(EmptyModelBase): """ Base class of all models, with an 'added' field """ added = models.DateTimeField(default=now) class Meta: abstract = True ordering = ['-id'] class EmptyModelBase(models.Model): """ Base class of all models, with no fields """ def get_entry_dict(self): return {'id': self.id} def get_entry_attr(self): ct = ContentType.objects.get_for_model(self) return 'data-model="%s/%s" data-id="%s"' % ( ct.app_label, ct.model, self.id) def get_entry_id(self): ct = ContentType.objects.get_for_model(self) return '%s.%s.%s' % (ct.app_label, ct.model, self.id) class Meta: … -
Django url parameters prevent download exported excel file
I have a url like this: " http://localhost:8001/browse/4/766821590082433/" and when i click the button to download excel file my url gets : "http://localhost:8001/browse/4/766821590082433//export/xls/". In my urls.py url(r'export/xls/$', main.export_users_xls, name='export_users_xls') but when I pass any other url params like : "http://localhost:8001/browse/4/766821590082433/?earliest=2018-01-10&latest=2018-01-17" I cant download the excel file and url gets updated to : http://localhost:8001/browse/4/766821590082433/?earliest=2018-01-10&latest=2018-01-17/export/xls/ the error I get is unconverted data remains: /export/xls/ Any idea how to fix this in order to download excel data even when url has parameters. -
Django: get() returned more than one items -- it returned 3
I got an error MultipleObjectsReturned: get() returned more than one items -- it returned 3!. I want edit and update an existing record in the database. Below are my model, views and html code. Model.py import datetime from django.db import models from django.utils import timezone class Purchases(models.Model): bottle = models.CharField(max_length=20) bottle_purchased = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now_add=True) bottle_total= models.CharField(max_length=20) transportation_cost = models.CharField(max_length=20) total_cost = models.CharField(max_length=20) class Meta: verbose_name_plural = 'Purchases' def __str__(self): return self.bottle Views function for editing. Views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from .models import Purchases from .forms import PurchasesForm def purchases(request): purchases = Purchases.objects.order_by('date_added') context = {'purchases': purchases} return render(request, 'ht/purchases.html', context) def edit_purchase(request): entry = get_object_or_404(Purchases) purchase = entry.purchase if request.method != 'POST': # Initial request; pre-fill form with the current entry form = PurchasesForm(instance=entry) else: # POST data submitted; process data. form = PurchasesForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('geo_gas:purchases')) context = {'entry': entry, 'purchases': purchases, 'form': form} return render(request, 'geo_gas/edit_purchase.html', context) edit_purchase.html <form action="{ url 'geo_gas:edit_purchase' %}" method='post'> {% csrf_token %} {{ form.as_p}} <button name="Submit">save changes</button> </form> Attached is the returned error. get() returned more than one items -- it returned 3! enter image description here -
Django rest framework combine/nested serializer
I have 2 table, appointment and schedule. schedule has these field: scheduleid, title, 'starttime', 'endtime', 'date' appointment has these field: id, scheduleid, clinicid, 'time', 'queueNo', 'date' schedule starttime is = appointment time. So is the date When ever a user create a Appointment, it will also create a schedule as u can see on above. I know how to make a nested serializer but what i do not know is. If a schedule hasn't been created, what do i insert the scheduleid in the appointment table. Reason is because, create appointment first, how to create so that in appointment django know how to create a scheduleid for it ? -
Django Admin prefetch not working - duplicating queries ~1000 times
Ive added a prefetch to django admin as I noticed it was running nearly 1000 queries for a model. However the prefetch seems to have had zero effect. as far as I can see the prefetch query is correct? example duplicate: SELECT "sites_sitedata"."id", "sites_sitedata"."location", "sites_sitedata"." ... FROM "sites_sitedata" WHERE "sites_sitedata"."id" = '7' Duplicated 314 times. 0.09126367597049141% 0.24 Sel Expl Connection: default /itapp/itapp/circuits/models.py in __str__(88) return '%s | %s | %s | %s ' % (self.site_data.location, \ there are also duplicates for, circuit providers, and circuit types glancing at a high level admin.py class SiteSubnetsAdmin(admin.ModelAdmin): search_fields = ['site_data','device_data','subnet','subnet_type','vlan_id','peer_desc'] list_display = ('site_data','device_data','subnet','subnet_type','vlan_id','peer_desc') ordering = ('site_data','device_data',) def get_queryset(self, request): queryset = super(SiteSubnetsAdmin, self).get_queryset(request) queryset = SiteSubnets.objects \ .prefetch_related( Prefetch( 'circuit', queryset=Circuits.objects.prefetch_related('site_data').prefetch_related('service_contacts').prefetch_related('circuit_type').prefetch_related('provider'), ), ) \ .prefetch_related('site_data') \ .prefetch_related('device_data') \ .prefetch_related('subnet_type') return queryset admin.site.register(SiteSubnets, SiteSubnetsAdmin) subnets.models class SiteSubnets(models.Model): device_data = models.ForeignKey(DeviceData, verbose_name="Device", \ on_delete=models.PROTECT, blank=True, null=True) site_data = models.ForeignKey(SiteData, verbose_name="Location", \ on_delete=models.PROTECT, blank=True, null=True) subnet = models.GenericIPAddressField(protocol='IPv4', \ verbose_name="Subnet", blank=True, null=True) subnet_type = models.ForeignKey(SubnetTypes, verbose_name="Subnet Type") circuit = models.ForeignKey(Circuits, verbose_name="Link to circuit?", \ on_delete=models.PROTECT, blank=True, null=True) vlan_id = models.IntegerField(verbose_name="Vlan ID", blank=True, null=True) peer_desc = models.IntegerField(verbose_name="Peer description", blank=True, null=True) class Meta: verbose_name = "Site Subnets" verbose_name_plural = "Site Subnets" def __str__(self): if self.device_data != None: return …