Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot start docker VM: ImportError: cannot import name 'format_lazy' from 'django.utils.text' (Python Error)
I cannot start a docker VM, due to a Python error that is being thrown. I have tried switching Python versions from 3.5 to 3.6 to 3.7. I have connected to the VM directly, and attempted to run commands directly from the command line (eg. ./manage.py makemigrations) and received the same error. The contents of manage.py are at the bottom. The docker virtual machine that is built using: docker-compose pull docker-compose build docker-compose up When the VM starts, the below error is shown: web_1 | ImportError: cannot import name 'format_lazy' from 'django.utils.text' (/usr/local/lib/python3.7/site-packages/django/utils/text.py) Full trace below: web_1 | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f9ba32c7b90> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 226, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run web_1 | autoreload.raise_last_exception() web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception web_1 | six.reraise(*_exception) web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise web_1 | raise value.with_traceback(tb) web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 226, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 27, in setup web_1 | apps.populate(settings.INSTALLED_APPS) web_1 | File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 108, in populate web_1 | app_config.import_models(all_models) web_1 | File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line … -
Not persistent connection for flutter/dart http.Client()
I have a running django-server that works with sessions. A simple example from my views.py that should be enough to reproduce my problem is given here: def test(request): print("Session objects(") for k,v in request.session.items(): print(k,v) print(")") request.session["a"] = "b" So this does just print everything in the current session and after that saving some dummy-data in the session. If I do access this via my browser the first time the output is Session objects( ) so the session is empty just like expected. Then after refreshing the site the output is: Session objects( a b ) also as expected, so everything seems to work just fine. But now I want to use the site with my flutter app. For that I used the flutter packacke import 'package:http/http.dart' as http like this: var client = http.Client(); String host = ...; // just the ip:port to my host void my_request() async { var response = await client.get(host + "/path/to/test/"); response = await client.get(host + "/path/to/test/"); } So everything this should do is requesting my site twice just like i did before in the browser manually. But now my server just logges twice: Session objects( ) So obviously the client has a not … -
How do I make a django table row have a drop down which has data?
I have a simple database system which I developed in django. it has bootstrap running on front end and the back end has postgresql database connected. the system lets user add a job name, area, salary and experience years. once user fills out fields and hits submit a table will be created in front of him displaying data that he entered (that submitted data is saved in Postgres database) my question is now I want to be able to drop down on a single row to view the job description. meaning under job I want to have job description. how would I do that? -
In django how can I create a postlist like Instagram or facebook?
In django i made a postlist where all the users posts can be showed. how can i make a postlist like instagram or facebook. where if any user follow another user they show their posts first in the list and then as timedate ordered. in post list they can like dislike for particular posts. -
unable to track migration in subfolders in django
in Django when I am running this command python 'manage.py makemigrations Planning' it is saying no change detect and it also not creating any pycache folder in that subfolder. but when I am creating the model in another subfolder on which I had worked in past then it works properly, I am unable to understand what's going on. please healp -
Provide the namespace argument to include() instead on django 3.0
In Django 3.0 this gives the error: django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. How should I change url(r'^admin/', include(admin.site.urls))? I tried to look at the documentation, from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^hello/', include(myapp.views)), ] -
Where is a backend email displayed in Pycharm?
I am following the book 'Django 2 by example', and on page 226 explains how to setup the email backend to write emails to the console the piece of code to add in settings.py is EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' Once having selected the 'forgotten your password' link on the website, everything works fine and it redirects me to the right page. After that, the book states: Take a look at the console where you are running the development server. You will see the generated email, as follows: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Password reset on 127.0.0.1:8000 From: webmaster@localhost To: user@domain.com Date: Fri, 15 Dec 2017 14:35:08 -0000 Message-ID: <20150924143508.62996.55653@zenx.local> Someone asked for password reset for email user@domain.com. Follow the link below: http://127.0.0.1:8000/account/reset/MQ/45f-9c3f30caafd523055fcc/ Your username, in case you've forgotten: zenx I thought I just had to open the 'Python Console' tab, but nothing is shown apart for the basic initial code. Also inside the terminal, the email is not displayed. So, where exactly I can actually see a backend email when is sent, in Pycharm? Thank you for any help. -
objects titles are not passing to dropdown in multiple pages
i created nav bar for ea ch pages and i want include a dropdown by passing model object title to the list and its passing to main page but not passing to other pages my template <li class="menu-has-children"><a href="#services">All Services</a> <ul style="display: inline;"> {% for detailinfo in detail.all %} <li><a href="{% url 'details' services.slug %}">{{ detailinfo.title }}</a></li> {% endfor %} </ul> </li> my view def details(request, services_slug): q = services.objects.filter(slug=services_slug) if q.exists(): q=q.first() else: return HttpResponse("<h1> page not found </h1>") detail = {'detail': q} return render(request, 'detail.html', detail,) and my this is my main page view it passed the titles in it but not in the detail my main page view def homepage(request): aboutinfo = aboutpage.objects servicesinfo = services.objects programinfo = prgm.objects return render(request, 'index.html', {'aboutinfo': aboutinfo, 'servicesinfo': servicesinfo, 'programinfo': programinfo}) -
project ideas for a coding-beginner in: JS, Vue.Js, Python and Django
I have recently started my coding journey. I have been going through tutorials but would like to take on some progressively challenging projects to put my skills to the test and integrate what I have learnt from the separate tutorials. Does anybody have any ideas or experience as to how I should go about it? Thank you. -
how to conditionally add filter fields and value in Django
Consider the below sample model. class Server(models.Model): os = models.CharField(max_length=30) server_owner = models.CharField(max_length=30) server_located = models.CharField(max_length=20) server_name = models.CharField(max_length=20) ... ... In the future, this model will have more fields. So from the request, I would get list of values that I need to filter. Consider the below sample data. os_list = ["Windows", "Linux", "Mac"] server_owner_list = ["John", "Will", "Jake", "Shyam"], server_located = ["India", "USA"] server_name = [] ... ... ... I want to exclude the lists which are empty. From the above example, server_name is an empty list. So while filtering from the Server model I want to add os_list, server_owner_list and server_located and exclude the server_name. In the future, more fields will be added to the DB model, and I might receive an extra list of values from the client request. which could have empty list of array. So I don't want to write a bunch of if-else conditions to check which lists are empty and not empty. Can anyone please help me how can I write scalable ORM for this. -
Django Import Export - Import_id_field not working
I have an excel sheet that looks like this: data.xlsx I want to store the data in this model: class ExcelData(models.Model): var1 = models.CharField(max_length=200) var2 = models.CharField(max_length=200) var3 = models.CharField(max_length=200) var4 = models.IntegerField() Im following this documentation: https://django-import-export.readthedocs.io/en/latest/getting_started.html#declaring-fields This is how far I got: @admin.register(ExcelData) class ViewAdmin(ImportExportModelAdmin): fields = ( "var1", "var2", "var3", "var4" ) class ExcelDataResource(resources.ModelResource): var1 = Field(attribute='var1', column_name='Name') var2 = Field(attribute='var2', column_name='SAP_ID') var3 = Field(attribute='var3', column_name='Abbrev.') var4 = Field(attribute='var4', column_name='Max. Capacity') class Meta: model = ExcelData import_id_fields = ('Max. Capacity',) I get this error: Column 'id' not found in dataset. Available columns are: ['Name', 'SAP_ID', 'Abbrev.', 'Max. Capacity'] The error clearly states that the import_export module is still looking for a column named 'id', despite having set the import_id_fields to 'Max. Capacity'. Thank you for any suggestions -
Exception has occurred: OperationalError no such table: aguadisponivel_dados
Gente sou novo no python e to tendo que fazer um sitezinho que vai armazenar alguns dados obtidos através de uma tabela excel. Mas logo no inicio to lidando com esse erro do titulo que não to sabendo como resolver. Como vocês vão ver boa parte foi tirada de tutoriais e personalizada, então me perdoem caso haja algum erro muito tosco. Meu Models.py : from django.db import models import os.path import sqlite3 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, "aguadisponivel.db") with sqlite3.connect(db_path) as db: class Calculo(models.Model): #codigo retirado da pergunta por falta de relevancia. class Dados(models.Model): ID = models.CharField(max_length=30, null=True) SBICS = models.CharField(max_length=100) OLD = models.CharField(max_length=100, null= True) LAT = models.CharField(max_length=50, null= True) LON = models.CharField(max_length=50, null= True) MUN = models.CharField(max_length=50,null= True) GEOCOD = models.CharField(max_length=50, null= True) T_ARE = models.CharField(max_length=50, null= True) AGRO = models.CharField(max_length=50, null= True) AFIN = models.CharField(max_length=50, null= True) SILT = models.CharField(max_length=50, null= True) ARG = models.CharField(max_length=50, null= True) SOLO = models.CharField(max_length=50, null= True) C_ORG = models.CharField(max_length=50, null= True) def publish(self): self.ID self.save() self.SBICS self.save() self.OLD self.save() self.LAT self.save() self.LON self.save() self.MUN self.save() self.GEOCOD self.save() self.T_ARE self.save() self.AGRO self.save() self.AFIN self.save() self.SILT self.save() self.ARG self.save() self.SOLO self.save() self.C_ORG self.save() def __str__(self): return self.title Meu views.py: from django.shortcuts import … -
Django session variable not store value in the session
I have a Django that I would like it to log some submission request in the backend. I have a requestlog function that I would like it to log the username captured in the customized login page. However,if User B logins after User A, then every request that actually User A submits is recorded as submitted by User B. Below is a snippet of the code #the first two function is for the login page def getotp(request): global otp username =otp = '' if request.POST: username = request.POST.get('username','') request.session['username']= username #code to check the user is in the authorized list, if yes, send an otp to user return JsonResponse(json.dumps({'username':username,'otp':otp}),safe=False) def otpcheck(request): if request.POST: #the otp entered is the same as the one that system gives request.session['pp_auth'] = True ts=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) loginlog(request.session['username'],ts) #code to log the login event return JsonResponse(json.dumps({'authresult':authresult}),safe=False) #main page after authorization def search_index(request): if 'pp_auth' in request.session: del request.session['pp_auth'] #show page content #if not , redirect to the login page #in the main page def cat(request): if request.method == 'POST': #code to get variables to be returned ts=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) requestlog(request.session['username'], ts) #I hope this logs the user stored from the login page that directs to the … -
How to modify admin_order_field and exclude of a django admin class from a function?
Instead of repeating similar code in each of the admin module where I want to replace the field content with an hyperlink to the object details change page, I'm attempting to make a function to do so which I can call from the different admin classes. def url_to_object(obj): url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[obj.pk] ) return format_html('<a href="%s">%s</a>' % (url, obj.__str__())) def display_link(admin_instance, obj, field_name): """ Replaces the object in the admin instance with a hyperlink to this object detail defines in addition the new field with the original field name, and enables sorting based on the original field """ # print(getattr(obj, field_name)) instance = url_to_object(getattr(obj, field_name)) instance.short_description = field_name admin_instance.exclude = [field_name,] # prevent field to be displayed instance.admin_order_field = field_name #'base_target_shape' return instance Call to the function within the ModelAdmin class: def _base_target_shape(self,obj): return display_link(self,obj, 'base_target_shape') # _base_target_shape.short_description = 'base_target_shape' # exclude=['base_target_shape',] # prevent field to be displayed # _base_target_shape.admin_order_field ='base_target_shape' I'm able to generate the link, but the exclude and admin_order_field instructions are not passed back to the admin class. The goal would be to avoid repeating always the same short_description , exclude and admin_order_field in all the admin classes Thanks in advance -
How to make custom error message in Django Admin
need make custom error message in Django Admin @receiver(pre_save, sender=User, dispatch_uid='active') def active(sender, instance, **kwargs): email = instance.email if User.objects.filter(email = email): if email == None:raise ValidationError('The email can not be null.') raise ValidationError('The email address is alerady in use.') -
Http and https confusing for request.build_absolute_uri()?
The docs state Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has. If you need to redirect users to HTTPS, it’s best to let your Web server redirect all HTTP traffic to HTTPS. I have a https-only app behind nginx which converts all http requests to https. I get an incoming https call, but when I run request.build_absolute_uri() it gives me the request with a http and not https (so not the same scheme). What is going wrong? Is there a setting I should add/change? -
AssertionError at /apartments/ Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view,
Whenever I make a 'GET' request to the 'apartment' endpoint, I get 'AssertionError'. I tried it without pagination, I got a response, but when I switch back to using pagination, I get 'AssertionError'. views.py class ApartmentList(APIView,MyPaginationMixin): authentication_classes = [TokenAuthentication] permission_classes = [AllowAny] apartments = Apartment.objects.all() serializer = ApartmentSerializer pagination_class = api_settings.DEFAULT_PAGINATION_CLASS def get(self,request): page = self.paginate_queryset(self.apartments) if page is not None: serializer = self.serializer(page, many=True) return self.get_paginated_response(serializer.data) mixins.py class MyPaginationMixin(object): @property def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() return self._paginator def paginate_queryset(self, queryset): """ Return a single page of results, or `None` if pagination is disabled. """ if self.paginator is None: return None return self.paginator.paginate_queryset( queryset, self.request, view=self) def get_paginated_response(self, data): """ Return a paginated style `Response` object for the given output data. """ assert self.paginator is not None return self.paginator.get_paginated_response(data) -
Django shows page not found
I'm learning Chapter 18 18.4.2 in Python Crash Course,when i open http://localhost:8000/topics ,I'm using Django 3.0 and python 3.8 shows Page not found (404) Request Method: GET Request URL: http://localhost:8000/topics Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, topics, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. and this is my code learning_log\urls.py from django.contrib import admin from django.urls import path from learning_logs import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name = 'index') ] learning_logs.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index,name = 'index'), url(r'^topics/$',views.topics,name='topics') ] views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): return render(request,'learning_logs/index.html') def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics':topics} return render(request,'learning_logs/topics.html',context) base.html <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a>- <a href="{% url 'learning_logs:topics'%}">Topics</a> </p> {% block content %}{% endblock content %} topics.html {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li>{{ topic }}</li> {% empty %} <li>No topics have … -
How to return custom JSON response in UpdateAPIView?
I was trying to return some custom message after user complete updated data after submit. How can i do this in UpdateApiView? class DetailUpdateView(generics.UpdateAPIView): permission_classes = (permissions.IsAuthenticated,) lookup_field = "pk" serializer_class = DetailSerializers def get_queryset(self): data = Data.objects.all() return data -
Having headers on selected pages in Django using pdfkit
I am having a Django application and am using pdfkit for converting the document to pdf. However, I need to add a custom header of my own starting from second page only and not on first. Moreover, I am using the configuration: 'header-right': '[page]/[topage]', So, when I add a separate header tag in my .html file. The header-right option gets overlapped with my custom header and the paging section disappears. So, I am unable to add a custom header from second page onwards by keeping the page intact. Any leads? -
Convert many to many relationship to one to many in django
What I'm trying to achieve Till now we've models which have many to many relationships like given below. class A(models.Model): name = models.CharField(max_length=255) data = models.ManyToManyField(B, related_name='data', through='C') class B(models.Model): name=models.CharField(max_length=255) class C(models.Model): a = ForeignKey(A) b = ForeignKey(B) c = model.CharField(max_length=255) active = models.BooleanField(default=True) and so on.... Although Django creates an intermediate table automatically for many to many relationships if we don't define it explicitly as you can notice I've defined the third intermediate table explicitly to store extra metadata about each relation. So, as per new business requirements, we need to remove many to many relationships from the table and replace it with one to many relationships i.e each record of B can have more than one references to obj A but record of A will always have one reference to A obj. also, since these tables are already being used in production therefore we need to migrate the existing data as well. Things which I've tried so far Removed many to many from model A. class A(models.Model): name = models.CharField(max_length=255) data = models.ForeignKey(B) Updated the existing row of model C. for eg: #this might return more than one obj because of many to many relationship test = … -
using python Django does not import from same folder
-myapp -mysite - urls.py trying to from myapp import views as v from urls.py but it does not recognize the myapp I'm using pycharm IDE -
how could i include search box in leaflet django forms?
i want to have a search box in my django leaflet forms my model is: class Post(models.Model): title = models.CharField(max_length=50) location = models.PointField(null=True, blank=True) objects = GeoManager() def __str__(self): return self.title and my form is : class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','location') widgets = {'location':Leafletwidget( attr= {'settings_overrides':{ 'DEAFULT_CENTER':(35.68,51.38), } }) } and my templates is: {% load static %} {% load leaflet_tags %} {% load widget_tweaks %} <div class="form-group"> {% render_ field form.location %} </div> <script type="text/javascript"> {% leaflet_js plugins="ALL" %} </script> and also i dont want to render form entirly like {{ form }} rather than i want render each one of field like this: {% render_ field form.location %} please help me if evrey body has solution becuse i realy need it -
Creating a datatable using makemigrations and migrate in Django
models.py from django.db import models class Students(models.Model): name=models.CharField(max_length=64), rollNo=models.IntegerField(), marks=models.IntegerField(), friends=models.CharField(max_length=64) After applying these commands; py manage.py makemigrations and py manage.py migrate the 0001_initial.py should have hold all the features of the table. But it has only created the Id and the last column name i'm providing. 0001_initial.py: # Generated by Django 2.2.7 on 2020-01-06 08:57 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Students', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('friends', models.CharField(max_length=64)), ], ), ] How could I store all the column names in this file so that my table will be reflected on the admin page in the browser? admin.py from django.contrib import admin from testcase.models import Students class StudentAdmin(admin.ModelAdmin): List_display=['id','name','rollNo','marks','friends'] admin.site.register(Students,StudentAdmin) -
Django LeafletWidget map not movable
i have a Django application where I am using leaflet maps. I have created models, views and everything as it should be and it works fine, except for one part. When I create a form based on model and use the leaflet widget (LeafletWidget()) the map shows up fine, I can draw on it, but if I try to move the map no matter where the map recenters itself to the initial location. Any ideas how can I disable that automatic recenter?