Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
non-www with https not woring in Heroku deployed Django App
I have deployed a django application on Heroku. I have added a custom domain from godaddy, say 'example.com'. I have added both 'www.example.com' and 'example.com' in heroku custom domains. I have added CNAME record with www as host and points to dns target given by heroku for 'www.example.com'. I own a hobby dyno, which has ACM whose statuses are OK for both domains. Now, the website works at 'https://www.example.com', 'http://www.example.com', 'http://example.com'. All these urls redirects to 'https://www.example.com'. But, 'https://example.com' is not working at all. Please give me a solution. -
How configure Django logging to file for app
I am struggling with Django logging configuration. I have one app called "api" and I want to save to file all logs from this app. When I set up a logger to django everything works fine but when I change it to my app_name it doesn't. Here is my configuration: File structure: email_api api tasks.py email_api celery.py settings logs email.log My logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logs/email.log', }, }, 'loggers': { 'api': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } tasks.py file where I logging: import logging logger = logging.getLogger(__name__) @app.task(bind=True, default_retry_delay=3, max_retries=3,) def send_email(self, data, email_id): message = create_message(data, email) try: logger.debug("Log Message Here") message.send() -
Call Django command with phrase as argument
I'm trying to run the command zappa manage staging 'run_sql --sql \"show databases\"' But I get the following error: zappa manage staging 'run_sql --sql "show databases"' [START] RequestId: dd895134-dc62-41c3-987b-3ea550af1129 Version: $LATEST [DEBUG] 2019-03-02T10:51:18.213Z dd895134-dc62-41c3-987b-3ea550af1129 Zappa Event: {'manage': 'run_sql --sql show databases'} Error: unrecognized arguments: databases: CommandError Traceback (most recent call last): File "/var/task/handler.py", line 580, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 248, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 413, in handler management.call_command(*event['manage'].split(' ')) File "/var/task/django/core/management/__init__.py", line 127, in call_command defaults = parser.parse_args(args=parse_args) File "/var/task/django/core/management/base.py", line 55, in parse_args return super().parse_args(args, namespace) File "/var/lang/lib/python3.6/argparse.py", line 1737, in parse_args self.error(msg % ' '.join(argv)) File "/var/task/django/core/management/base.py", line 61, in error raise CommandError("Error: %s" % message) django.core.management.base.CommandError: Error: unrecognized arguments: databases I tried various things like zappa manage staging 'run_sql --sql \"show databases\"' zappa manage staging 'run_sql --sql \\\"show databases\\\"' zappa manage staging 'run_sql --sql \"show\ databases\"' zappa manage staging 'run_sql --sql \\\"show\\\ databases\\\"' But all fail for the same reason: django.core.management.base.CommandError: Error: unrecognized arguments: databases\\” It looks like Django command parser believes the phrase are several options or something, but I can't figure out the way to treat it as a single argument. Based on the following Django Command: … -
Type Error when using " ..." % (...) type of string
I'm having a problem when trying to process a form in Django. The lines that are causing me trouble are the form.cleaned_data ones. Message.objects.create( object=_("Changement de profil - %s %s (%s) ") % (self.request.user.first_name, self.request.user.last_name, self.request.user.pk), author=self.request.user, receiver=admin, content=_("Bonjour, voici les nouvelles informations concernant mon profil :\n" "- %s\n" "- %s\n" "- %s\n" "- %s\n") % (form.cleaned_data["nom"], form.cleaned_data["prenom"], form.cleaned_data["telephone"], form.cleaned_data["adresse"], # str(form.cleaned_data["reaffectation"]) if form.cleaned_data["reaffectation"] != None else _("Aucune reaffectation") ) ) It's giving me this error: 'object' is an invalid keyword argument for this function However, when I checked the type of each element, it's saying that they are of type str. My initial thought was that the reverse_lasy (aka: _) was returning a different object and thus causing this error. I tried to change the cleaned data to a normal string and it didn't work either. The "object" kwargs isn't causing any trouble even though this is the same syntax so I'm kind of lost. -
Display Sub folders in drop down menu using Ajax and Django
I'm trying to display sub folders in bootstrap form, after selecting folder from another drop down. for that , i'm just trying to print data in console and ajax call is ` <script> $("#select_id").change(function () { //var url = $("#ajax_req").attr("sub-direc-url");\ajax/validate_username\ var url='subdirectories/' var id = select_id.value; //var csrf= //var csrf_token = '<%= {{csrf_token}} %>'; console.log(id) console.log("hhhhhhhhhhh") $.ajax({ url: url, type: 'GET', data: {'id':id, csrfmiddlewaretoken: '{{ csrf_token }}'}, contentType: 'plain/text', success: function (data) { console.log($("#id_direc").html(data)); } }); }); </script>` and text box code is if i select the folder from drop down menu, it's printing all the sub folders finely <div class="form-group input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-building"></i> </span> </div> <select class="form-control" id="select_id"> <option > select the folder</option> {% for i in list_dirc %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> </div> <div class="form-group input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-user"></i> </span> </div> <input name="" class="form-control" placeholder="Full name" type="text" id=id_direc> </div> -
Why i am getting error in service-worker.js while developing a pwa app
I am trying a develop a pwa-app from my Django website.But i am getting following errors:- Uncaught (in promise) TypeError: Request failed Promise.then (async) (anonymous) @ service-worker.js:16 while my service-worker.js is :- {% load static %} var dataCacheName = 'template-pwa'; var cacheName = 'template-pwa'; var filesToCache = [ '/', "./index.html", "./{%static "json/manifest.json" %}", "./{%static "js" %}", "./{%static "js/app.js" %}", "./{%static "js/jquery-3.3.1.js" %}", "./{%static "js/materialize.js" %}", ]; self.addEventListener('install', function(e) { console.log('[ServiceWorker] Install'); e.waitUntil( caches.open(cacheName).then(function(cache) { console.log('[ServiceWorker] Caching app shell'); return cache.addAll(filesToCache); }) ); }); self.addEventListener('activate', function(e) { console.log('[ServiceWorker] Activate'); e.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (key !== cacheName && key !== dataCacheName) { console.log('[ServiceWorker] Removing old cache', key); return caches.delete(key); } })); }) ); return self.clients.claim(); }); self.addEventListener('fetch', function(e) { console.log('[Service Worker] Fetch', e.request.url); e.respondWith( caches.match(e.request).then(function(response) { return response || fetch(e.request); }) ); }); While console is showing that service worker is registered.According to console,the error is at e.waitUntil -
Custom field name format in DjangoFilterBackend
Is it possible to change the field format in URL in DjangoFilterBackend? By default it is for example: ?status=active I need this: ?columnFilters[status]=active -
Django: Getting results from multiple joinned tables
I have 3 tables flotation has many lightresidues has many compositions. I'm wanting to make a view for each flotation which can access a list of light residues and a list of associated compositions. There are only ever 2-3 light residues to each flotation and the same for compositions, so manageable. I can get a flotation record and its referenced light residues, but I'm having trouble passing the lightresidue_id to get the compositions. [n.b. I know lightresidue.id is the Django way of doing things, but I opt for this way] The view code is as follows, I've hard coded for lightresidue.lightresidue_id = 17 which works, but how do I substitute this for the lightresidue.lightresidue_id = composition.lightresidue_id. def botanyoverview(request, flotation_id): flotation = get_object_or_404(Flotation, pk=flotation_id) lightresidue = LightResidue.objects.filter(flotation_id__flotation_id=flotation_id) # composition = Composition.objects.filter(lightresidue.lightresidue_id) composition = Composition.objects.filter(lightresidue_id=17) return render(request, 'dashboard/botanyoverview.html', { 'flotation':flotation, 'lightresidue':lightresidue, 'composition':composition, }) -
Error after migrate - object has no attribute "model"
I have a problem with creating models in Django. I want to create new model, so I write code: class Image(models.Model): title = models.CharField(max_length=100) image = models.ImageField() In the next step, I complete the admin.py file as: from django.contrib import admin from .models import Page, Image admin.site.register(Page, Image) In the end, I did python manage.py makemigrations , python manage.py migrate. I got this result: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myfirstapp', '0008_delete_image'), ] operations = [ migrations.CreateModel( name='Image', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('image', models.ImageField(upload_to='')), ], ), ] In the result, I did error: "AttributeError: 'Image' object has no attribute 'model'". Without class Image, my application works correcty. Does anyone know what should I do? Or can see an error, know of tips, or other ways to help? -
set' object is not reversible. I don't understand this error
I'm getting error in most of links in html page. Even after removing first link, i get error in another link. [1]: https://i.stack.imgur.com/8JfKA.png -
Django - ordering multiple models by date created
So far, this is my models.py page: from django.db import models from datetime import date from django.conf import settings class Star(models.Model): thumbnail = models.TextField() title = models.CharField(max_length = 200) description = models.TextField() star_power = models.TextField() def __str__(self): return self.title class recent_update(models.Model): title = models.CharField(max_length = 200) description = models.TextField() video = models.TextField() date = models.DateField(("Date"), default=date.today) ordered_videos = recent_update.objects.order_by('-created_date') def __str__(self): return self.title yet my terminal says that recent_updates is undefined. I need to organize the model content so that the most recent model created comes at the top of the page; the oldest model goes at the bottom of the page. -
Adding non-CMS (Django) page to Wagtail menu
I may not be understanding something obvious, but I'm struggling to add a (top-level) menu item to my Wagtail based menu that hooks to a page rendered by an included app that doesn't know about Wagtail. Ideally, it is just a normal Django TemplateView with standard urlconf, though I may need to add some custom code. If I use the custom URL in the menu editor, I get a not found from Wagtails core.serve. I've looked at snippets, wagtail hooks, RoutablePageMixin, and the custom URL in the menu editor and none seem like it accomplishes what I'm trying to do. It may well be that I'm simply misunderstanding the docs, but is there a simple example of someone doing this? The closest I've found so far is https://www.caktusgroup.com/blog/2016/02/15/wagtail-2-steps-adding-pages-outside-cms/. I've also searched https://docs.wagtail.io/en/v2.4/advanced_topics/third_party_tutorials.html to now avail. Any guidance appreciated. Thx, --Don -
How to filter MultiSelectField with django-filter
I've created filter and all works fine, but 1 filter which is MultiSelectField don't return any results.Other filter works fine, user can filter by City and by company type, but when I'm trying to filter with 3 filters then I'm getting no results. Also when I try to filter only by stack, there are no results just like django-filters couldn't see MultiSelectField. My code below models.py from django.db import models # Create your models here. from django.db import models from django.utils import timezone from django.core.validators import MinValueValidator from multiselectfield import MultiSelectField import django_filters TYPES = ( ('startup', 'Startup'), ('software_house', 'Software House'), ('e-commerce', 'E-commerce'), ('corporation', 'Corporation'), ) CITIES = ( ('warszawa', 'Warszawa'), ('poznan', 'Poznan'), ('szczecin', 'Szczecin'), ('gdansk', 'Gdansk'), ('krakow', 'Krakow'), ('wroclaw', 'Wroclaw'), ('katowice', 'Katowice'), ('gliwice', 'Gliwice') ) COMPANY_TECHNOLOGIES = ( ('php', 'PHP'), ('js', 'JavaScript'), ('ang', 'Angular'), ('java', 'Java'), ('ruby', 'Ruby'), ('ror', 'Ruby on Rails'), ('jee', 'Java EE'), ('python', 'Python'), ('django' , 'Django'), ) class company(models.Model): name = models.CharField(max_length=100, blank=False) type = models.CharField(max_length=15, choices=TYPES) workers = models.PositiveIntegerField(validators=[MinValueValidator(1)]) city = models.CharField(max_length=15,choices=CITIES) stack = MultiSelectField(max_length=25, choices=COMPANY_TECHNOLOGIES, min_choices=1) company_about = models.TextField(max_length=500, blank=False) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.name .. views.py from django.shortcuts import render … -
Django Image should be displayed but isnt
I don't understand why the image isn't being displayed, HTML <div class="features-icons-item mx-auto mb-5 mb-lg-0 mb-lg-3"> <div class="features-icons-icon d-flex"> <img src="{{ x.pic.url }}"> </div> model class Item(models.Model): title = models.CharField(max_length=200, default='item name...') desc = models.TextField(default='Description....') pic = models.ImageField(default='default.png', upload_to='item_pics') views def index(request): itemList = Item.objects.all() return render(request, 'main/items.html', {'itemlist': itemList}) settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
how to input csv file into Django
I placed a prediction model code inside views.py of Django i need to pass input data from html page to views.py. How to feed csv file into Django views.py through html page.And that csv file further used for read with pandas to proceed for my prediction model -
Default Entry in Django Model While Migrating
I want to enter default values in Django Models. Like i have create one Role Model class Role(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=100) class Meta: verbose_name = _('role') verbose_name_plural = _('roles') db_table = "role" def __str__(self) : return self.name I want to enter defualt values whenever i am migrating - makemigrations and migrate. Example data should be entered - name - Super Admin Description - This is Super Admin name - Admin Description - This is Admin name - Manager Description - This is Manager This will help me from doing manual work. Thank You. -
Django if model._meta.abstract: AttributeError: type object has no attribute '_meta'
I want to add filter in Admin View of Model in DJango. Code of admin.py file from django.contrib import admin from asset.models import Title, Album # Register your models here. class TitleAdmin(admin.ModelAdmin): search_fields = ('display_name',) pass admin.site.register( [Album] ) admin.site.register( [Title, TitleAdmin] ) Click here to see Error Screenshot ** Already Below Given Suggested Solutions and they didn't worked out: Solution 1 Solution 2 I don't know what I am missing. Please help. Thanks a lot! -
Linking to existing record on create with a many to many record
I have a many to many relationship between two models (places and tags). However, there seems to be unnecessary duplication in the tags table. For instance, when creating a new place with an exiting tag, it creates a duplicate tag with the same name and links it rather than linking the already existing tag. I thought making the name field unique on the model would help but it understandably results in the following error when running a post request: {"tags":[{"name":["tags with this name already exists."]},{"name":["tags with th is name already exists."]}]} Serializer class PlaceTagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tags fields = ('name',) class PlaceSerializerPost(serializers.ModelSerializer): tags = PlaceTagSerializer(many=True) class Meta: model = Place fields = ('title', 'lat', 'lon', 'tags', 'featured_image_url', 'created_at') def create(self, validated_data): tags_data = validated_data['tags'] """ Tags need to be deleted otherwise the place object will not save as they need to be handled separately. """ del validated_data['tags'] place = Place.objects.create(**validated_data) for tag_data in tags_data: place.tags.get_or_create(place=place, **tag_data) return place Model class Tags(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class Meta: ordering = ('name',) class Place(models.Model): title = models.CharField(max_length=800) lat = models.DecimalField(max_digits=20, decimal_places=10) lon = models.DecimalField(max_digits=20, decimal_places=10) featured_image_url = models.CharField(max_length=2000) created_at = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tags) live = … -
Adding 2fa to a django project
I'm trying to add 2fa to my Django site. I adopted this library. My current login form looks something like that: if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: messages.error(request, "Invalid username or password") else: messages.error(request, "Invalid username or password") But from here i don't really know how to proceed and how to integrate the library into this login form. Can someone give me some help, a direction or an already existing example of how to implement it? Thanks in advance! -
Django URL Path Issue
I currently have a template folder with 2 different HTML files (help.html and users.html). I'm having issues accessing both pages with my current path setup: mysite urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('help/', include('AppTwo.urls')), path('users/', include('AppTwo.urls')), path('admin/', admin.site.urls), ] AppTwo urls from django.urls import path from . import views urlpatterns = [ path('', views.help, name='help'), path('', views.users, name='users'), ] I know I'm missing something here as I am unable to generate views for both paths when I launch the server. The Django docs just seem to show examples of a single page or examples with variables. -
run parallel process referring to django db
I have a separate module where my telegram bot is running. I need it to refer to django db, and do some changes there. I know I can run it as: python manage.py shell < mybotmodule.py But I guess it is not correct to run this in production. When I try to set an environmental variable (DJANGO_SETTINGS_MODULE) it still does not work (an error reports that django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. What is the right way to run a process that depends on django? -
URL folder system Django Python
How is it possible to move through the folders using url like in Dropbox. Example: i have an url to file site_name/home/path1/path2/file How i can take the path1/path2/file as parameter from url in Django? Or the only way is to use GET parameters as PATH to file site_name/home?path=path1/path2/file? -
Import a static HTML website to Django CMS
I have designed and coded a website (with bootstrap 4) and now I would like to import it in Django CMS so the client can edit the content. Any tips or guide that helps me to achieve this? Thanks a lot -
Django use marksafe right
i have a templatetag based filter to fold-up a text field but for some reason the text is not formated right. currently it looks like that: H e l l o t h i s is s o m e n e w t e x t a n d a l i n e s b r a k e but is should be like that Hello this is some new text and a lines brake filter.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() import re readmore_showscript = ''.join([ "this.parentNode.style.display='none';", "this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';", "return false;", ]); @register.filter def readmore(txt, showwords=15): global readmore_showscript words = list( escape(txt)) #words = re.split(r' ', escape(txt)) if len(words) <= showwords: return txt # wrap the more part words.insert(showwords, '<span class="more" style="display:none;">') words.append('</span>') # insert the readmore part words.insert(showwords, '<span class="readmore">... <a href="#" onclick="') words.insert(showwords+1, readmore_showscript) words.insert(showwords+2, '">more</a>') words.insert(showwords+3, '</span>') # Wrap with <p> words.insert(0, '<p>') words.append('</p>') return mark_safe(' '.join(words)) readmore.is_safe = True any idea how to get clean output content here. thanks in advance. -
How to fill the 'sender' automatically when sending a message to another user? CBV
I know that I can use 3rd party messaging libraries, but I want to learn how to make my own. I've been struggling to automatically set the sender in my CreateMessageForm. My error code: __init__() got an unexpected keyword argument 'sender' Forms class CreateMessageForm(forms.ModelForm): reciever = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control form-control-sm','placeholder':'Send to'})) title = forms.CharField(max_length=20, widget=forms.Textarea(attrs={'class':'form-control form-control-sm', 'placeholder':'Enter message subject', 'rows':'1'})) msg_content = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control form-control-sm', 'placeholder':'Writing your message', 'rows':'10'})) class Meta: model = Message fields = ( 'sender', 'reciever', 'title', 'msg_content', ) def __init__(self, *args, **kwargs): sender = kwargs.pop('sender') # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole super(CreateMessageForm, self).__init__(*args, **kwargs) View class MessageCreateView(CreateView): model = Message fields = ['sender', 'reciever', 'title', 'msg_content'] def get_form_kwargs(self): """This method is what injects forms with their keyword arguments.""" # grab the current set of form #kwargs kwargs = super(MessageCreateView, self).get_form_kwargs() # Update the kwargs with the sender_id kwargs['sender'] = self.request.user.id return kwargs Models class Message(models.Model): sender = models.ForeignKey(User, related_name="sender", on_delete=models.CASCADE) reciever = models.ForeignKey(User, related_name="reciever", on_delete=models.CASCADE) title = models.CharField(max_length=20) ... I've looked at other threads, but wasn't able to fix it. I tried following this __init__() got an unexpected keyword argument 'user' How can I fix this so that my form automatically …