Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resoponsive django ckeditor
I'm already downloaded ckeditor for my blog web appicationa But when i visit this site by mobile it's look very bad because it's not responsive how can i convert this into responive design... CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'height':500, 'width':450, 'extraPlugins': 'codesnippet', 'toolbar_Custom': [ ['Bold', 'Italic','Image', 'Underline'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source','codesnippet'] ] }, 'special': { 'toolbar': 'Special', 'wdith':100, 'toolbar_Special': [ ['CodeSnippet','Youtube'], ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink',], ['Image','Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ],'extraPlugins': 'codesnippet', } } -
Why are migrations files often excluded from code formatting?
We're applying Black code style to a django project. In all the tutorials / examples I find, I keep seeing django's migrations files excluded from the linter. But to my mind, these are still python files. Sure, django may not autogenerate them to meet the Black spec. But it's not like developers always write their code to meet Black spec... that's what linting is for! Why are these pythons different to all the other pythons?! NB I'm aware of the possibility of changing an already-applied migration if you've got pre-existing migrations - this requires care on first application (as does first application to the rest of the codebase, frankly) but surely isn't a reason not to do it? -
Is it a way to change translation for multilingual project in django like this except using django-rosetta?
Hi I want something like this in my django project admin page. Is there any package that can do this for me except django-rosetta? -
How to disable django models from escaping regex string? [duplicate]
I have one django model which stores regex text along with other fields. When i save the model from django admin the regex is correctly saved (without extra escape) in the database (sqlite) Data in sqlite DB broswer However, when i query the model i get regex escaped. Regex from model Requesting help to get it unescapped (to original regex text) -
Rich text Editor suggestion for a Note making Application
I am building a notemaker application with Django and I want suggestion for a Rich text Editor that all my users can use. Initally, I was drawn towards CKEditor, however it turns out that it is best suited for admin page. For other users to use image upload features, they have to be set as is_staff=True. In my opinion, that is not a wise decision.(Any one who disagrees?) Now I am considering Tiny MCE and also Quill JS. Tiny MCE doesn't seem to have a feature where users can upload an image directly from their storage and Quill JS doesn't seem to have a trustworthy django library. Kindly suggest me a Rich text Editor for my Note making application. -
How to use display Django's messages via the alert function in JavaScript
I want to display messages via Django's messages framework as an alert. views.py if request.method == 'POST': form = CreatePost(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) user = User.objects.get(username=username) if user.post_set.filter(title=new_form.title).exists(): # if the post exist with the same title under the same author do not add the post. messages.error(request, 'Blog already present with the same title') else: new_form.author = user form.save(commit=True) messages.success(request, 'Blog posted successfully') return redirect('blog-home') else: messages.error(request, 'Form not valid! Try again') only part of the file added. .html file <script> var message = '{{ messages }}' </script> <button type="submit" class="submit" onclick="messageFunction()">Submit</button> <script> function messageFunction(){ //console.log({{messages}}) alert(messages); } </script> I tried to do something but I couldn't able to complete that. Actually I want to access the messages variavle via the js to display dynamic messages accordingly. -
Django: Using Func for unnest array of dicts and apply filters
I have a model same as below: class Work(models.Model): sub_items = ArrayField(JSONField(null=True), null=True, default=list) ... The data on the sub_items store like below: [ { "dt": 159565990, "task": { "description": "This is a task...", "progress": 75 } }, { "dt": 159565990, "task": { "description": "This is a task...", "progress": 100 } }, { "dt": 159565990, "task": { "description": "This is a task...", "progress": 80 } }, { "dt": 159565910, "task": { "description": "This is a task...", "progress": 100 } }, { "dt": 159565920, "task": { "description": "This is a task...", "progress": 100 } }, { "dt": 159565940, "task": { "description": "This is a task...", "progress": 20 } }, { "dt": 159565950, "task": { "description": "This is a task...", "progress": 50 } }, { "dt": 159565972, "task": { "description": "This is a task...", "progress": 10 } }, { "dt": 159565989, "task": { "description": "This is a task...", "progress": 100 } }, ] Every array item contains "progress" key in dept and I need query for getting all items that progress is equal to 100. I try fetching data by using below query: Work.objects.annotate(xyz=models.functions.Cast(models.Func(models.F('history'), function='unnest'), JSONField())).filter(xyz__message__progress=100) But django can't handle this query by below prompt: *** django.db.utils.NotSupportedError: set-returning functions are not allowed … -
Reason for getting Exception Type:ValueError
In my eCommerce project, I have an issue where I am adding an item to the cart and in the order summary when I change the quantity of this item, I get Exception Type:ValueError and the exception value is The view core.views.add_to_cart didn't return an HttpResponse object. It returned None instead. for an unknown reason although when I return and refresh the page the quantity is correctly updated I have been battling it for a while and trying to fix it. Here are the views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'order_summary.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item_qs = OrderItem.objects.filter( item=item, user=request.user, ordered=False ) item_var = [] # item variation if request.method == 'POST': for items in request.POST: key = items val = request.POST[key] try: v = Variation.objects.get( item=item, category__iexact=key, title__iexact=val ) item_var.append(v) except: pass if len(item_var) > 0: for items in item_var: order_item_qs = order_item_qs.filter( variation__exact=items, ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user=request.user, ordered=False ) order_item.variation.add(*item_var) order_item.save() order_qs = Order.objects.filter(user=request.user, … -
Django 500 Error when Debug=False on Heroku
I have my app up and running on heroku and everything is working well with Debug mode set to true. When I set DEBUG to False I get a 500 Internal Server error on all my website's pages. Running the collectstatic command works fine and ALLOWED_HOSTS is set to ['*'] and have followed all of Heroku's steps for configuration. Any suggestions as to what could be the issue? Setting up my admin email does not send me any error reports and the heroku logs list a 404 error for getting my page icon and then a 500 error from the app. -
Django Sessions for add to cart
I am building a pizza ordering site. Okay, now I need help setting up sessions for my cart. So right now whenever a user clicks add to cart in the modal window that pops up when any item is clicked saves it to a div. And that div displays the cart items. Now how do I save it to sessions so whenever that user logins, django pulls up the relevant cart info. Any simple solution would do! I have attached a video demonstrating how my site is now. https://youtu.be/8aOifbdg0e8 Thank you so much in advance! -
Django, separate settings files with a custom part
I'm trying to setup Django with two separate settings files, to be selected via the command line parameter --settings, and that (obviously) must have a common file they both use for the common variables. So I have the file settings_local.py: DEBUG = True from . import settings And I expected that then in settings I would have been able to access DEBUG. I found no way at all to do that. I've tried to use globals() in both files, I've tried to use global in both, nothing seems to work. Obviously I cannot import settings_local from settings: the entire point of this setup is to also have a settings_public and call either one from the command line. settings itself should be agnostic to it. I'm also planning to add some kind of control check to ensure settings is not called directly, such as: try: DEBUG except NameError: raise ValueError( "This file shouldn't be used directly." ) But the exception is always raised, since DEBUG doesn't seem to appear in settings. I reiterate, even using globals() in both files does not work. Searched a lot online, couldn't find anything at all that could help me in this very specific situation. I've … -
Can I use Django app to create a project which connects a Database and does CRUD?
I am thinking of a project where I connect to a Database and then do CRUD operations on a database. I have created python core modules, but I want a front-end for the same and want to report and allow users to provide the operations on a button-click. can you please help how can I add my modules to Django app and all the actions are recorded in the Django models itself? PS: I made a quiz app a year ago and I forgot Django now. :( Thanks in advance! -
how to combine two tables in django
There are two tables Hookahs and tobacco for example and for the basket model, you need to combine these two models, help For example: class Hookah(model.Model): name = models.Charfield() description = ..... price = ....... class Tabacco(model.Model): name = models.Charfield() description = ..... price = ....... and OrderItem model: class OrderItem(model.Model): and here I need to pass the top two models, as a product, how to do it? i.e. combine Hookah and Tabacoo into one please help me -
Django sweetify
I already read the documentation about https://github.com/Atrox/sweetify-django but I don't understand clearly, I already download and import requirement of sweetify in Django. I just want that if the record is updated the popup message (sweetify) will appear. def studentrecords(request): if request.method == 'POST': update = StudentsEnrollmentRecord.objects.get(id=id) update.Section = s update.save() sweetify.success(request, 'You did it', text='Your Form has been Updated', persistent='Hell yeah') return render(request, 'Homepage/selectrecord.html') this is my html {% load sweetify %} {% sweetify %} <form method="post" action="/studentrecords/" enctype="multipart/form-data">{% csrf_token %} <table> {% for student in myrecord %} <tr> <td>Control #</td> <td><input type="text" name="id" value="{{student.id}}"></td> <td><input type="submit"></td> </tr> <tr> <td>Name: </td> <td><input type="text" value="{{student.Student_Users.Firstname}} {{student.Student_Users.Lastname}} {{student.Student_Users.Middle_Initial}}"></td> <td>Course/Track</td> <td><input type="text" value="{{student.Courses}}"></td> </tr> <tr> <td>Education Level: </td> <td><input type="text" value="{{student.Education_Levels}}"></td> <td>Strand: </td> <td><input type="text" value="{{student.strands}}"></td> </tr> <tr> <td>Section: </td> <td> <select name="section"> <option value="{{student.Section.id}}">{{student.Section}}</option> {% for sections in section %} <option value="{{sections.id}}">{{sections.Description}}</option> {% endfor %} </select> </td> <td>Payment Type: </td> <td><input type="text" value="{{student.Payment_Type}}" class="myform"></td> </tr> {% endfor %} </table> </form> my settings.py INSTALLED_APPS = [ #my apps …. 'sweetify' ] SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2' I didn't receive any error , but no popup message appear (sweetify) -
how to choose django rest framework views
Hi Guys I had a little confusion about choosing views for developing endpoints using django rest framework. class based views and viewsets and functions based views among these which one is better for longer run. -
Django save inline formset from template view
Have a master-detail objects with a one-to-many relationship: from django.db import models class Master(models.Model): field1 = models.CharField(max_length=100) field2 = models.IntegerField() class Detail(models.Model): field3 = models.IntegerField() field4 = models.IntegerField() field5 = models.IntegerField() master = models.ForeignKey(Master, on_delete=models.CASCADE) For details, I have a ModelForm and an inline formset: from django import forms from .models import Master, Detail class MasterForm(forms.Form): field1 = forms.CharField(label='Field 1', max_length=100) field2 = forms.IntegerField(label='Field 2') class DetailsForm(forms.ModelForm): class Meta: model = Detail exclude = () DetailsFormset = forms.inlineformset_factory( Master, Detail, form=DetailsForm, extra=1) I have a template view: class MasterDetailsView(TemplateView): template_name = 'app/master_detailsview.html' def post(self, request, *args, **kwargs): print('IN POST!') details_formset = DetailsFormset(request.POST) if details_formset.is_valid(): print('FORMSET VALID!') Master.objects.get(pk=self.kwargs['pk']).save() details_formset.save() else: print('ERRORS!') print(details_formset.errors) return HttpResponseRedirect(self.request.path_info) def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs['pk'] master_instance = Master.objects.get(pk=pk) context['master_instance'] = master_instance if self.request.POST: context['details_formset'] = DetailsFormset(self.request.POST, instance=master_instance) else: context['details_formset'] = DetailsFormset(instance=master_instance) return context and the template: {% extends 'base.html' %} {% block contents %} <table class="table table-bordered"> <tr> <th>Field 1</th> <th>Field 2</th> </tr> <tr> <td>{{ master_instance.field1 }}</td> <td>{{ master_instance.field2 }}</td> </tr> </table> <hr/ > <form action="" method="post"> {% csrf_token %} {{ details_formset.as_p }} <input type="submit" value="Save" /> </form> <hr/ > {% endblock %} The error I get in the console: [{'master': ['The … -
how to derive values from foreign key field? django
model.py class Authors(models.Model): name = models.CharField(max_length=50) class Books(models.Model): date_pub = models.DateField() name = models.CharField(max_length=50) author = models.ForeignKey('Authors') I need to derive the names of authors from a foreign key, but the Books.objects.all().values_list('author', 'name') command infers the id from the Authors model. how to derive author names from the Books model -
Not enough values to unpack expected two got one
whenever i submit this form, i get an error saying "ValueError: not enough values to unpack (expected 2, got 1)" This is the code for views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultView(generic.DetailView): model = Question template_name = 'polls/results.html' def votes(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', {'question':question, 'error_message': "You didn't select a choice",}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:resullts', args=(question_id,))) And the code for details.html <p>{{question.question_text}}</p> {% if error_message %}<p>{{error_message}}</p>{% endif %} <form action="{% url 'polls:votes' question.id %}" method="POST"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}" > <label for="choice{{forloop.counter}}">{{choice.choice_text}}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> please help me out -
Scheduling crontabs in django python
I have created a app billing using django and I would like to get the month bills by every month and i have tired crontab in windows but its not working can anyone suggest what to do, -
Include sensitive environment variables to AWS EB Django app
I am deploying a django app to AWS Elastic Beanstalk and initially I am defining my environment variable in .ebextensions/django.config Some of those variable are sensitive and I don't want to push them to Git, so I want to encapsulate those variables in a single file (for example: .env) that will not be pushed to Git. Plan A: A way to include .env in my config file, but I didn't find a way to do it supposedly like: option_settings: aws:elasticbeanstalk:application:environment: include .env aws:elasticbeanstalk:container:python: WSGIPath: mydjangoapp.wsgi:application Cons: The environment variables are shown as plain text in AWS console at Elastic Beanstalk > Environments > my-environment > Configuration > Environment properties, although I know the fact that they are only readable by the authorised AWS users who have permission to it. Pros: Ability to update only and directly the environment variables from AWS console without requiring new deployment. Plan B: Remove the sensitive variables at all from my config file and load the .env file from my django app itself. Cons: If I want to update any of those variables, I have to deploy a new version of my application. Although .env file will not pushed to Git and it can be … -
AWS access key is showing up in browser url when accessing the s3 content from heroku
I have deployed my django app to heroku and using Amazon s3 bucket to store the static files and I see there is no issues in getting the data from the s3 to the heroku. But, when I'm testing to see the content storage location i'm getting the url path in addition with the AccesskeyID https://myapp.s3.amazonaws.com/img/front_cover.JPG?AWSAccessKeyId=AKIAXPKPZLYKLRB7DR4N&Signature=JzTU0DpmbGSBRpYHwV8Dvt0p1QQ%3D&Expires=1590936351 So I'm concerned up showing up access id in the browser URl, do we have an option to disable this in heroku or django settings or in AWS -
create or edit models and tables dynamically based on user input from a form outside admin panel
I am new to python django and I wanted to ask if there is a suggested way to create an app with ui for the users to be able to create tables on database with models dynamically. So basically I want the user to fill in the table name and desired column names with types on a form and create them dynamically when they hit submit button. this is for an internal application where we do not want to use the admin panel for implementing it as admin panel will have other elements needed. any advise or examples shared to take a look and learn along the road building would be a huge help. Thank you so much for all the support. -
Django model's save method is not called when creating objects in test
I am trying to test one of my application's model Book that has a slug field. I have a custom save function for it, like below. models.py class Book(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def save(self, *args, **kwargs): if not self.slug: slug = slugify(self.title, allow_unicode=True) return super(Book, self).save(*args, **kwargs) To test this, I created the following test.py class BookModelTests(TestCase): @classmethod def setUpTestData(cls): Book.objects.create(title="Book One") def test_get_absolute_url(self): book = Book.objects.get(pk=1) self.assertEquals(book.get_absolute_url(), '/books/book-one/') But when I run the test, it fails with django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$']. Why is slug empty? Why is the save method not called? What am I missing? -
GridView with actions column in django
I need to display list of books title and authors in a table with actions column in a django project. Would you suggest some packages for this purpose? Thank you. -
JQuery date django.core.exceptions.ValidationError: must be YYYY-MM-DD
I'm trying to create an edit jQuery ajax call. The code are the following: function editUser(id) { if (id) { tr_id = $("#element-" + id); data_pagamento_saldo = $(tr_id).find(".elementDatapagamentosaldo").text().replace(/\./g, "/"); $('#form-data_pagamento_saldo').val(data_pagamento_saldo); } } $("form#updateUser").submit(function() { var data_pagamento_saldoInput = $('input[name="formDatapagamentosaldo"]').val(); if (data_pagamento_saldoInput) { $.ajax({ url: '{% url "crud_ajax_update" %}', data: {'data_pagamento_saldo': data_pagamento_saldoInput, }, But django give me the following error: django.core.exceptions.ValidationError: ["The value '31/05/2020' hhas an invalid date format. It must be in YYYY-MM-DD format] How could I overcome the problem? For more information this is my html template: <td class="elementDatapagamentosaldo userData" name="data_pagamento_saldo">{{element.data_pagamento_saldo|date:"d.m.Y"}}</td> ... <label for="data_pagamento_saldo">Data pagamento saldo</label> <input class="form-control" id="form-data_pagamento_saldo" type="text" name="formDatapagamentosaldo" /> and this my models: class Materiale(models.Model): data_pagamento_saldo=models.DateField('Data pagamento Saldo', default="GG/MM/YYYY")