Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reactjs / Django : my login page background keeps showing in other pages
this is my login.css for the login form body { margin: 0; padding: 0; font-family: sans-serif; background: url(bg.png) no-repeat; background-size: cover; } .login { width: 250px; position: absolute; top: 50%; left: 76%; transform: translate(-50%, -50%); } .login h1 { float: left; font-size: 40px; border-bottom: 6px solid #54c7a4; margin-bottom: 50px; padding: 13px 0; } .champ { width: 100%; overflow: hidden; font-size: 80px; padding: 8px 0; margin: 8px 0; border-bottom: 1px solid #54c7a4; } .icon { width: 20px; float: left; text-align: center; } and I don't have a css file for my register.js but the login background keeps showing I have other pages but the background doesn't show into them i don't know what's the promblem ! any help please ? -
Fixing error "Badly formed hexadecimal UUID string" after converting existing id to uuid in Django (Django 3.0)
I created a table with an initial IntegerField primary key and later changed the id to a UUIDField. Now this raises a "Badly formed hexadecimal UUID string", I guess because a number such as "1" isn't a valid UUID value. Does anyone know a concise way to fix this in code when updating the models.py file for the django app? -
django admin filter show number of records in brackets
I have to show the related records in a filter, inside brackets. Example below: How do I create ShowCountInBrackets? class ModelAdmin(admin.ModelAdmin, ShowCountInBrackets): list_filter = ('client') The code below works, but its ugly. And only for a specific field. class ClientCountInFilter(admin.SimpleListFilter): title = _('Client') parameter_name = 'client' def lookups(self, request, model_admin): qs = model_admin.get_queryset(request) for pk, name, count in qs.values_list('client__id','client__name').annotate(total=Count('client')).order_by('-total'): if count: yield (pk, f'{name} ({count})') def queryset(self, request, queryset): id_val = self.value() if id_val: return queryset.filter(client=id_val) class ModelAdmin(admin.ModelAdmin): list_filter = (ClientCountInFilter) -
Email template doesn't render html tag
I'm trying to override content for default password_reset_email.html with some html tag but it doesn't work. Here is my modification. For testing purpose, I'm just using p tag. But i doesn't work. I'm totally unaware what going wrong. Here is my process. urls.py path('accounts/', include('django.contrib.auth.urls')), and here is my html templates {% load i18n %} {% autoescape on %} {% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %} {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} <p>Hello world</p> {% trans 'Your username, in case you’ve forgotten:' %} {{ user.get_username }} {% trans "Thanks for using our site!" %} {% blocktrans %}The {{ site_name }} team{% endblocktrans %} {% endautoescape %} and here is output enter image description here -
Usage of Openlayers in Django
It's been few days i'm trying to make Openlayers work with my Django web site. I'm totally a noob in Web, so I might miss straightforward stuff that I'm not able to understand, yet. From what I understand, I need to load Openlayers, so for this in my index.html, I've added in the <head> this : <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script> Then in the <body> I've added the index.js where I would like to work with openlayers: <script src="{% static 'index.js'%}"></script> I've copy paste a simple example in the index.js and it's been working correctly. var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([2.333333, 48.866667]), zoom: 10 }) }); So I have a map centered on Paris. Now I would like to load a GeoJson file, thus I need to add a Layer containing the GeoJon. For this I've followed an example here. Here is my first problem I tried to import like this : import GeoJSON from 'ol/format/GeoJSON'; or like this import Style from ol.style.Style bit I got this error : Uncaught SyntaxError: Cannot use import statement outside a module The only solution I found was to new ol.style.Style(...) when … -
when i tried to execute my code in pycharm i got the following error?
[(venv) F:\projects\MULTI_TRAFFIC\MULTI_TRAFFIC\Code\Multi_Traffic_Scene_Perception>python manage.py runserver Performing system checks... Unhandled exception in thread started by .wrapper at 0x0000021B32A08950> Traceback (most recent call last): File "C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\django\db\backends\mysql\base.py", line 274, in get_new_connecti on ]1 -
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,