Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Composition pattern in database design (django model)
I have two concept but could not choose the better one. Let's assume that: Component - class, which can have children and parents Leaf - class, which can have only parents First is the concept, where I have two class for representing parent -> child relationship. One for the Component-Leaf relation and second for Component-Component relation: class Leaf(models.Model): name = models.CharField(max_length=30) #other fields ... class Component(models.Model): name = models.CharField(max_length=30) #other fields ... class ComponentLeafMap(models.Model): parent = models.ForeignKey( Component, on_delete=models.CASCADE, related_name="leaves" ) child = models.ForeignKey( Leaf, on_delete=models.CASCADE, ) amount = models.IntegerField() class ComponentComponentMap(models.Model): parent = models.ForeignKey( Component, on_delete=models.CASCADE, related_name="components" ) child = models.ForeignKey( Component, on_delete=models.CASCADE, ) amount = models.IntegerField() Second is the concept, where I have base class for both Component and Leaf class and one class for representing parent -> child relationship: class Element(models.Model): name = models.CharField(max_length=30) is_component = models.BooleanField() def __init__(self, *args, **kwargs): super(Element, self).__init__(*args, **kwargs) if not self.pk and not self.is_component: self.is_component = self.IS_COMPONENT class Leaf(Element): IS_COMPONENT = False #other fields ... class Component(Element): IS_COMPONENT = True #other fields ... class ComponentRelationship(models.Model): parent = models.ForeignKey( Component, on_delete=models.CASCADE, related_name="relationship" ) child = models.ForeignKey( Element, on_delete=models.CASCADE, ) amount = models.IntegerField() Which concept is better for further development. -
Django template - Strange behavior in select drop-down
I'm working on two linked form fields (Class and Students) where the user selects a class from the drop-down menu and then the students form field updates with the corresponding list of students. I have it all working with the AJAX logic, except...except...I have run into some strange behavior when trying to apply the selected attribute to the <option> tags. views.py def load_students(request): classid = request.GET.get('classid') contractid = request.GET.get('contractid') # Lookup students for given class students = Student.objects.getclass(classid=classid) if(contractid): # Generate list of students associated with this contract contract_party_list = [] contract_parties = ContractParty.objects.get_contract_parties( contractid=contractid ) for mycontractparty in contract_parties: contract_party_list.append(mycontractparty.partyuserid) # Generate new student list (with appended contract user info) student_list = [] for mystudent in students: # Set flag to determine whether student is part of contract if(mystudent.studentuserid in contract_party_list): selectedFlag = True else: selectedFlag = False # Add updated student info to new student list student_list.append( { 'studentuserid':mystudent.studentuserid, 'firstname':mystudent.firstname, 'lastname':mystudent.lastname, 'selectedFlag': selectedFlag } ) students = student_list return render(request, 'dropdown_ajax.html', {'students': students}) dropdown_ajax.html {% if students %} {% for student in students %} <option value="{{ student.studentuserid }}" {% if student.selectedFlag %} selected="selected"{% endif %} > {{ student.firstname }} {{ student.lastname }} </option> {% endfor %} {% endif … -
Django Populating SQLite3 database from a pandas df within a python script
This question is similar to: Populating a SQLite3 database from a .txt file with Python but my goal is different since I want to populate the database from a pandas dataframe rather than a text file. My goal is to take an XML dump (StackExchange data dump) and populate my database based on some of the data contained in it. I started by using xml.etree.ElementTree to parse the file, then I pulled the data into a pandas data frame for easy indexing. I need to iterate through the data frame to check for conditions on the questions, make some modifications on fields, and then populate the fields in my question model based on that. Here is my question model: class Question(models.Model, HitCountMixin): """Model class to contain every question in the forum""" title = models.CharField(max_length=200, blank=False) description = MarkdownxField() pub_date = models.DateTimeField('date published', auto_now_add=True) tags = TaggableManager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) closed = models.BooleanField(default=False) positive_votes = models.IntegerField(default=0) negative_votes = models.IntegerField(default=0) total_points = models.IntegerField(default=0) I know that I can start the django shell as follows: python manage.py shell And that I need to do something as follows to create the objects: from your_app.models import Question # If you're using different field names, … -
Adding comment system to Django blog-like app
I am trying to add a comment system with the threadedcomments package. The code to which I am trying to add the package is below, where it says "My Code". I have read the threadedcomments documentation and Django comment documentation, but I'm having difficulty figuring out exactly how to implement it. My attempt is included in the code (post_create.html). The product works like this (not exactly like a blog): There's a book list. On each book item is a form. This form saves a post and makes it related to this particular book. When you click a book item (DetailView), you see a list of posts, all related to this book item. Now I would like to post a comment on each post. I'd really appreciate any help. Right now, when I run it as it is below, I get this error message: 'QuerySet' object has no attribute '_meta' Thank you! My code: (only relevant parts) views.py: class BookList(ListView): model = Book template_name='books/books.html' class PostForm(ModelForm): class Meta: model = Post fields = ['post'] widgets = { 'post': forms.Textarea() } def get_context_data(self, **kwargs): context = super(BookList, self).get_context_data(**kwargs) context['form'] = BookList.PostForm return context def post(self, request, *args, **kwargs): form = BookList.PostForm(request.POST) if … -
Handle users' uploaded images in Django
what I am trying to do is have a website where users post different topics and pictures as well with the topics. How can I get each topic display only the pictures that belong to this topic. I've tried many things but I am really stuck now. This is the way I am trying to do it now, my view probably looks messy, just not sure if request.FILES should be there or should write another method and my html file is not full but whatever I've tried I got typeerror: One positional argument topic_id missing...Basically be very grateful to any directions This is my view and html, image is a foreignkey to topic if it matters at all enter image description here enter image description here -
django; Is there way to combine the result of filtering objects
I'm new to Django and I'm filtering an Object but maybe I'm using dumb way. What I want to do is to get object named Message if the sender and receiver match. I'm creating a chat-like page. Currently 'views.py' is like this, def message(request, user_id): '''Direct message between users''' #Get an user that the user is sending messages to someone = CustomUser.objects.get(id=user_id) #Get past messages past_messages = Message.objects.filter(someone=someone, user=request.user) models.py is like this class Message(models.Model): text = models.TextField() created = models.DateTimeField(auto_now_add=True) #Has a relationship with the user user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='myself') #Has a relationship with the someone who the user is talking to someone = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='someone') But for this way, I can get only messages I sent and cannot get messages the user I'm chatting sent to me. So I'm wondering if there's a way to combine the result of filtering objects, basically I want to get both messages the user send to someone and the ones someone send to the user and order them by date. But I didn't come up with a good way to do it. Anyone who can give me tips? -
saving authentication token in cookie (Django Rest Framework + React)
So, as the title says I am using Django Rest Framework, combined with React. I am authentication my user by using token authentication. Now I am walking up against the problem that when I reload a page (F5 key, that effect) all the state is gone, and so I can't save the token in such cases. Now I thought about storing the token in a cookie, but that doesn't seem very safe. There are more questions like this, but no answer that really explains how much of a security risk this is. I figure it is quite high, since having the token seems to be enough to authenticate as someone to the backend. So, my question is: is my assumption true, that it is not safe to store my authentication token in a cookie. Note: I am thinking about switching to session based authentication, but I'd rather safe me the work and keep token authentication. -
Error while removing a div with a particular id using BeautifulSoup
I am trying to remove a div with a particular id using BeautifulSoup. Code snippet: from django import template from bs4 import BeautifulSoup register = template.Library() @register.filter(name='reset_html_styles') def reset_html_styles(value): # value = '<div class="test"><div dir="ltr" id="divRplyFwdMsg"><p>Some paragraph</p></div></div>' soup = BeautifulSoup(value, 'html5lib') soup.find('div', id='divRplyFwdMsg').decompose() return str(soup) which is giving me this error output: Error: 'NoneType' object has no attribute 'decompose' I faced no problem while removing divs using class names. I'm using python 3.6.5, django 2.0 and beautifulsoup4 4.6.0 version. -
django-oauth-toolkit; Django Rest Framework - Authentication credentials were not provided
My question is related to this one and this one but for some significant differences: for the first reference: I use django-oauth-toolkit although unlike the second reference, the user MUST be authenticated as this is not a registering endpoint but an upload one. I have successfully implemented other endpoints within the same application with the same setup and it works appropriately. For example: class projectsView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(owner=self.request.user) and it's model and serializer and urls works as expected. However this one: class uploadView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = FileUpload.objects.all() parser_classes = (MultiPartParser, FormParser,) #(FileUploadParser,) serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): print(request.data['file']) return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(owner=self.request.user, project_id=self.kwargs['pk'], file=self.request.data['file']) Does not as it returns {"detail":"Authentication credentials were not provided."} with code 401. There is the minor detail that the "pk" parameter from the url references explicitly the corresponding project id as from it's url instruction: path('projects/<uuid:pk>/upload/', views.uploadView.as_view(), name='upload'),. But apart from that, as far as I can tell, the only difference is the parser_classes. I use curl to test locally … -
No Module Named 'django_python3_ldap'
I would like to authenticate users using an Active Directory. In order to support this functionality in my project, I am using the framework 'django-python3-ldap'. However, I am receiving the error ModuleNotFoundError: No module named 'django_python3_ldap'. If you need anymore information, please let me know. global_settings.py AUTHENTICATION_BACKENDS = ['django_python3_ldap.auth.LDAPBackend'] setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'django_python3_ldap', ] # Authentication Backend AUTHENTICATION_BACKENDS = ('django_python3_ldap.auth.LDAPBackend',) # Django-Python3-LDAP Authentication LDAP_AUTH_URL = "ldap://<my_domain>.com:389" LDAP_AUTH_SEARCH_BASE = "ou=people,dc=<my_domain>,dc=com" LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" -
Associate addditional value to a manytomanyfield
I have 2 models book and favorite class Book(models.Model): title = models.CharField(max_length=200) class Favorite(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Book, related_name='favorited_by') Here a user has its own sets of favorite books. I want to associate an additional variable to each selected favorite book but how can this be done? -
NoReverseMatch at /admin/ error after upgrading Django
After I upgraded my Django project from 1.8 to 2.0, I try to log into the admin page, and receive this error message. I am able to see the login page, other links of the admin like "http://159.203.172.178/admin/QI/page/", but I can't see the first page only.enter image description here I definitely included too many code here because I really don't now where the problem is. Great thanks beforehand. urls.py for admin: from django.conf.urls import * from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required from . import views from django.urls import path,re_path,reverse,include app_name="QI" urlpatterns = [ path('admin/', admin.site.urls), ] settings.py: import os from .settings_secret import * BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'import_export', 'xml_tool', 'haystack', 'QI', ) MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',) ROOT_URLCONF = 'QI.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', The review_transcription_lists that is included in this html file: {% extends 'admin/base_site.html' %} {% load staticfiles %} {% block extrastyle %} <link rel="stylesheet" href="{% … -
custom margin css not doing anything
Basically I have this code in the style brackets in the head of my header.html file. .margin-lol { margin-top: 500px !important; } and then i have something like this in my html class: <ul class='margin-lol'> <i class="fa fa-spotify icon-1 d-flex justify-content-center" aria-hidden="true"></i> <a class="btn btn-outline-white mb-5" href="https://open.spotify.com/artist/5ADZ1KqGgl7gP0lQAhbVKN">Spotify</a> </ul> the margin-lol as the class type is not giving me a 500 pixel top margin. Nothing happens. I need it in the style brackets because i want to use media queries so i can't just put it in the html itself. I've tried moving the class around to different subsections like div and whatever but nothing changes. Any Help? BTW i am using mdbootstrap css and javascript stylesheets -
Django Desing Model : Item/Inventory/User
I would like to ask some advice on Modeling a specif model behavior. Basically I have model Item . It´s describes the name and description of an item. I have a inventory, wich shoudl hold a "List" of items, consedering the quantity of each item should be specified in the invetory. Each User should have one unique inventory. Here´s What I´m trying to do. class User(models.Model): name = models.CharField(max_length=100) invetory =models.ForeignKey(inventory,on_delete=models.CASCADE) class item(models.Model): name =models.CharField(max_length=40) description = models.TextField(max_length=200) value = models.FloatField() class inventory(models.Model): ? I´m not sure if this is the right aproach. -
Upload multiple images in Django Admin
models.py class Video(models.Model): title = models.CharField(max_length=100, blank=True, default='') details = models.TextField() class VideoDetails(models.Model): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='videos') images = models.ImageField(upload_to='images/video/%Y/%m/%d') serializers.py class VideoDetailsSerializer(serializers.ModelSerializer): class Meta: model = VideoDetails fields = '__all__' class VideoSerializer(serializers.ModelSerializer): class Meta: model = Video fields = '__all__' admin.py class VideoDetailsInline(admin.TabularInline): model = VideoDetails class VideoAdmin(admin.ModelAdmin): inlines = [VideoDetailsInline] admin.site.register(Video, VideoAdmin) As shown above, I uploaded 3 images for video 2, however, in my Video view I didn't get the urls of those images. views.py class VideoList(viewsets.ModelViewSet): serializer_class = VideoSerializer queryset = Video.objects.all() How can I attach those image url in VideoDetail to the queryset of Video? Need your help... -
What is the best way to fetch price data daily with django?
The Problem I want to get price data from a foreign API. Afterward, I save the data in a JSON file and want to create Price Objects in my database. I don't know what the best approach is to set this task up so that it runs daily. What I've Tried I've tried Django-background-tasks but I feel like that makes this simple task too complicated. I don't need all the stuff that Django-background-tasks provides. I just want to fetch data and if it worked I want to write something like "success" in my special log file. If it didn't work I just write "failure" or something similar. I don't want to use celery as I don't want to look into celery for such a simple task. I was thinking that I could maybe set up a stand-alone python file which fetches the data and saves it to the database. Then I use a cronjob to execute it daily. However, I'm not sure if that's the best way to do it. What is the easiest and the most uncomplicated way to solve this problem? - I searched for similar questions but didn't find any that suited my problem. If it's a … -
Integrity Error at /some-path/ . duplicate key value violated unique constraint
My database is presently Empty Empty Admin panel Pic But When i try to create some object I get following error. Error Picture I think the problem is with sequence . I searched many solutions on Internet But none of the answer works. The table and sequence is : Table name and Sequence name When I do select all query on database. 0 rows are returned. Output of Select all query My Sequence return following output. Sequence Output Can Anyone help please . This problem came after is flushed the database and tried to start new db with migrations. This problem also comes in Another model as follows. **Iknow Its not a good r in scenario. -
Trying to authenticate using ldap using django-auth-ldap
I am making an intranet app and I'm trying to authenticate by exclusively using an AD Proxy server. My thinking is the best way to accomplish this in my Django web app is to use django-auth-ldap. This is how I set up my ldap in settings: AUTHENITCATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', ] AUTH_LDAP_START_TLS = True AUTH_LDAP_SERVER_URI = "ldap://(DB)" AUTH_LDAP_BIND_DN = "(Service Account DN)" AUTH_LDAP_BIND_PASSWORD = "(Service Account Password)" AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=User-Groups,DC=(Database Name),DC=global",ldap.SCOPE_SUBTREE, "(&(objectClass=user)(mail=%(user)s))") AUTH_LDAP_USER_ATTR_MAP = {"email":"mail"} I am attempting to sign in to the service account in the settings and then query the database for all of the users in the DB. I'm not sure how authentication works from here. I currently have the built-in login authentication plugged into my application and I know that alone doesn't pull from the LDAP info because I attempted to login using an account from this DB and it didn't work. Where am I supposed to go from here? How do I plug the ldap into my project in a way where a user from this DB can be authenticated and I will be able to pull their email for later use in my website? I am using Python 2.7, Django 1.11, ubuntu 14 server, … -
django how to know if new items are added to manytomanyfield
I am adding items to m2m using add() method but after adding items, how can I know whether any new items added or not, for better understanding have a look at my code cart.products.add(*cart_obj.products.all()) cart.messages = 'A' cart.save() cart_obj.delete() cart_obj = cart what I want is cart.messages = 'A' will only execute when new items added to cart, is there any builtin method for this, if not then how can I do this. -
django server is not working currectly
what is the problem in this code, I am adding this code in the setting.py file in Django framework and it's not working properly # pages_project/settings.py TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], ... }, ] (unix-9PXH2taC) unix@unix:~/Desktop/pages$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/unix/.local/share/virtualenvs/unix-9PXH2taC/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/unix/.local/share/virtualenvs/unix-9PXH2taC/lib/python3.5/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/home/unix/.local/share/virtualenvs/unix-9PXH2taC/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/unix/.local/share/virtualenvs/unix-9PXH2taC/lib/python3.5/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/unix/.local/share/virt`enter code here`ualenvs/unix-9PXH2taC/lib/python3.5/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/unix/.local/share/virtualenvs/unix-9PXH2taC/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 661, in exec_module File "<frozen importlib._bootstrap_external>", line 767, in get_code File "<frozen importlib._bootstrap_external>", line 727, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/unix/Desktop/pages/pages_project/settings.py", line 65 'DIRS': [os.path.join(BASE_DIR, 'templates')], ^ SyntaxError: invalid syntax -
Apache mod_wsgi, www-data user is creating image file in directory with -rw------- when uploading with mobile
Apache mod_wsgi, www-data user is creating image file in directory with -rw------- when uploading with mobile -rw------- 1 ubuntu www-data 4691970 Jul 2 17:25 IMG_20180427_082303.jpg but when i'm trying with desktop browser it is being creating -rw-rw-r--+ 1 ubuntu www-data 34081 Jul 2 17:29 001-2bd33965-e569-4f61-9b1d-53d40c325146.jpg -
Cannot import celery on Heroku
When I run "heroku local", I am able to see that celery tasks are being run in the window. However, when I try to deploy my code to Heroku, I keep getting the error that the module "celery" cannot be found. I have celery listed in my requirements.txt file. Also, I have named my files in a way that should avoid naming conflicts. Project structure invmvp --__init.py__ --celeryapp.py --settings.py --urls.py --wsgi.py Procfile worker: celery worker -A invmvp --app=invmvp.celeryapp:app __init__.py from __future__ import absolute_import, unicode_literals __all__ = ('celery_app') celeryapp.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'invmvp.settings') app = Celery('invmvp') app.conf.update(BROKER_URL=os.environ["REDIS_URL"], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Output when I try to push to heroku Counting objects: 88, done. Delta compression using up to 4 threads. Compressing objects: 100% (83/83), done. Writing objects: 100% (88/88), 14.26 KiB | 3.56 MiB/s, done. Total 88 (delta 53), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: Skipping installation, as Pipfile.lock hasn't changed since last deploy. remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) … -
DuplicatePlaceholder warning
I was trying to execute a build and ended up with this error. Could someone tell what this error is all about and how we can fix this ? /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "button_get_started" %} in template static_pages/product_personal.html. web_1 | DuplicatePlaceholderWarning) web_1 | web_1 | /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "button_get_rates" %} in template static_pages/product_personal.html. web_1 | DuplicatePlaceholderWarning) web_1 | web_1 | /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "button_get_pricing" %} in template static_pages/product_personal.html. web_1 | DuplicatePlaceholderWarning) web_1 | web_1 | /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "button_pricing" %} in template static_pages/product_business.html. web_1 | DuplicatePlaceholderWarning) web_1 | web_1 | /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "intro_stat_1" %} in template homepage.html. web_1 | DuplicatePlaceholderWarning) web_1 | web_1 | /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "intro_stat_2" %} in template homepage.html. web_1 | DuplicatePlaceholderWarning) web_1 | web_1 | /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "intro_stat_3" %} in template homepage.html. web_1 | DuplicatePlaceholderWarning) web_1 | /usr/local/lib/python2.7/site-packages/cms/utils/placeholder.py:241: DuplicatePlaceholderWarning: Duplicate {% placeholder "intro_stat_4" %} in template homepage.html. -
Saving primary key in class based view to another view (django)
I do not know how even find solution for this, but lets start from the begining. These are my models: class Animal(models.Model): SPECIES = ( ("DOG", "DOG"), ("CAT", "CAT"), ) species = models.CharField(max_length=4, choices=SPECIES) name = models.CharField(max_length=20) weight = models.PositiveSmallIntegerField(null=False, blank=False) age = models.PositiveSmallIntegerField(null=False, blank=False) color = models.CharField(max_length=10) isill = models.BooleanField(null=False) isagressive = models.BooleanField(null=False) isadopted = models.BooleanField(null=False) isreturned = models.NullBooleanField() whichbox = models.CharField(max_length=5) photo = models.ImageField(null=True, blank=True) def __str__(self): return self.name class MedicalHistory(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) disease = models.CharField(max_length=100) medicine = models.CharField(max_length=20, null=True, blank=True) therapy = models.CharField(max_length=50) howmuchmed = models.CharField(max_length=50) daterecord = models.DateField def __str__(self): return self.disease and here are my urls: urlpatterns = [ path('', AnimalListView.as_view(template_name='Animals/animals.html'), name='animallist'), path('add/', AddAnimal.as_view(), name='addanimal'), path('edit/<int:pk>/', EditAnimal.as_view(), name='editanimal'), path('detail/<int:pk>/', AnimalDetailView.as_view(template_name='Animals/animaldetail.html'), name='animaldetail'), path('medlist/<int:pk>/', MedhistoryListView.as_view(template_name='Animals/medlist.html'), name='medlist'), ] and my views (only two from all) class AnimalDetailView(DetailView): queryset = Animal.objects.all() def get_object(self): object = super().get_object() object.save() return object context_object_name = 'animal_detail' class MedhistoryListView(ListView): "PLACE FOR CODE" context_object_name = 'medical_history_list' In the MedhistoryListView i would like to show a diseases that animal had. There is the link on AnimalDetailView template to the url with Medhistorylistview. My main problem is how to save primary key from one view to another and choose only these objects with specify animal.pk. … -
“greatest-n-per-group” query in Django 2.0?
Basically, I want to do this but with django 2.0. If I try: Purchases.objects.filter(.....).annotate(my_max=Window( expression=Max('field_of_interest'), partition_by=F('customer') ) ) I get back all the rows but with the my_max property added to each record.