Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use storages.backends.s3boto.S3BotoStorage to add tags to an s3 object
My question is around tagging s3 objects using S3BotoStorage. Through boto3 you can add tags to an s3 object before uploading it to an s3 bucket. this it the documentation for tagging s3 objects I was wondering if there is a way to add tags to an s3 object if the method of uploading is storages.backends.s3boto.S3BotoStorage. Thanks! -
Django: ImportError: cannot import name 'GeoIP2'
I am trying to set up geoip2 for GeoDjango as per the instructions. For some reason the wrapper isn't importing the function. It worked before I downloaded the databases and pointed to them in my settings, but for some reason now I can't load GeoIP2 (even when I comment out the line in settings.py). How should I troubleshoot this? Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import geoip2 >>> >>> from django.contrib.gis.geoip2 import GeoIP2 Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name 'GeoIP2' >>> -
Exception Type: MissingSchema / beautifulsoup
I'm exploring beautifulsoup en django and it worked fine until I added a variable as url (from a model textfield with URLValidator) I added an 'https://"+ before the model_url, but this gave also an error. what could be the problem? I googled a lot, but nothing worked.. hopefully it's not a double question.. thanks in advance! This is my model.py class ScrapeUrl(models.Model): product_title = models.CharField(max_length=255) product_ean = models.CharField(max_length=25) scrape_url = models.TextField(validators=[URLValidator()]) shop_price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.product_title def __unicode__(self): return unicode(self.product_title) or u'' this is my views.py def scrape_list_view(request): scrape_object = ScrapeUrl.objects.all() model_url = ScrapeUrl.scrape_url good_url = (model_url) print(good_url) response = requests.get(good_url) soup = bs4.BeautifulSoup(response.text) price = soup.find("span", {"class": "promo-price"}).text price_dot = price.replace(",",".").replace('-','0') price_break = price_dot.replace('\r', '').replace('\n', '').replace(' ','') price_data = float(price_break) return render(request, 'scrape_list.html', {'price': price}) and this is the traceback Environment: Request Method: GET Request URL: http://localhost:8000/app/ Django Version: 1.11.13 Python Version: 2.7.14 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mathfilters', 'scrapeapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/sanderhegeman/scraper/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/sanderhegeman/scraper/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/sanderhegeman/scraper/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sanderhegeman/scraper/scrapeapp/views.py" in scrape_list_view 18. response … -
Want to resolve a dictionary whose key is a field in a model
I have {% for competency in domain.competency_set.all %} <td> {{competency.id}} {{scoredict.8}} {% with cid=competency.id %} {{ scoredict.cid }} {% endwith %} </td> so scoredict.8 displays a value but when competency.id is 8, scoredict.cid comes up empty. What am I doing wrong? What's the workaround? I can see why scoredict.competency.id doesn't work, but I don't see how to change the order of evaluation. If I could force order of evaluation with parentheses I'd want something like scoredict.(competency.id) -
Django throws Operational Error with substituted Auth Model
apologies in advance if this is a duplicate question. To the best of my searches, I was not able to find this question. Using Django 2.0, I substituted the built-in django.contrib.auth with my own Users model, extending it with AbstractUser. The Users model is dependent on an existing table in MySQL, which is configured to work with Django. Django does not detect any issues when performing a check; however, I receive the following error: OperationalError at / (1054, "Unknown column 'users.last_login' in 'field list'") I added the column into the table thinking it would be a useful field to have, but was apprehensive because I figured I'd get another error for another missing field. Lo and behold: OperationalError at / (1054, "Unknown column 'users.is_superuser' in 'field list'") The point of substituting the user model is so I can ditch unimportant fields, such as "username". Do I just need to add each column to the table until I get all the auth fields in the table, or am I doing something fundamentally wrong? TL;DR: How do I create a custom authentication method for Django using an existing table? -
Django NoReverseMatch when redirecting to view
After loging in correctly, I want to redirect the user to another page so I use redirect, but I get a NoReverseMatch error. Reverse for 'watchfilms' with arguments '()' and keyword arguments '{}' not found. I don't know what's going wrong so I'm showing you my urls.py and views.py files. Maybe you see something wrong... project's url.py urlpatterns = patterns('', url(r'^films/', include('films.urls')), url(r'^admin/', include(admin.site.urls)), ) app's url.py urlpatterns = patterns('', url(r'^$', 'films.views.index'), url(r'^signup$', 'films.views.signUp'), url(r'^login$', 'films.views.logIn'), url(r'^signedupok$', 'films.views.signedUpOk'), url(r'^watchfilms$', 'films.views.watchFilms'), url(r'^logout$', 'films.views.logout'), ) views.py ... def logIn(request): error = "" username = request.POST.get('username', False) pass = request.POST.get('password', False) user = authenticate(username = username, password = pass) if username or pass: if user is not None: if user.is_active: login(request, user) return redirect('watchfilms') else: error = 'Error while login!' else: errorea = 'Data is not correct!' return render(request, 'films/login.html', {'error': error}) @login_required def watchFilms(request): film_list = Film.objects.all() paginator = Paginator(film_list, 3) page = request.GET.get('page') try: films = paginator.page(page) except PageNotAnInteger: films = paginator.page(1) except EmptyPage: films = paginator.page(paginator.num_pages) return render(request, 'films/watchFilms.html', {'films': films}) ... Once login is OK, watchFilms view should be called but it looks like it cannot be found (I don't get it why, I think urls.py is OK)... -
how to correctly assign the through attribute in django?
I was just looking the documentation to be able to change the intermediate table: https://docs.djangoproject.com/en/2.0/topics/db/models/#extra-fields-on-many-to-many-relationships but when I implement it, I get into trouble. I am developing an app where students can evaluate their teachers, my models are: class Item(models.Model): name = models.TextField() def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=50,null=True) items = models.ManyToManyField(Item, related_name='categories') def __str__(self): return self.name class Professor(models.Model): name = models.CharField(max_length=50,null=True) categories = models.ManyToManyField(Category, related_name='professors') def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=50,null=True) professors = models.ManyToManyField(Professor, related_name='students') def __str__(self): return self.name each student has Professor, these Professor in turn have associated categories of questions, and each category of questions has associated questions. what I want is to modify the intermediate table student_professor to add a field in which when the student evaluates a teacher, this is recorded in the database. I tried it with: class Professor(models.Model): name = models.CharField(max_length=50,null=True) categories = models.ManyToManyField(Category, related_name='professors') def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=50,null=True) professors = models.ManyToManyField(Professor, related_name='students',through='Studentprofesor' ) def __str__(self): return self.name class Studentprofesor(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) professor = models.ForeignKey(Professor, on_delete=models.CASCADE) tested = models.BooleanField(default=False) the migration works without problems, and in the database I get the intermediate table student_professor with the fields I assigned in … -
Annotate Django queryset with previous Sunday based on row's date field
I have a table with a set of Orders that my customers made (purchased, to say so). The customers can choose the delivery date, and that is stored in each Order in a field called Order.delivery_date. I would like to annotate a queryset that fetches Orders with the previous Sunday for that date class Order(BaseModel): customer = ForeignKey(Customer, on_delete=CASCADE, related_name='orders') delivery_date = DateField(null=True, blank=True) I thought "Oh! I know! I'll get the date index in the week and I'll subtract a datetime.timedelta with the number of days of that week index, and I'll use that to get the Sunday (like Python's .weekday() function)": from server.models import * import datetime from django.db.models import F, DateField, ExpressionWrapper from django.db.models.functions import ExtractWeekDay Order.objects.filter( delivery_date__isnull=False ).annotate( sunday=ExpressionWrapper( F('delivery_date') - datetime.timedelta(days=ExtractWeekDay(F('delivery_date')) + 1), output_field=DateField() ) ).last().sunday But if I do that, I get a TypeError: unsupported type for timedelta days component: CombinedExpression when trying to "construct: the timedelta expression. This is a Python 3.4, with Django 2.0.3 over MySQL 5.7.21 Thank you in advance. -
Django database migration error
I have a Django project connected to Gmail API. When I try to do database migration it returns this: C:\Users\Peter\Desktop\FastProject>python manage.py migrate FastProject Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", l ine 371, in execute_from_command_line utility.execute() File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", l ine 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 332, in execute self.check() File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrat e.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 397, i n check for pattern in self.url_patterns: File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 536, i n url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 529, i n urlconf_module return import_module(self.urlconf_name) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File … -
{% include '' with %} in Django template
I'm trying to use the code below in a specific way. {% include 'your_template_here' with keyword='your_value_here' %} What I wanna do is pass my argument store_list into your_value_here as an argument for the paramater keyword. That is, it should be like the following: {% include 'your_template_here' with keyword={{ store_list }} %} But, it has a syntax error. Is it not allowed to pass a queryset in {% include ' ' with=' ' %} ? -
How can I stop a django server programatically
I want to perform some checks across a few environments being pointed to on startup of my django server to ensure consistency of the different environment configrations. For example, that they are all in dev configuration, or all in prod configuration. If this is not the case I would like to shut down the server. My question is what is the best way to shut down the server and report the issue? At the moment my plan is to raise a RuntimeError with the appropriate exception message. But I was wondering if there is any problem with this approach, or if there is a more suitable approach which I can not find. Researching the issue has unfortunately not yielded sufficient information. -
Take value from ForeignKey and SUM it. Django
I have no idea how to say on the title. but check it here: my model.py class Employee(models.Model): name = models.CharField(max_length=100) class EmpLoan(models.Model): status = models.BooleanField('Status', default=False) nominal = models.DecimalField(max_digits=10, decimal_places=0) employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL, related_name='emploan') class EmpInstallment(models.Model): nominal = models.DecimalField(max_digits=10, decimal_places=0) loan = models.ForeignKey(EmpLoan, related_name='empinstallment') created_at = models.DateTimeField(auto_now=True) and my views.py class EmpLoanListView(ListView): context_object_name = 'emploans' model = models.EmpLoan def get_context_data(self, **kwargs): context = super(EmpLoanListView, self).get_context_data(**kwargs) context['form'] = EmpLoanForm() return context and here my template_loan.html {% for emploan in emploans %} <tr> <td>{{ emploan.employee.name }}</td> <td>{{ emploan.nominal|intcomma }},-</td> <td>{{ emploan.installment.nominal|intcomma }},-</td> </tr> {% endfor %} here I am trying to access data from EmpInstallment model with emploan.installment.nominal but it doesn't work. how to how to take data from ForeignKey and sum it in my case?... it will return get() returned more than one ContentType -- it returned 2! since will have more than one value so I need to sum it also. -
How to fetch all users addresses from messages? Gmail API
I have a Django project connected to Gmaip API. My task is to cout all top senders and top recievers of user's email. So the plan is to get all user id's, put them in a dictionary, count their amount and print. How to fetch all the unique users from all these emails and at once, very fast? I tried this but it works very slow with INBOX label (10 000+ messages): import operator from googleapiclient import errors from quickstart import service def getTop(n): try: label = '' if n == 1: label_ids = "INBOX" label = "From" else: label_ids = "SENT" label = "To" user_id = "me" topers = service.users().labels().get(userId=user_id, id=label_ids).execute() count = topers['messagesTotal'] topers = service.users().messages().list(userId=user_id, labelIds=label_ids).execute() tmp = [] st = [] if 'messages' in topers: tmp.extend(topers['messages']) l = len(tmp) for i in range(0, l): idshka = tmp[i]['id'] mdata = service.users().messages().get(id=idshka, userId=user_id, format='metadata', metadataHeaders=[label]).execute() head = mdata['payload']['headers'] obval = head[0]['value'] # algo/////////////////////// t = str(obval) t = t.split('<', 1)[-1] t = t.replace('>', "") st.append(t) while 'nextPageToken' in topers: tmp = [] page_token = topers['nextPageToken'] length = len(page_token) topers = service.users().messages().list(userId=user_id, labelIds=label_ids, pageToken=page_token, maxResults=count).execute() tmp.extend(topers['messages']) for i in range(0, length): idshka = tmp[i]['id'] mdata = service.users().messages().get(id=idshka, userId=user_id, format='metadata', … -
1054, Unknown column 'group_shop_item.promo_discount' in 'field list'
I added a column on the Items table, ran makemigrations, then migrate. And now a 1054 error came up. Since I'm running it on a Vagrant Box, I ran vagrant up --provision and dropped & replaced mysql database. The column is not showing up on the database. Any help is greatly appreciated. models.py class Item(models.Model): obj_manager = ItemManager() brand = models.ForeignKey(Brand, on_delete=models.CASCADE) promo_discount = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) -
Celery Task State Not getting Store into Django-Celery Database
I'm running Celery(3.1.26) with Django(2.0.5) and want to see the task states in the database table. Unfortunately no entries are written into the table djcelery_taskstate and I can't figure out why. My settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djcelery', 'djkombu', 'cdm', ] BROKER_URL="django://" CELERY_RESULT_BACKEND = "database" CELERY_IMPORTS = ('cdm.tasks.autodiscover') import djcelery djcelery.setup_loader() My Task: from __future__ import absolute_import, unicode_literals import time from celery import task @task def auto(): for i in range(10): print('celery task=>',i) time.sleep(2) I am running python manage.py celerycam also, still I am not getting anything in the table, please help in that. -
RecursionError when Accessing DecimalField in Django
I have a model in Django that has a DecimalField. The field is nullable. When accessing the field I get a recursion error for some reason. ipdb> student.current_longitude *** RecursionError: maximum recursion depth exceeded while getting the str of an object ipdb> Can this have something to do with the way the null value is being serialized into a DecimalField? What's going on here? -
yelp search using Django
I am developing with yelp API, It works when I do the first time, but for the subsequent searches, it shows the same result. The following is my code def yelp_query(keyword, location): headers = {'Authorization': 'Bearer %s' % YELP_API_KEY} params = {'term': keyword, 'location': location} query = requests.get(YELP_SEARCH, headers=headers, params=params) return query.json() def search_result(request): items = [] query_item = request.GET.get('q') if query_item: items = yelp_query(keyword='query_item', location='London') return render(request, 'locator/search.html', {'results': items}) return render(request, 'locator/search.html', {'results': items}) my HTML <body> <h1>Search</h1> {% for biz in results.businesses %} {{biz.name}}, {{biz.location.city}}<br> {% endfor %} </body> Now when I do my first search, for example, Italian food http://127.0.0.1:8000/search/?q=Italian%20Food yelp lists some result Fortnum & Mason, London Team Man And Van, London TopShop, London Wickes Building Supplies, London Sylvanian Families Shop, London, London ... when I do the next search for pizza http://127.0.0.1:8000/search/?q=pizza it displays the same result as above. Can anyone suggest where I went wrong and How to improve my code. -
Django slug without unicode
I want to store my language Title as URL using Slugify. For Eg: my title is வணக்கம் நண்பர்களே I want to store this as வணக்கம்-நண்பர்களே but I get வணககம-நணபரகள missing some elements in the words. Models.py class Blog(models.Model): title = models.CharField(max_length = 55) slug = models.CharField(max_length=80) Views.py slugify(input,allow_unicode=True) -
Choose which way to calculate the PV and UV in Django?
I'm building a news website using Django and hope this website can handle millions of traffic.Now I'm coding a function that displays 48 hours most viewed articles to readers,so I need calculate the PV. I have searched for a while and asked some people.I know I have some options: 1.using simply click_num=click_num+1,but I know this is the worst way. 2.A better way is using Celery to code a distributed task,but I don't know how to exactly do it. 3.I heard Redis also can used to calculate PV and UV but,have no idea how to do it and not sure the it can satisfy my needs. 4.Another good way is to use google analysis,but I also have no idea how to do it and not sure the it can satisfy my needs. 5.The last way ,I think the easiest way is to use JavaScript, but I'm not sure whether it can satisfy my needs. Any friend can give me some advice? Thank you so much! -
Running Python inside Visual Studio 2017
I think I have a setting issue for Visual Studio... But a script that works just fine in Python IDLE 3.6 and in a separate anaconda IPython application (which I am used too) but does not run properly in VS 2017. The script uses a package called pyhaystack to get data off of a building automation system (and build pandas df) and the packages installed just fine... Could there be setting in VS to make it run? Ultimately I am hoping to create a Django app in VS to show the API data thru HTML/web browser... The code just runs forever in Visual Studio debug mode (f5) and the only thing I see in the output is this: The thread 'MainThread' (0x2ec4) has exited with code 0 (0x0). The program '[11104] python.exe' has exited with code -1 (0xffffffff). This is the Python script I am using: import numpy as np import pandas as pd from pyhaystack.client.niagara import NiagaraHaystackSession session = NiagaraHaystackSession(uri='http://1.1.1.1', username='@', password='!', pint=True) rng = '2018-05-08,2018-05-09' #Get Data for ProblemZnt znt = session.find_entity(filter_expr='sensor and zone and temp and problem').result znt = session.his_read_frame(znt, rng= rng).result znt = pd.Series(znt[znt.columns[0]]) #Get Data for oat oat = session.find_entity(filter_expr='sensor and outside and temp and … -
Django iframe gview from fileSystem/Storage not loading
Im trying to load with gview a PDF file from the filesystem The file its storage and when I call "{{documento.adjunto.url}}" it doesnt shows me 404 error, but still the PDF its not show. Trying using one from web, it works. <iframe src="http://docs.google.com/gview?url=https://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf&embedded=true" style="width:600px; height:450px;" frameborder="0"></iframe> HTML <div class="container"> <div class="row"> <div class="col-lg-12"> <iframe src="http://docs.google.com/gview?url={{documento.adjunto.url}}&embedded=true" style="width:600px; height:450px;" frameborder="0"></iframe> </div>> </div> </div> Viws.py @login_required def CurriculumDetailView(request, pk): documento = Curriculum.objects.get(pk=pk) return render( request, "INTRANET/curriculum_detail.html", context = { 'documento':documento, }, ) Model class Curriculum(models.Model): rut_candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE) adjunto = models.FileField(upload_to=UPLOAD_CVS) fecha_ingreso_cv = models.DateField(_("Date"), auto_now_add=True) URL.py urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Create an instance of postgre with a "COLLATE" pt_BR (Kubernetes/GCloud)
Good afternoon sirs. I'm having a little difficulty. I have a system created in pytho and django. Previously I used sqlit3 to store the data and recently changed the database to postgre. The "COLLATE" that we use in Brazil is pt_BR, however, when we start an instance in kubernetes do gcloud, it automatically gets en_US. This is causing conflict in my system, because we use characters of the type "to use". How could I solve this problem? Is it possible to create an instance in kubernetes, from postgre, which already comes with the standard collate pt_BR? Is there anything in the django application that I can choose the collate I will use? I need help! -
when a user likes a post, My code assumes that that user has liked every post for that group, need to fix this.
In my App, posts belong to groups, and posts can be liked. this is the model for posts: from django.db import models from django.contrib.auth.models import User from groups.models import Group class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() likes_total = models.IntegerField(default=0) likers = models.ManyToManyField(User, related_name='likers') pub_date = models.DateTimeField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'author') group = models.ForeignKey(Group, on_delete=models.CASCADE) def __str__(self): return self.title def summary(self): # return the 1st 100 chars return self.body[:100] def pub_date_pretty(self): # strftime is how to break down time return self.pub_date.strftime('%b %e %Y') when somebody likes a post, this user gets added to the 'likers' M2M relationship. here is the view that takes care of this: def like(request, post_id, group_id): group = get_object_or_404(Group, pk= group_id) post = get_object_or_404(Post, pk= post_id) posts = Post.objects.filter(group__id = group_id) if request.method == 'POST': if request.user in post.likers.all(): return render(request, 'groups/detail.html', {'group':group, 'posts':posts} ) else: post.likes_total += 1 # with add, we are adding a liker to the likers relation, between a user and a post post.likers.add(request.user) post.save() return redirect('/groups/' + str(group_id) ) else: return render(request, 'groups/detail.html', {'group':group}) the url for the likes view is here: from . import views from django.urls import path app_name = 'posts' urlpatterns = [ path('create/<int:group_id>/', views.create, … -
Django admin nested models
I have model model Word which has foreign key to model Group And I want the structure in django admin panel to be nested, like this: -Group -Word1 (clickable where I can show all the info about this word model) -Word2 (clickable) -Word3 (clickable) I tried to do something like this in admin.py but got an error: no class meta from django.contrib import admin from main_app.models import Profile, Project, User, Word, Phrase, Group def unbound_callable(word): return word.name class WordInline(admin.TabularInline): model = Word fields = ('name', 'model_callable', 'model_admin_callable', unbound_callable) readonly_fields = ('model_callable', 'model_admin_callable', unbound_callable) def model_admin_callable(self, word): return word.name class GroupAdmin(admin.ModelAdmin): model = Group inlines = (Word,) class Meta: model = Group admin.site.register([GroupAdmin, Word, Phrase]) -
Google's material design with Django? (w/out node.js)
I stumbled upon google's material design web components ("https://material.io/") and would like to implement it in my projects. The only problem is that all the documentation are written for node.js. Is it possible use Material Design with django/jinja? Note: Google's Material Design is the successor of Material Design Lite.