Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display django-taggit tags in template as clickable link to all items with these tags
I want to display all tags that my model have in my template as a clickable link, when I click on any link it will take me to all items that have these tag (like in stackoverflow or any other website) my app urls.py : from django.urls import path from . import views app_name = 'core' urlpatterns = [ path('', views.GameList.as_view(), name='gameslist'), path('<int:pk>/', views.GameDetail.as_view(), name='gamedetail'), ] my views.py : class GameList(PaginationMixin, ListView): model = Game template_name = 'core/game_list.html' context_object_name = 'game_list' paginate_by = 12 class GameDetail(DetailView): model = Game template_name = 'core/game_detail.html' context_object_name = 'game_detail' #related items using django-taggit def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["related_items"] = self.object.tags.similar_objects()[:4] return context my models.py : class Game(models.Model): name = models.CharField(max_length=140) developer = models.CharField(max_length=140) game_trailer = models.CharField(max_length=300, default="No Trailer") game_story = models.TextField(default='No Story') tags = TaggableManager() -
How to edit the migration file in Django?
Sorry for my English, I'm still learning. I have a question about migrations in django. I currently have 2 problems with migrations. Being them: 1. A migration, in which I changed the column name in the database. 2. A migration creating new tables, which does not allow running the migrate command since the tables were created. One solution I found would be to create a validation on both files checking if the field or table exists in the field. But I do not know how to do it, could you help me? Example of codes: 1.Error: Referred is change from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('produtos', '040_item_comprado'), ] operations = [ migrations.CreateModel( name='ProdutoAlterado', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField()), ('date_buy', models.DateTimeField(null=True)), ('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='ecommerce.Client')), ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='ecommerce.Order')), ('change', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='ecommerce.Troca')), ], options={ 'db_table': 'productchange', }, ), ] 2 Error: The table e already exists from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('ecommerce', '082_new_tables'), ] operations = [ migrations.CreateModel( name='Actions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=32)), ('value', models.CharField(max_length=64)), ('ref', models.CharField(max_length=16)), ], options={ 'db_table': 'action', }, … -
unsupported operand type(s) for +=: 'int' and 'NoneType'?Error in django
This is my code def list_ledger(listleg): listledger = [['','','',''] for x in range(listleg.count())] f=0 for q in listleg: k=0 while k<4: if (k==0): listledger[f][k] = q.Creation_Date elif(k==1): listledger[f][k] = q.name elif(k==2): gn = q.group1_Name gn_bn = gn.balance_nature listledger[f][k] = gn_bn else: listledger[f][k] = q.Opening_Balance k=k+1 f=f+1 return listledger def list_journal(listjour): listjournal= [['','','','',''] for x in range(listjour.count())] c=0 for i in listjour: d=0 while d<5: if (d==0): listjournal[c][d] =i.Date elif(d==1): listjournal[c][d] =i.To elif(d==2): listjournal[c][d] =i.By elif(d==3): listjournal[c][d] =i.Debit else: listjournal[c][d] =i.Credit d=d+1 c=c+1 return listjournal def toside(ledgerlist,journallist,lname): for w in ledgerlist: sum2 =0 for i in journallist: if(str(i[2]) == w[1]): sum2 +=i[3] if(str(w[1])==str(lname)): return(sum2) def byside(ledgerlist,journallist,lname): for w in ledgerlist: sum1 =0 for i in journallist: if(str(i[1]) == w[1]): sum1 +=i[4] if(str(w[1])==str(lname)): return(sum1) def total_balance(ledgerlist,journallist,ledgername): sumby = 0 sumby+=byside(ledgerlist,journallist,ledgername) return sumby def total_balance_credit(ledgerlist,journallist,ledgername): sumto = 0 sumto+=toside(ledgerlist,journallist,ledgername) return sumto lspre = ledger1.objects.all() ls = list_ledger(lspre) jpre = journal.objects.all() j = list_journal(jpre) @receiver(pre_save, sender=ledger1) def update_total_debit(sender,instance,*args,**kwargs): Total_Debit = total_balance(ls,j,[lspre[i].name for i in range(int(lspre.count()))]) instance.Total_Debit = Total_Debit @receiver(pre_save, sender=ledger1) def update_total_credit(sender,instance,*args,**kwargs): Ctotal = total_balance_credit(ls,j,[lspre[i].name for i in range(int(lspre.count()))]) instance.Ctotal = Ctotal @receiver(pre_save, sender=ledger1) def update_closing_balance(sender,instance,*args,**kwargs): Closing_balance = instance.Total_Debit + instance.Opening_Balance - i instance.Ctotal instance.Closing_balance = Closing_balance I am getting an error 'unsupported operand … -
Hot to access python django dev server started in AWS Cloud9
I'm new to AWS. I created a test environments with AWS Cloud9, and a django project. When I start djangos dev server, is it possible to access it, from Cloud9 IDE preview or from the internet? thanx for your help in advance, strophi -
Debug, measure time image upload in django
I have a problem in my project in django (Django 1.8 - I know it is old) with photo uploading. The point is that this is too slow. What could be the reason? How can I debug, measure how long it takes? This should be checked on the nginx side? -
Django Rest Framework Filter using foreign Key
I have following DB Structure with 3 tables as following Table Persons Id U_id PersonName 101 12 Iron Man 201 12 Spider Man 301 15 Thanos Table EarnTypes Id U_id TypeEarning 10 12 Salary 20 15 Lottery 30 15 Gambling Table EarningsEntry ID U_Id P_Id EarnType_Name Earn_Amt Earn_Date 1001 12 101 10 5$ 8-Jun-2017 3001 15 301 20 25$ 7-Apr-2018 4001 12 201 10 50$ 19-Apr-2018 My List API View code is following i am filtering data based on logged in users only. class EarningEntryAPIView(mixins.CreateModelMixin,generics.ListAPIView): permission_classes = [IsOwnerOnly] serializer_class = EarningsSerializer # def get_queryset(self): request = self.request #print (request.user) qs = EarningsEntry.objects.filter(U_id=self.request.user) query = request.GET.get('q') if query is not None: qs = qs.filter(Earning_Type_id__EarningTypeName__contains=query) return qs def post(self,request,*args,**kwargs): return self.create(request,*args,**kwargs) def perform_create(self, serializer): serializer.save(id=self.request.user) My EarningEntry Model is as following. def upload_file(instance, filename): return "earnings/{user}/{filename}".format(user=instance.id, filename=filename) class EarningsQuerySet(models.QuerySet): def serialize(self): list_values = list( self.values('Id', 'U_id', 'P_id', 'Earning_Type_id', 'Ear_Amt', 'Ear_Img', 'Ear_date', 'Ear_comm')) print(list_values) return json.dumps(list_values, sort_keys=True, indent=1, cls=DjangoJSONEncoder) class EarningssManager(models.Manager): def get_queryset(self): return EarningsQuerySet(self.model, using=self._db) # Create your models here. class EarningsEntry(models.Model): Id = models.AutoField(primary_key=True) U_id=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) P_id =models.ForeignKey(personmodel.Person,on_delete=models.CASCADE) Earning_Type_id = models.ForeignKey(eartypemodel.EarningTypes,on_delete=models.CASCADE) Ear_Amt = models.FloatField(null=False,blank=False) Ear_Img = models.ImageField(null=True,blank=True) Ear_date = models.DateField("ExpenseDate",null=False,blank=False) Ear_comm = models.TextField() objects = EarningssManager() def __str__(self): return str(self.U_id) + str(self.P_id) … -
Django ORM Group BY and return additional fields
I want to perform query like this: SELECT loan_id, tenor, amount COUNT(id) AS total FROM loan GROUP BY loan_id But, I want only use 1 group by field "loan_id", how to return other fields like "tenor", "amount" I don't want tenor and amount in GROUP BY clause. How to achive using django ORM? -
DRF - OPTIONS request for serializer with nested serializer doesn't show inner fields
Why would the OPTIONS request not include the nested serializer field or its inner fields? class CustomerProductsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) description = serializers.ReadOnlyField(source='product.description') class Meta: model = CustomerTemplate fields = ('id', 'description', 'quantity', 'unit',) class CustomerDetailSerializer(serializers.ModelSerializer): products = CustomerProductsSerializer( source='customertemplate_customer', many=True) class Meta: model = Customer fields = ('id', 'name', 'products') read_only_fields = ('id', 'name') def update(self, instance, validated_data): ... OPTIONS request output: { "name": "Customer Instance", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "PUT": { "id": { "type": "integer", "required": false, "read_only": true, "label": "ID" }, "name": { "type": "string", "required": false, "read_only": true, "label": "Name" } } } } How would you go about adding the products field and it's inner fields to the Metadata? According to this comment chain, it's been supported for a while. -
ensure_csrf_cookie on every page
Consider an online shop with a Basket button. Clicking the button reveals a popup, where user can change, among other things, number of items to be ordered (AJAX requests). That means I've got to add ensure_csrf_cookie to every page. But some views are defined right in urls.py files (e.g., TemplateView.as_view(...)). Additionally, I'd like to enforce it for all the pages, to not forget to add it one day. What do I do? -
gunicorn + mezzanine : static files are not found
I installed a Mezzanine CMS by default and I will try to serve by gunicorn -- With python manage.py runserver, all static files are served only if DEBUG = True Logs said: ... (DEBUG=False) [07/Sep/2018 12:23:56] "GET /static/css/bootstrap.css HTTP/1.1" 301 0 [07/Sep/2018 12:23:57] "GET /static/css/bootstrap.css/ HTTP/1.1" 404 6165 ... -- With gunicorn helloworld.wsgi --bind 127.0.0.1:8000, no static found! Logs said: $ gunicorn helloworld.wsgi --bind 127.0.0.1:8000 [2018-09-07 14:03:56 +0200] [15999] [INFO] Starting gunicorn 19.9.0 [2018-09-07 14:03:56 +0200] [15999] [INFO] Listening at: http://127.0.0.1:8000 (15999) [2018-09-07 14:03:56 +0200] [15999] [INFO] Using worker: sync [2018-09-07 14:03:56 +0200] [16017] [INFO] Booting worker with pid: 16017 Not Found: /static/css/bootstrap.css/ Not Found: /static/css/mezzanine.css/ Not Found: /static/css/bootstrap-theme.css/ Not Found: /static/mezzanine/js/jquery-1.8.3.min.js/ Not Found: /static/js/bootstrap.js/ Not Found: /static/js/bootstrap-extras.js/ Please have a look to url wanted: gunicorn or mezzanine (or else?) add a / character in the end of url. I did this command too python manage.py collectstatic with no effect :( STATIC_ROOT is correct and I applied https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-static-files-during-development Do you have a tips or solution? I'm afraid I didn't search correctly! Thanks Momo -
How to get multilevel data in django
I am new in django framework.I have 4 tables in mysql database. I want to fetch data from main table with translation table and city table with its translation. My model.py class Country(models.Model): #id = models.IntegerField(primary_key=True) iso_code = models.CharField(max_length=2, unique=True) slug = models.CharField(max_length=255, unique=True) is_featured = models.IntegerField(max_length=1) class Meta: db_table = 'rh_countries' class CountryTranslation(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) locale = models.CharField(max_length=2) class Meta: db_table = 'rh_countries_translations' class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) class Meta: db_table = 'rh_cities' class CityTranslation(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) locale = models.CharField(max_length=2) class Meta: db_table = 'rh_city_translations' And This is my views.py Country.objects.filter( is_featured=1, countrytranslation__locale='en' ).annotate( name=F('countrytranslation__name') totalCities=Count('city', distinct=True) ) I want to fetch all cities from city table which has foreign key country_id and city name from city translation lable. -
How to visualize events/signals in Django project?
When project gets bigger I need to see all events which happens during model or project lifecycle. I want to see (on graph or chart) all consequences of actions like creating, updating, saving etc. For example, when I create a Property object, there is a post_save signal which creates PropertyProfile and PropertyProfile has overriden save method where I calculate price of the property before super().save(..). Which tool should I use to visualize such events so I can see what will happen and when will it happen? I think that sequence diagram or flowchart is probably not enough because I can't visualize all such information but maybe I'm wrong, not good at UML. -
Django Generic View - ListView from an instance of DetailView
I am using Generic views DetailView and ListView I have three models as such User, Business and Invoice. A User can have multiple businesses can have multiple invoices. #mixins.py class BusinessOwnerRequiredMixin(object): def has_permissions(self): obj = self.get_object() if isinstance(obj, Business): # Assumes that your Article model has a foreign key called `auteur`. return obj.owner == self.request.user def dispatch(self, request, *args, **kwargs): if not self.has_permissions(): raise PermissionDenied return super(BusinessOwnerRequiredMixin, self).dispatch(request, *args, **kwargs) #views.py class BusinessDashboard(BusinessOwnerRequiredMixin, DetailView): model = Business template_name = "business/business-main.html" class InvoiceListView(BusinessDashboard): template_name = "business/purchase/purchase_invoice-main.html" class InvoiceDetailView(InvoiceListView): template_name = "business/purchase/purchase_invoice.html" #urls.py path(r'business/<pk>/purchase_invoices/<pid>/',vw.PurchaseInvoiceDetailView.as_view(), name='purchase_invoice'), path(r'business/<pk>/purchase_invoices/',vw.PurchaseInvoiceListView.as_view(), name='purchase_invoices') What I am looking for is to inherit the ListView of Invoice from DetailView of Business i.e, from an instance of a Business i.e, all invoices of a particular Business must be listed. How to implement this like: #views.py #views.py class BusinessDashboard(BusinessOwnerRequiredMixin, DetailView): model = Business template_name = "business/business-main.html" class InvoiceListView(BusinessDashboard, ListView): model = Invoice template_name = "business/purchase/purchase_invoice-main.html" class InvoiceDetailView(InvoiceListView, DetailView): model = Invoice template_name = "business/purchase/purchase_invoice.html" But that woin't work, since I am overriding the model on each class... For the url http://example.com/business/1/invoices/1/, inside the template I must have a variable with a invoice instance. -
Django Rest Framework determine choices available from related model using JSONRenderer?
In a nested serializer using the JSONRenderer how do you determine the choices available on a ChoiceField with the choices originating from another model? class CustomerProductsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) description = serializers.ReadOnlyField(source='product.description') class Meta: model = CustomerTemplate fields = ('id', 'description', 'quantity', 'unit',) class CustomerDetailSerializer(serializers.ModelSerializer): products = CustomerProductsSerializer( source='customertemplate_customer', many=True) class Meta: model = Customer fields = ('id', 'name', 'products') read_only_fields = ('id', 'name') def update(self, instance, validated_data): ... For example, say there's a Unit model with 4 objects and a GET request returns the below JSON. When submitting a PUT request to the same endpoint in which a user would add a quantity and unit to create an order, how would you alter the serializer so that the user can determine all the available units to choose from? { "id": 1, "name": "Example", "products": [ { "id": 6183, "description": "product one", "quantity": null, "unit": 1, }, { "id": 3839, "description": "product two", "quantity": null, "unit": 4, } ] } In the BrowsableAPIRenderer there's a <select> widget that automatically displays the choices on a PrimaryKeyRelatedField but how would someone interacting with the JSONRenderer determine the available choices? -
How can I make a clickable link add items to a list?
I have a simple web interface that shows asset numbers for pieces of equipment in our company database. I have a clickable link next to the number that says Deploy and Return. What I would like to happen is when someone clicks Deploy, the asset number for that specific piece of equipment is added to a list (eventually for to a csv file for printing), along with its requisite model and serial numbers. How can I make the clickable link execute a function that takes that specific asset number next to it, searches the database for its model and serial numbers and adds them to a list? The idea is that I can click Deploy on a bunch of assets and have them on a deployment sheet that is suitable for printing. I'm new to Django, and I've been using a Mozilla tutorial for the skeleton of this site, but now I'm going off the reservation a little bit. Thanks! models.py: from django.db import models from django.urls import reverse #Used to generate URLs by reversing the URL patterns from django.contrib.auth.models import User import uuid from datetime import date class ModelInstance(models.Model): asset = models.CharField('Asset Number', max_length = 50, help_text = "Enter … -
Django queryset EXCLUDE: are these equivalent?
In Django, are these two equivalent? Cars.objects.exclude(brand='mercedes').exclude(year__lte=2000) and Cars.objects.exclude(brand='mercedes', year__lte=2000) ? I know the first one says: exclude any mercedes and exclude any car older than year 2000. What about the second one? Does it say the same? Or it does only exclude the combination of mercedes being older than year 2000? Thanks! -
No rows are getting inserted into database,using django
I am not understanding where data got missed, request are getting on to server and view but not able to save data. my task is to on click button, it should popup form and form filled up by user and submit. form to be submitted internally without changing page. models.py: class Test(models.Model): name=models.CharField(max_length=20) emailt=models.EmailField() message=models.CharField(max_length=90) views.py: from .models import Test def test(request): if request.method == "POST": if "name" in request.POST and "email" in request.POST: name=request.POST["name"] email=request.POST["email"] message=request.POST["message"] insatance=Test(name=name,emailt=email,message=message) insatance.save() Here is part to which i am totally new Ajax and modalform. HTML part: <div class="modal fade" id="modalForm" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel">Contact Form</h4> </div> <!-- Modal Body --> <div class="modal-body"> <p class="statusMsg"></p> <form role="form">{% csrf_token %} <div class="form-group"> <label for="inputName">Name</label> <input type="text" class="form-control" id="inputName" placeholder="Enter your name"/> </div> <div class="form-group"> <label for="inputEmail">Email</label> <input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/> </div> <div class="form-group"> <label for="inputMessage">Message</label> <textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea> </div> </form> </div> <!-- Modal Footer --> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button> </div> </div> </div> javascript: function submitContactForm(){ var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i; var name … -
Add querystring parameters to from class based detail view with Django
How can I modify a class based view to add querystring parameters to the view? (So that when the view response is returned, the querystring is in the address bar? class MyDetailView(DetailView): """ A detail view for retrieving a model object. """ model = MyModel def some_function_to_modify_qs(self): # do something and return modified qs for response -
How to create a personnal account in django?
I was wondering of how to create a personal account in django. For example I have two users in my project the details of one user-login cannot be seen by another...I mean User1 will have his/her personal data which will be not visible to User2... Basically,I mean to say how to differentiate datas of Users in django... Any guess?? Actually I am very much new to django. Thats why facing this difficulty.It will be real help if anyone can suggest me to solve this problem.. Thank you... -
Django rest framework how to access field in serializer
I have a model called Video class Video(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False, null=False, default='', unique=True) file = models.FileField(upload_to='videos/', blank=False, null=False) owner = models.ForeignKey('auth.User', related_name='videos', on_delete=models.CASCADE, verbose_name='') def __str__(self): return self.name + ': ' + self.file.name class Meta: ordering = ('created',) And its serializer: class VideoSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Video fields = ['name', 'file', 'owner'] I was trying to access the field in serializer in my view because I need it to do some processing: def post(self, request): serializer = VideoSerializer(data=request.data) if serializer.is_valid(): # I need the name of the file!!!!! # accessing the fields below print(serializer.name) print(serializer.file.name) # accessing the fields above serializer.save(owner=request.user) videos = Video.objects.filter(owner=request.user) return Response({'videos': videos, 'serializer': VideoSerializer(), 'style': self.style}) return Response(data=None, status=status.HTTP_400_BAD_REQUEST, template_name='videoserver/error.html') But when I make request it will report this error: AttributeError: 'VideoSerializer' object has no attribute 'name' and AttributeError: 'VideoSerializer' object has no attribute 'file' Any advice would be greatly appreicated!! -
Django + NginX proxy_pass redirect issues
I faced an issue with nginx proxy_pass to a Django app in a different server. I configured nginx server to this django: server { listen 443 ssl; server_name mydjango.com; ssl on; ssl_certificate /opt/ssl/nginx/mydjango.crt; ssl_certificate_key /opt/ssl/nginx/mydjango.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; client_max_body_size 120M; #charset koi8-r; access_log /var/log/nginx/backend.mydjango.app.log main; error_log /var/log/nginx/backend.mydjango.app.error.log error; location / { proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://backend.mydjango.app:3080/; proxy_redirect off; } } But connecting to NginX reverse proxy (https://mydjango.com) django starts redirecting and finish with a bad request changing in my browser to: http://127.0.0.1:5002 It seems I forgot some proxy header but I tried some combinations and I dont find the good one. Thanks in advance, -
Internal error when upgrading stack from cedar-14 to heroku-16
I am trying to upgrade my stack in Heroku from cedar-14 to heroku-16, and I am surprised to see errors when deploying the app, but not when running python manage.py runserver locally. [2018-09-07 09:57:37 +0000] [8] [ERROR] Error handling request /en/ Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 111, in _get_response resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 520, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLPattern '^robots\.txt$'>], [<URLPattern '^sitemap\.xml$'>], [<URLPattern '^sitemaps/static\.xml$'>], [<URLPattern '^sitemaps/destinations\.xml$'>], [<URLPattern '^sitemaps/routes_index\.xml$'>], [<URLPattern '^sitemaps/routes-(?P<orig_country>[A-Z]+)-(?P<dest_country>[A-Z]+)\.xml$' [name='routes_sitemap_index']>], [<URLPattern '^en/blog/$' [name='blog_en']>], [<URLPattern '^en/blog/(?P<slug>[A-Za-z1-9\-\(\)_]+)$' [name='blog_post']>], [<URLPattern '^../blog/.*'>], [<URLPattern '^index.*$'>], [<URLPattern '^content/cities$'>], [<URLPattern '^content/countries-and-cities$'>], [<URLPattern '^de/reisen/routen$'>], [<URLPattern '^en/travel/routes$'>], [<URLPattern '^.*grenchen.*'>], [<URLPattern '^content/imprint$'>], [<URLPattern '^en/content/imprint$'>], [<URLPattern '^content/terms$'>], [<URLPattern '^content/privacy$'>], [<URLPattern '^en/content/privacy$'>], [<URLPattern '^content/faq$'>], [<URLResolver <URLPattern list> (None:None) 'en-us/'>]], 'path': 'en/'} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/app/.heroku/python/lib/python3.6/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 … -
django file upload, file select window keeps popping up
I am using the file upload given here. The upload works fine on first load of the page (the upload field is in a modal ). If i try it again, the file select window keeps popping up on submission/cancel/close modal ,and upload doesn't seem to work. I can't find what's wrong. Pls Help. -
Visit heroku database and connect to local mysql database
I have deployed a django app in heroku. It has some log-in function and data fill-in function. May I know where do these data information stored? How could I visit them? In addition, in the django app, I have add some function that connect to local mysql database. But in the web deployed, the connection is refused. How could I deal with the problem? Thx! Sorry that I am quite new in heroku. -
How to safely access request object in Django models
What I am trying to do: I trying to access request object in my django models so that I can get the currently logged in user with request.user. What I have tried: I found a hack on this site. But someone in the comments pointed out not to do it when in production. I also tried to override model's __init__ method just like mentioned in this post. But I got an AttributeError: 'RelatedManager' object has no attribute 'request' Models.py: class TestManager(models.Manager): def user_test(self): return self.filter(user=self.request.user, viewed=False) class Test(models.Model): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(Test, self).__init__(*args, **kwargs) user = models.ForeignKey(User, related_name='test') viewed = models.BooleanField(default=False) objects = TestManager()