Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Service Workers: "a redirected response was used for a request whose redirect mode is not follow" error
I've been trying to build a progressive Django Web App with a service worker and django-pwa. Everything seems to work fine, but whenever I load the page, turn on offline mode in Chrome, and reload, I get this error: "The FetchEvent for "https://haverford.getdibs.app/login/?redirect_to=/dashboard/" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow"". Now I've seen that someone else came into a seemingly similar problem here, but I don't quite understand what's going on in the answer. I think I need to set the redirect mode to "follow" for a request that I make with my fetch, but I'm not sure how to do that. Here is my service worker: var staticCacheName = "django-pwa-v" + new Date().getTime(); var filesToCache = [ '/offline', ]; // Cache on install self.addEventListener("install", event => { this.skipWaiting(); event.waitUntil( caches.open(staticCacheName) .then(cache => { return cache.addAll(filesToCache); }) ) }); // Clear cache on activate self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(cacheNames => { return Promise.all( cacheNames .filter(cacheName => (cacheName.startsWith("django-pwa-"))) .filter(cacheName => (cacheName !== staticCacheName)) .map(cacheName => caches.delete(cacheName)) ); }) ); }); // Serve from Cache self.addEventListener("fetch", event => { event.respondWith( caches.match(event.request) .then(response => { return response || fetch(event.request); … -
Append a link using ajax in django
I have read through the internet to find out the best solution to pass a django link in ajax. Bellow is a django template link to remove an object from a manytomany relationship using ajax call. {% for objects in allobjects %} <div class="products"> {{objects.title}} <a data-href="{% url 'app:removeitem' slug=objects.slug %}" >Revomove</a> </div> </html> My removeitem view def RemoveItem(request,slug): #calling the function which returns user cart object cart=Cart_object(request) product=Product.objects.get(slug=slug) RemoveItem=False if request.is_ajax(): if request.user.is_authenticated: cartinstance=Cart.objects.filter(user=request.user).first() if cartinstance: cartinstance.products.remove(product) RemoveITem=True #converting the available products in user cart object to jason prod=[] for x in cart.products.all(): prod.append({'title':x.tittle}) data={'products':prod,"image":x.image.url} return JsonResponse(data) url.py url(r'^Remove_item/(?P<slug>[\w-]+)',views.RemoveItem,name='remove_item'), here is my ajax $(document).ready(function(){ $('a').click(function(e){ e.preventDefault() var this_=$(this) var dataUrl=this_.attr('data-href') $.ajax({ url:dataUrl, method:"GET", data:{ }, success:function(data){ var cartbody=$('.cartbody') $.each(data.products,function(index,value){ cartbody.prepend("<tr> <td > <img src='"+value.image+"'>"+ value.title+ "</td>") } } }) }) }) So the question is, how can i get the removeitem url for each product as a jason string and pass it over to an ajax call. Please i need help. Thanks in Advance -
Django Allauth alternative?
Django 2.1 Python 3.6 I have begun to implement djanog alllauth because I've heard a lot of good things about it, however I just saw on an issue page on github that it isn't being maintained anymore. Should I be worried about this? Is there an alternative authentication app that I should be using instead? I'm using it for the login, logout, password change, email verification and possibly social authentication. https://github.com/pennersr/django-allauth/issues/468 -
Django Python Show functions in html
Let's imagine that i have this in the models: def show(): print("Hello bro") And i want to show that function on my html page, how woulded it? -
Python, Django 2.1 - suggestion and guidance please
A very good evening to Everyone. I am a frontend 3D developer well versed with Python and JavaScript. Recently I created a frontend application for interior designing based on webgl. I now want to invest my time in making it a SAAS application using Django. Well my experience with Django is minimal with only experience doing a to-do list based on a tutorial, lol. The frontend of the app is only part (~30%) of the final goal. The product is aimed at manufactures and freelancers in interior designing and should use subscription model. Based on the subscription plans the abilities vary. The main vision is to help manufactures in handling projects with designers both in-house and by employing freelancers. Technically this translates to user types who are 1) individuals, 2) groups, and 3) subgroups. Also there are assets(meshes, textures) that are available as private and public access. One possibility in the roadmap is including the ability of groups to be able to White label the app (custom domain, Logo etc). Finally, the last part of the vision is social media and I am planning to use LinkedIn for this purpose. Coming to my experience with Django is quite minimal but … -
Python how to iterate from an array of objects and use key values to update multiple records at once
Python how to iterate from an array of objects and use key values to update multiple records at once. I wanted to update multiple rows in the table where companyid = company and applicant_id = applicant as you can see company and applicant value in the json and set attached_document_ins.is_viewed equal to the checked value based on the task id. https://imgur.com/a/nttq6XT(table rows) code def post(self, request): data = request.data print("Response Data :" , data) try: for item in data['tasklist']: company = item['company'] applicant = item['applicant'] hey = item['checked'] attached_document_ins = DocumentTask.objects.filter(company=company , applicant = applicant) for attached_document_ins in attached_document_ins: attached_document_ins.is_viewed = True attached_document_ins.save() return Response("Success", status=status.HTTP_200_OK) except DocumentTask.DoesNotExist: return Response("Failed.", status=status.HTTP_400_BAD_REQUEST) data { 'tasklist':[ { 'company':6, 'checked':True, 'files':[ ], 'applicant':159, 'id':35, 'task':'s' }, { 'company':6, 'checked':True, 'files':[ ], 'applicant':159, 'id':36, 'task':'ss' }, { 'company':6, 'checked':True, 'files':[ ], 'applicant':159, 'id':37, 'task':'sss' } ] } -
Sharing session across different top level domains with custom middleware in Django
I have 3 different TLDs, using a single django project. To help deal with multiple domains I'm using django-hosts. As far as the content and function of the sites are concerned, there's a staff site (staff.com) that's specifically used by publishers to publish and manage content, it's basically akin to an admin site, albeit a lot more user friendly. Then there are 2 different sites for customers, let's say musicstuff.com and videostuff.com. These two share couple of applications like blog, forums, content pages, etc. Since all 3 sites use different domains I have to find a way to deal with sessions. It needs to have a single login page, with ability to share cookies between all the sites and their respective subdomains. I have a following custom middleware: from django.conf import settings class CrossDomainSessionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if response.cookies: host = request.get_host() if host not in settings.SESSION_COOKIE_DOMAIN: if host in settings.ALLOWED_HOSTS: domain = '{domain}'.format(domain=host) for cookie in response.cookies: if 'domain' in response.cookies[cookie]: response.cookies[cookie]['domain'] = domain return response The goal there is to replace the domain in the cookie with one from the site that's being used, which must be listed in … -
AWS security group and Django Email SMTP TLS port 587
I am running Django on AWS Lambda with Zappa. I have AWS Lambda set in a VPC and I have an EC2 NAT Instance in the same VPC. The NAT Instance security group takes inbound connections from by Lambda subnets (through HTTPS and HTTP) and outbounds to the public internet. This way, my Django app can communicate with the public internet if it needs to send Push Notifications to Apple Push Notification services. One thing that does not work is sending emails from Django. It works in development but not on AWS Lambda. I send emails with SMTP using port 587, and I use TLS. I figured I had to add Inbound rules to my NAT Instance security group. The problem is I can't add inbound SMTP with port 587. Here are screenshots to show this. When I select SMTP, the port number is fixed at 25 and greyed out so I can't modify the port to 587. I looked at other options in the list but none of them set the port number to 587. I even tried 'Custom TCP Rule' and setting the port to 587 but that does not work. Emails are not sending! -
How to Download ExcelDownload in Django
How to Download ExcelDownload in Django my modules.py **modules.py** def getAnswerStats(year, month): answer_stats = Lawyer.objects.raw(''' select select * from ( select y.lawyer_name, DATE_FORMAT(y.register_date, '%Y-%m-%d') as reg_date, (select count(counsel_answer_idx) from counsel_answer where lawyer_idx = y.lawyer_idx and DATE_FORMAT(register_date, '%Y%m') = '%s') as cnt, (select count(counsel_answer_idx) from counsel_answer where lawyer_idx = y.lawyer_idx and DATE_FORMAT(register_date, '%Y%m') = '%s' and week(register_date,5) - week(DATE_SUB(register_date,INTERVAL DAYOFMONTH(register_date)-1 DAY),5) = 1) as cnt1 where y.lawyer_status = 'N' ) A order by A.cnt desc ''', (year+month, year+month, year+month, year+month, year+month, year+month, year+month)) return answer_stats admin_view.py @csrf_exempt def answer_stats_excel(request): if request.method == "POST": year = request.POST.get("year") month = request.POST.get("month") print(year+month) stats_data = getAnswerStats(year, month) return redirect('/admin/visual/answer_stats') The stats_data is retrieved from the module. answer_stats.html <form id="boardFrm" name="boardFrm" enctype="multipart/form-data" action="/admin/visual/answer_stats_excel" method="post"> <div class="form-inline"> <select class="form-control " style="width:49%" id="year" name="year"></select> <select class="form-control " style="width:49%" id="month" name="month"></select> </div> <button type="submit" style="margin-top:20px;" name="button"> excel down</button> </form> ExcelDownload button here How do I download the Exceldown button when I click it? -
Adding table gridlines to tables in django-tables2
Django-tables2 relies on bootstrap templates with no gridlines. It relies on the django-tables2/boostrap4.html template. I'd like to add lines in-between rows and categories like this style/design: https://material.io/design/components/data-tables.html#anatomy Is there an easy way to do this with django-tables2 and a nice template to use? -
Calling a function that is in the same class - Django
Calling a function that is in the same class - Django I'm confused. I can not make this work on my project. However, it works in a separate python-only file. Class Test(): def trocaPlano(self, assinatura_id): payload = { "id": assinatura_id, } print(payload) def update(self, assinatura_id, data): ... self.trocaPlano(assinatura_id) ... Call Test.update(self, assinatura_id=2, data=form.cleaned_data) Nothing happens and displays no error. -
When I run manage.py run server it return back to directory and get stuck
enter image description here When I run manage.py run server it return back to directory and get stuck -
Hi guys, im new to django i want to display the value of ChoiceField
there is no error but there's no value/display of category in the template forms.py : class UploadwContentForm(forms.ModelForm): TYPE_OF_FILE_CHOICES = ( ('CATEGORY 1','CATEGORY 1'), ('CATEGORY 1','Catergoty 2'), ('CATEGORY 1','Catergoty 3'), ('CATEGORY 1','Catergoty 4') ) title = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder' : 'Enter your title here:' } ) ) category = forms.ChoiceField(widget=forms.Select(attrs={ 'class' : 'btn btn-danger dropdown-toggle' }), choices=TYPE_OF_FILE_CHOICES) views.py: def uploadlist(request): uploadwcontent = UploadwContent.objects.all() return render(request, 'upload/uploadlist.html', { 'uploadwcontent' : uploadwcontent }) template_views.py {% for uploadwcontent in uploadwcontent%} <td> {{uploadwcontent.title}}</td> <td>{{ uploadwcontent.author}}</td> <td> <a href="{{ uploadwcontent.pdf.url}}" class="btn-primary btn-sm "target="_blank"> Download PDF </a> </td> <td> {{form.get_category_display}} </td> </tr> {% endfor %} -
How do I write a Django query that uses a complex "on" clause in its inner join?
I'm using Django, Python 3.7, and PostGres 9.5. I have these models ... class Article(models.Model): ... label = models.TextField(default='', null=True) class Label(models.Model): name = models.CharField(max_length=200) I want to write a Django query that retrieves all the articles whose label contains a name from the Labels table. In PostGres, I can structure my query like so ... select a.* from myapp_article a join myapp_label l on a.label ilike '%' || l.name || '%'; but I have no idea how to pull this off in Django on account of the "on" clause and "ilike". How do I pull this off? -
How do I customise url in RedirectView
I'm using Django 1.5, trying to capture a param from url, then use this param to query an article id and redirect user to that article. Can I not specify new url in url.py and do something like below? But it just appends the url I want to use to the end of current url url.py url(r'^external/(?P<external_id>\d+)/$', myView.as_view(), name='external-view') views.py class MyView(RedirectView): def get_redirect_url(self, **kwargs): external_id = kwargs['external_id'] article_id = Article.objects.get(external_id=external_id).id domain = Site.objects.get_current().domain new_url = '{}/article/{}'.format(domain, article_id) return new_url -
Heroku: ModuleNotFoundError :No module named 'requests'
I am trying to deploy a django program to Heroku. The application runs successfully on my local machine, which uses Anaconda and python 3.5. I cannot get it to push to heroku. Upon the command >git push heroku master remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.6.8 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.6.2 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 2018.5.18… remote: Installing dependencies from Pipfile.lock (958efe)… remote: -----> Installing SQLite3 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) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 978, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 961, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 948, … -
Update Smokeping config file with Python
I'm trying to update/add host on the Smokeping config file using a Web UI and Django, can we use this with python script? Sample: -
Get multiple models in single QuerySet ordered by timestamp
I'm working on a table consisting of all events performed on a user despite that these events are represented by 4 different models. The models are: WebhookSubscription WebhookEvent TokenRefresh LogEvent I want these to all be visible to the user in their dashboard, but in a single table ordered by timestamp. I could do a single query for each model then append to a dictionary which I'll then sort by date, however, I don't want to go against a native solution if there is one (and I don't believe this is an edge case so I could foresee it). Is there a native way of retrieving multiple models in a single QuerySet? -
How is the Django view class executed?
I have a simple question to ask. How is the class executed defined the views.py? For example, if I have the path defined like the following, I assume that the snippet, 'views.PostListView.as_view()', is executing the PostListView defined in the views.py. Am I right? urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('about/', views.AboutView.as_view(), name='about'), path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'), ] -
Why Django migrations.AlterModelOptions drops views?
I have the following table view: class CPUResourceView(PolledResource): quantity = models.SmallIntegerField() running = models.BooleanField() class Meta: db_table = 'cpu_view' verbose_name_plural = "Resources View: CPU" managed = False I changed the verbose_name_plural and ran makemigration which generated the following: migrations.AlterModelOptions( name='cpuresourceview', options={'managed': False, 'verbose_name_plural': 'Resources View: CPU'}, ) But when I run migration it drops the view, why? -
django slug in function base view
im just a student. I have another post like this code but just ignore that. I'm experimenting in rendering views. Now i want to know how to use my already existing code with slug.. here's is my views.py that build with id, def BookDetail(request, id): most_recent = Book.objects.order_by('-timestamp')[:3] book= get_object_or_404(Book, id=id) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={ 'id': book.pk })) if request.user.is_anonymous: user_membership = None else: try: user_membership = Customer.objects.get(user=request.user) except Customer.DoesNotExist: user_membership = None context = { 'user_membership': user_membership, 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) and here's my new book model that returning slug name, class Book(models.Model): slug = models.SlugField(unique=True, help_text="Enter BIC Code", null=True) title = models.CharField(max_length=200) #more fields after this timestamp = models.DateTimeField(default=timezone.now) activeReference = models.ManyToManyField(Membership) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs={'slug': self.slug}) @property def get_comments(self): return self.comments.all().order_by('-timestamp') @property def pages(self): return self.page_set.all() class Page(models.Model): slug = models.SlugField(max_length=50) book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True) preview = models.FileField(upload_to='book_content', validators=[pdf_file_extension], help_text="PDF File Only") def __str__(self): return self.slug def get_absolute_url(self): return reverse('page-detail', kwargs={ 'book_slug': self.book.slug, 'page_slug': self.slug }) i hope you can help me. -
How to connect postgres container with django container?
I run postgres and django using docker So I have two container. It's postgres and django container. I want to connect postgres container in django container. How can I do this? my django dockerfile is like below. FROM python:3.7.2-alpine RUN apk update && apk add postgresql-client && rm -rf /var/cache/apk/* COPY . ./myproject WORKDIR /myproject RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and I'm using postgres officail dockerfile. my django databases settings is as follows. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } then I run two containers as follows. django docker run -p 8000:8000 --rm --name mydjango me/mydjango:latest postgres docker run -p 5432:5432 --rm -v /vol:/var/lib/postgresql/data --name postgres postgres:latest Also I create docker network. docker network connect mynetwork mydjango docker network connect mynetwork postgres But page is not shown when I connect to localhost:8000. I think django container can't connect postgres container. When I launch postgres not using docker. It works. django can conenct to local postgres. How can I connect django container to postgres container? -
Django Apache Setup issue
I am using trying to deploy an app in my server. I have the following configuration Django 1.10 Apache 2.4 Red Hat Enterprise Linux Server release 7.6 (Maipo) I followed the instructions which was mentioned under Django documentation https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/modwsgi/ My Apache config look like this WSGIPythonHome /usr/local/test WSGIScriptAlias / /usr/local/app/test/test/wsgi.py WSGIPythonPath /usr/local/app/test <Directory /usr/local/app/test/test> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /usr/local/app/test/static <Directory /usr/local/app/test/static> Require all granted </Directory> Alias /media /usr/local/app/test/media <Directory /usr/local/app/test/media> Require all granted </Directory> But the application doesn't seem to be working. Instead it show you don't have permission to view '/test' error 403 error . -
Django post with bootstrap tags input
I want to create post with tags. using bootstrap tags input. In view I create new tag but it displays that "tag" is not a valid value. . It doesnt validate form, But I see new tag created good in db. 2 Problem) When I refresh page all created tags are in selection and all autoselected. If I create post now, all tags will be connected good. and post will be posted with all tags. class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, blank=True, unique=True) body = RichTextField() date_pub = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField('Tag', blank=True, related_name='posts') view def post(self, request): bound_form = self.model_form(request.POST) tags = request.POST.getlist('tags') for tag in tags: objs, created = Tag.objects.get_or_create(title=tag, slug=tag) if bound_form.is_valid(): post = bound_form.save(commit=False) post.author = request.user post.save() post.tags.add(objs) post.save() new_obj = bound_form.save() return redirect(new_obj) return render(request, self.template, context={'form': bound_form}) tags are select multiple field for bootstrap tag input I just connected scripts here is html output with validation error -
Django doesn't create triggers for test database
I've added SearchVectorFields to my Django models and triggers to my Postgres DB, as indicated here. It works well, but I'm adding some unit tests, and the indexed search fields are not populated in the test database. The creation of the triggers is done inside a Python script, with a migration running that script. Any idea what can have gone wrong ?