Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My link is no responsive after or not generated after using get_url_absolute
The two links are not working despite of the using get_absolute_ur to get the object url in my models. How do i configure the code to make my links responsive PICTUREOF THE SITE IMAGE AND LINKS THAT ARE NOT WORKING MY VIEWS:BELOW from django.shortcuts import render from django.shortcuts import get_object_or_404, render_to_response from .models import Category, Product # from django.template import RequestContext # Create your views here. def index(request): page_title = 'Musical Instruments and Sheet Music for Musicians' return render(request, 'catalog/index.html') def show_category(request, category_slug=None): c = get_object_or_404(Category, slug=category_slug) products = c.product_set.all() page_title = c.name meta_keywords = c.meta_keywords meta_description = c.meta_description return render(request, 'catalog/category.html', {'c': c}) def show_product(request, product_slug=None): p = get_object_or_404(Product, slug=product_slug) categories = p.categories.filter(is_active=True) page_title = p.name meta_keywords = p.meta_keywords meta_description = p.meta_description return render(request, 'catalog/product.html', {'p': p}) MY MODELS:BELOW from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL,created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text='Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'categories' … -
Remove selected item from the inlineadmin interface
I don't know if this can be done in the django rendered admin interface what I want to do is remove item that has been selected from a foreign key field eg --mary --matter --mary-ann --may --mary jane when I select "mary-jane" I want mary jane off the list so it won't be selected twice. eg --mary --matter --mary-ann --may How can this be achieved? the model is like this class Name(models.Model): name = models.CharField(max_length=50) class Test(models.Model): name = models.ForeignKey(Name) -
Django + React Project could not load static files
I am having a Django and React application together in one project folder. Project Structure: project/ frontend/ react app src/ components/ App.jsx index.js static/ frondend/ main.js templates/ frondend/ index.html migrations/ init.py admin.py apps.py models.py test.py urls.py views.py project/ migrations/ init.py admin.py apps.py models.py test.py urls.py views.py > nodemodules/ .bablerc manage.py .webpack.config.js package-lock.json package.json index.html: <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css"> <title>Django DRF - React : Quickstart - </title> </head> <body> <section> <div> <div id="root"> <!-- React --> </div> </div> </section> </body> {% load static %} <script src="{% static 'js/bootstrap.js' %}"></script> </html> My .bablerc file: { "presets": [ "es2015", "stage-1", "react" ], "plugins": [ "transform-runtime", "transform-decorators-legacy", "transform-class-properties", "transform-object-rest-spread", "react-hot-loader/babel", "typecheck", "transform-es2015-modules-commonjs", "add-module-exports", "import-asserts" ] } my webpack.config.js: const HtmlWebPackPlugin = require("html-webpack-plugin"); module.exports = { module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader", query: { presets: ["@babel/preset-env", "@babel/preset-react"] } }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true } } ] } ] }, plugins: [ new HtmlWebPackPlugin({ template: "./frontend/templates/frontend/index.html", filename: "./index.html" }) ] }; The problem here is that my static files won't get loaded with {% load static %} statement. Is there … -
django: how to recursively get the modified date from a model and its related models and their related models
I have the following models: I have Four Main models which dont have any forieng key fields: class Main1(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Main2(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Main3(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Main4(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I have the following models which depend on Foriengn fields: Class Related1(models.Model) name = models.CharField(max_length=200) main4 = models.ForeignKey(Main4,on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) Class Related2(models.Model) name = models.CharField(max_length=200) main3 = models.ForeignKey(Main3,on_delete=models.CASCADE) related1 = models.ForeignKey(Related1,on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) Class Related3(models.Model) name = models.CharField(max_length=200) main2 = models.ForeignKey(Main2,on_delete=models.CASCADE) related2 = models.ForeignKey(Related2,on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) Class Related4(models.Model) name = models.CharField(max_length=200) main1 = models.ForeignKey(Main1,on_delete=models.CASCADE) related3 = models.ForeignKey(Related3,on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) If see that Main1 is related to Related4 Model, but Related4 has also another foriegn key Related3 I am trying to find out the modified date of all the Models related to Main1 for a given … -
How do I set form items order in a Django form?
I want to set my own form order in a Django form but when i run my app, every time i got a new form ordering. Here is the code : from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): class Meta(): fields =['username', 'email', 'password1', 'password2'] model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["password1"].label = "Your Password" self.fields["password2"].label = "Repeat Your Password" And the user model is : from django.db import models from django.contrib.auth.models import User, PermissionsMixin # Create your models here. class UserModel(User,PermissionsMixin): def __str__(self): return "@{}".format(self.username) What can I do in this situation? thanks in advance -
Displaying an image from string in django template
To give you an idea of my starting point: I have a set of forms with a label and checkbox. Some of my labels are supposed to display pictures, but not all. The pictures when they should be displayed are never at the same place with regards to the label text (ie sometimes the picture should be displayed in the middle of the label, sometimes at the beginning, end...). So the only way I could think of to address this problem was to have in my label at some place, something like <img src="{{ MEDIA_URL }}/sources/1/2.jpg" height=300px/> within the text. The problem is that it is considered as a string and not as an html tag. Would you have any idea of to address this issue? I'm currently run out of ideas. Thank you very much. Soso :) -
Manually create many-to-many relations - error on setting the relation
I have 2 models: class Item(models.Model): categories = models.ManyToManyField(Category, related_name='category_products') name = models.CharField(max_length=255) class Category(models.Model): name = models.CharField(max_length=255) I want to push some predefined data to the products: product = Product.objects.create(id=pk,name=name, categories=category.id) I get the following error: Direct assignment to the forward side of a many-to-many set is prohibited. -
django channles channels.exceptions.Channels Full
i am pretty new in django-channels and python, i make a demo using django-channels and django to send data from backend to front activly. the code in consumers.py as below: websocket_clients = [] class WebsocketConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): """ initial a new thread when new websocket instance initialed. """ super(WebsocketConsumer, self).__init__(self) self.index_websocket = GendataThread() async def connect(self): self.index_websocket.channels_name = self.channel_name print('channel_name', self.channel_name) self.index_websocket.start() websocket_clients.append(self.channel_name) await self.accept() async def disconnect(self, close_code): """disconnected a websocket instance, and stop the thread.""" self.index_websocket.stop() time.sleep(2) index = websocket_clients.index(self.channel_name) websocket_clients.pop(index) async def receive(self, text_data): """receive message from connected client, wouldn't work in this project.""" text_data = '{"message": "%s"}' % (text_data) text_data_json = json.loads(text_data) async def chat_message(self, event): """send message to websocket.""" print('event', event) await self.send(text_data=json.dumps( {'message': event['message']})) def websocket_send_data(data, channel_name): """ send data to front in websocket protocol, :param data: data which will be sent, :param channel_name: a symbol to mark connected client. :return: """ channel_layer = get_channel_layer() event = { "type": "chat.message", "message": data } async_to_sync(channel_layer.send)(channel_name, event) as you can see, i make a function name: websocket_send_data(data, channel_name),which i can call in GendataThread() as below: class GendataThread(threading.Thread): """new thread thread for getting data from cluster, and send to front with websocket protocol. """ def … -
Inline formset factory in django (2.0.8) generic View
I am trying to create a inline formset factory so that when i create the Post at the same time i can create a PostVocab which has a ForeignKey associated with it. I watched couple of tutorials but got stucked on this problem.. When saving it shows me : ValueError: save() prohibited to prevent data loss due to unsaved related object 'post'. My Models: from django.db import models from PIL import Image from django.urls import reverse from ckeditor.fields import RichTextField from django.db.models.signals import pre_save from django.utils.text import slugify from django.conf import settings # Create your models here. def upload_location(instance, filename): filename = instance.title return "blog/%s.jpg" %(filename) class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) pdf = models.FileField(blank=True, null=True) audio_file = models.FileField(blank=True, null=True) author = models.CharField(max_length=20) added = models.DateTimeField(auto_now=False,auto_now_add=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) post = RichTextField(blank=True, null=True) picture = models.ImageField(upload_to=upload_location, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail' , kwargs={'slug':self.slug}) def save(self, **kwargs): if self.picture: super(Post, self).save() mywidth = 440 image = Image.open(self.picture) wpercent = (mywidth / float(image.size[0])) hsize = int((float(image.size[1]) * float(wpercent))) image = image.resize((mywidth, hsize), Image.ANTIALIAS) image.save(self.picture.path) from django.db import models from blog.models import Post # Create your models here. … -
django filter based on selected choice in Integer field with choices
models.py: class User(AbstractUser): is_client = models.BooleanField(default=False) is_trainer = models.BooleanField(default=False) username = models.CharField('username', max_length=150, unique=True) email = models.EmailField(unique=True) hub = models.ForeignKey(Hub, on_delete=models.CASCADE,blank=True, null=True) USER_POSITIONS = ((0, 'Not a member'), (1, 'Member'), (2, 'Excom'), (3, 'Leader')) hub_position = models.IntegerField(default=0, choices=USER_POSITIONS) mentor = models.ForeignKey('self' ,on_delete=models.CASCADE, blank=True,null=True) terms = models.BooleanField(blank=True,default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','terms'] def get_absolute_url(self): return reverse('student:dashboard', kwargs={'pk': self.pk}) I have an integer field hub_position in the User model which has 4 choices and it creates a dropdown list in the admin panel.I want to filter all users who have selected a particular option from the dropdown list. For example, i want to filter all users who are Members .How to implement this? -
django.db.utils.ConnectionDoesNotExist: The connection default doesn't exist
i'm trying to connect the mongo(v4.0.3)db with django(v1.11) using mongoengine(0.6.0) driver , it is showing connection does not exist., i'm getting following errors., Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 337, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py", line 52, in class AbstractBaseUser(models.Model): File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 124, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 330, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/usr/local/lib/python2.7/dist-packages/django/db/init.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 208, in getitem self.ensure_defaults(alias) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 178, in ensure_defaults raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) django.db.utils.ConnectionDoesNotExist: The connection default doesn't exist Thank you in advance.. -
CSRF verification failed with using model
i am not using any template i am just making a model and my model code is from django.db import models class cmdr(models.Model): text=models.TextField() my browser cookies is enable now when i am trying to login in admin panel its giving me CSRF verification failed i am not making any templates right now. i am studing django from online its working good in my instructor machine but not in my laptop -
getting a list of values from a query set object in Django
I have the following object result from query set: <QuerySet [<Post_Sub_Category: car>, <Post_Sub_Category: spare parts>, <Post_Sub_Category: truck>, <Post_Sub_Category: motor cycle>] How to access the values only and make list of them as string :['car','spare parts','truck','motor cycle']. -
Django static file not found
I am struggling using the static file app in django 2.1. Using the django-admin findstatic, the file is found: $ sudo python3 /opt/bitnami/apps/django/django_projects/Project/manage.py findstatic --verbosity 2 leaflet/leaflet.css Found 'leaflet/leaflet.css' here: /opt/bitnami/python/lib/python3.6/site-packages/leaflet/static/leaflet/leaflet.css Using the url below, my browser shows "The requested URL /Project/static/leaflet/leaflet.css was not found on this server.": http://myserver/Project/static/leaflet/leaflet.css However, using a different file from a different directory: $ sudo python3 /opt/bitnami/apps/django/django_projects/Project/manage.py findstatic --verbosity 2 admin/css/fonts.css Found 'admin/css/fonts.css' here: /opt/bitnami/apps/django/lib/python3.6/site-packages/Django-2.1.1-py3.6.egg/django/contrib/admin/static/admin/css/fonts.css The file is accessible in my browser using the url: http://myserver/Project/static/admin/css/fonts.css What can I do to troubleshoot this issue? I use DJANGO 2.1 My settings.py: STATIC_URL = '/Project/static/' Thanks in advance. -
Django: Field missing when queried
I'm having some trouble querying for my CalculatedAmt field in my database. In fact, according to the error code, the field does not even exist. However, I have included it in my Models.py and it can even be seen in my admin interface on Django. Here are my codes: Model.py class Transaction(models.Model): DocRef = models.CharField(max_length=10,default="missing") DocDate = models.DateField() AcCrIsMinus1 = models.CharField(max_length=10,default="missing") AcCurWTaxAmt = models.CharField(max_length=10,default="missing") HomeWTaxAmt = models.CharField(max_length=10,default="missing") CalculatedAmt = models.CharField(max_length=10, default="missing") ProjectCode = models.CharField(max_length=10,default="missing") Location = models.CharField(max_length=10,default="missing") Sales_Person = models.CharField(max_length=10,default="missing") AcCode = models.CharField(max_length=8,default="missing") Customer_Name = models.CharField(max_length=30,default="missing") def __str__(self): return "%s" % self.id Query in shell (for a table): Transaction.objects.all().filter(Sales_Person=Sales_Person).values('DocRef','DocDate','AcCrIsMinus1','HomeWTaxAmt','ProjectCode','Customer_Name','Location') Error Message: django.core.exceptions.FieldError: Cannot resolve keyword 'CalculatedAmt' into field. Choices are: AcCode, AcCrIsMinus1, AcCurWTaxAmt, Customer_Name, DocDate, DocRef, HomeWTaxAmt, Location, ProjectCode, Sales_Person, id Here's a screenshot of a Transaction instance from the admin interface: screenshot Thank you! -
using latest() with pagination causes TypeError unhashable type: 'slice'
Perhaps my approach/query is totally wrong but anyway, I am trying to list books and the latest edit that was made to them. A book can be edited multiple times and each edit has a category. Book(models.Model) BookEdit(models.Model): book=models.ForeignKey(Book,related_name='book_edits') editedon=models.DateTimeField(auto_now_add=True) action=models.CharField(max_length=250 Now in my views I am simply doing: books=Book.objects.value('id','book_edits__action').latest('book_edits__editedon') try: page=request.query_params.get('page',1) paginator=Paginator(books,20) data=paginator.page(page) except PageNotAnInteger: data=paginator.page(1) except EmptyPage: data=paginator.page(paginator.num_pages) I have noticed it works without latest(), which seems to output dictionary object. How can I use latest() with paginator -
how to resolve an issue with If condition never be true in Django
This is a potion of view function written in Django. This clause never executed even though if the condition is true: def search(request): query_cc = request.GET.get('h_qcc') # category variable query_sc = request.GET.get('h_qsc') # sub_category variable print('###################') print(query_sc) dd = Post_Category.objects.filter(category_name__iexact=query_cc).get() print(';;;;;;;;;;;;;;;;;') print(dd) # print the category ddd = Post_Sub_Category.objects.filter(category_name__category_name__iexact=dd) print('ooooooooooooooooo') print(ddd) # print the sub_category variable for the category variable that is passed through the request of if query_sc in Post_Sub_Category.objects.filter(category_name__category_name__iexact=query_cc): # if the sub_category passed in variable query_sc is existing in a list of choices based on category that is passed in query_cc variable. Unfortunately this clause never executed even though it is true all_p_sub_category = Post_Sub_Category.objects.filter(category_name__category_name__iexact=query_cc) print('+++++++++++++++++++') print (all_p_sub_category) This is sample of the out put that the if statement should be executed: ################### car ;;;;;;;;;;;;;;;;; for sale ooooooooooooooooo <QuerySet [<Post_Sub_Category: car>, <Post_Sub_Category: spare parts>, <Post_Sub_Category: truck>, -
How to display in Django Templates Embedded Models?
models.py class Decomposicao(models.Model): tirosina = models.BooleanField('tirosina') fenilalanina = models.BooleanField('fenilalanina') class Meta: abstract = True class SDF(models.Model): numero = models.IntegerField('SDF', unique=True, primary_key=True) decomposicao = models.EmbeddedModelField( model_container=Decomposicao, ) data_insercao = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.numero) views.py def search(request): data = {} if request.method == 'GET': search = request.GET search = search['sdf'] if search.startswith("SDF") or search.startswith("sdf"): sdf = SDF.objects.get(pk=search[3:]) else: sdf = SDF.objects.get(pk=search) data['sdf'] = sdf data['numero'] = format(sdf.numero, '04d') return render(request, 'app/busca.html', data) I'm using mongodb and django, so I decided to utilize djongo as the connector - djongo doc - that been said I'm trying to display the content I find on querys in django templates - busca.html - but I can't find a way to display the Embedded models. busca.html {% extends 'app/base.html' %} {% block cabecalho %} {% load staticfiles %} <title>SDF{{ numero }}</title> {% endblock%} {% block conteudo %} <section class="bg-light"> <div class="container "> <div class="col-lg-12 h-100 text-center text-lg-left my-auto"> <h1 class="text-muted medium mb-4 mb-lg-0">SDF{{ numero }</h1> <br> {{ sdf }} </div> </div> </section> {% endblock %} Doing that only display the number - 'numero' - of the sdf. Thanks. -
Django: how do I use the form values in other python scripts?
this is my views.py from django.shortcuts import render from .reisplanner import * def home(request): return render(request, 'home.html', {}) def reisplanner(request): if request.method == 'POST': form = reisplannerForm(request.POST) if form.is_valid(): beginstation = form.cleaned_data['beginstation'] eindstation = form.cleaned_data['eindstation'] print(beginstation, eindstation) else: form = reisplannerForm() return render(request, 'reisplanner.html', {'form': form}) forms.py from django import forms class reisplannerForm(forms.Form): beginstation = forms.CharField(required=True) eindstation = forms.CharField(required=True) and i want to use the variables in reisplanner.py def reisplanner(): use the values of the form here I have literally tried everything, this is for a school project and have been trying to fix this for about 2 days now with no result. If you guys could help me that would be fantastic. how do I get the values of a form to my python script? -
Custom Mixin for Mulitple Field Object Lookup in Django REST
I have the following code which doesn't work: In models.py: class Unit(models.Model): unit_name = models.CharField(max_length=255) In views.py class MultipleFieldLookupMixin(object): """ Apply this mixin to any view or viewset to get multiple field filtering based on a `lookup_fields` attribute, instead of the default single field filtering. """ def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filter_queryset(queryset) # Apply any filter backends filter = {} for field in self.lookup_fields: if self.kwargs[field]: # Ignore empty fields. filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) # Lookup the object self.check_object_permissions(self.request, obj) return obj class UnitViewSet(viewsets.ReadOnlyModelViewSet, MultipleFieldLookupMixin): serializer_class = UnitSerializer queryset = Unit.objects.all() lookup_fields = ('pk', 'unit_name') In router.py router.register(r'units', UnitViewSet) I am able to access units/pk but units/unit_name gives a 404 error. Do you I have write a custom URL to make this work? If so, then what is the point of using Routers with ViewSets? Any help would be appreciated. Thanks. -
Understanding Django foreign key
A beginner quesion here. Probably this question has been asked before in stack overflow here, but still needing a clear answer. What is and when do you need to use ForeignKey in your Django models. Thanks -
Django filtering content by site_id depending on HTTP_HOST problem with request
so this is my view, the problems is that when i run the site, i get nameerror at/ name 'request' is not defined def HomePageView(TemplateView): def get_context_data(self,**kwargs): http_host = request.META['HTTP_HOST'] if 'doctorlandivar.com' in http_host: context = super(HomePageView, self).get_context_data(**kwargs) postlist = Post.objects.all().order_by("-date") videolist = Video.objects.all().order_by("-date") logolist = Logo.objects.all() context['object_list'] = postlist.filter(sites_id=3)[:4]#normal site 3 context['videos'] = videolist.filter(site_id=3)[:4] context['logos'] = logolist.filter(sites_id=3) return render('home/index.html', context) elif 'doutorlandivar.com' in http_host: context = super(HomePageView, self).get_context_data(**kwargs) postlist = Post.objects.all().order_by("-date") videolist = Video.objects.all().order_by("-date") logolist = Logo.objects.all() context['object_list'] = postlist.filter(sites_id=2)[:4]#normal site 2 context['videos'] = videolist.filter(site_id=2)[:4] context['logos'] = logolist.filter(sites_id=2) return render('home/index.html', context) else: context = super(HomePageView, self).get_context_data(**kwargs) postlist = Post.objects.all().order_by("-date") videolist = Video.objects.all().order_by("-date") logolist = Logo.objects.all() context['object_list'] = postlist.filter(sites_id=1)[:4]#normal site 1 context['videos'] = videolist.filter(site_id=1)[:4]#normal site 1 context['logos'] = logolist.filter(sites_id=1) return render('home/index.html', context) i tought i was done and ready to up the website but that just gave me trouble, is there any quick fix for that without changing my whole view/template :( thank you so much -
Django - Is there an easier way to to display movie genre pages using DRY
Ive created a movie website using Django 2.1, i have a few pages for genres Admin-top,Latest,Thriller,Horror,Action etc... which is fine, but i have another 10+ genres and 10+ years to do and am thinking there must be a better way, the DRY way, then to have the individual pages when the page layout is the same etc, its just the content which changes like in my detail view.. i have google,searched etc i cant seem to figure it out. Any help is appreciated Here is my views from django.shortcuts import render, get_object_or_404 from .models import Movie, Banner from django.views.generic import ListView, DetailView # Base page for pages. def base(request): return render(request, 'movies/base.html') # HOME-PAGE class HomeListView(ListView): model = Movie template_name = 'movies/home.html' # <app>/<model>_<viewtype>.html def get_context_data(self, **kwargs): context = super(HomeListView, self).get_context_data(**kwargs) context['admin_movies'] = Movie.objects.filter(admin_top__contains='Yes').order_by('-date_posted') context['latest_movies'] = Movie.objects.all().order_by('-date_posted') context['thriller_movies'] = Movie.objects.filter(genre__contains='Thriller').order_by('-date_posted') context['horror_movies'] = Movie.objects.filter(genre__contains='Horror').order_by('-date_posted') context['action_movies'] = Movie.objects.filter(genre__contains='Action').order_by('-date_posted') # Add any other variables to the context here return context # MOVIE DETAIL PAGE class MovieDetailView(DetailView): model = Movie queryset = Movie.objects.all() template_name = 'movies/movie-detail.html' def get_object(self): title_ = self.kwargs.get('title') return get_object_or_404(Movie, title=title_) # ADMIN MOVIE-PAGE class AdminListView(ListView): model = Movie queryset = Movie.objects.filter(admin_top__contains='Yes') template_name = 'movies/admin-top.html' context_object_name = 'admin_movies' ordering = ['-date_posted'] … -
django __class__ method not working on m2m relationship
In my django project at a instance I need class name of object by its reverse relationship, for that I used __class__ method . This is working fine with OneToOne relationship that is print(instance.content_object.__class__) and output is - <class 'products.models.ProductCreateModel'> but when using it with m2m it gives me print(instance.product_seller.__class__) and output is - <class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'> How can I get the class name ? -
Default Time with MM:SS format - Django
I have written code for countdown timer using Javascript and to make it dynamic I have given an option for admin to change the time accordingly. The javascript takes the input in MM:SS, I have used the following datatype in the model.py and the system are taking it in HH:MM format, so I cannot set the time for more than 24 minutes the values it shows are from 00:00 to 23:00. Is there any datatype or a way to resolve the time format. My application need timer in MM:SS and doesn't need hours. model.py class PhysicalPostPage(AbstractForm): intro = RichTextField(blank=True) strength = RichTextField(blank=True) agility = RichTextField(blank=True) flexibility = RichTextField(blank=True) points_for_this_activity = models.IntegerField(blank=True, default=0) timer_for_this_activity = models.TimeField(blank=True, default=datetime.time(00, 11)) thank_you_text = RichTextField(blank=True) For testing purpose, I have set the timer to 11 seconds. javascript function doCount(){ var timer2 = "{{ page.timer_for_this_activity|safe }}"; var interval = setInterval(function() { var timer = timer2.split(':'); //by parsing integer, I avoid all extra string processing var minutes = parseInt(timer[0], 10); var seconds = parseInt(timer[1], 10); --seconds; minutes = (seconds < 0) ? --minutes : minutes; seconds = (seconds < 0) ? 59 : seconds; seconds = (seconds < 10) ? '0' + seconds : seconds; //minutes = …