Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['employees\\/edit\\/(?P<pk>[0-9]+)\\/$']
Building an Employee application, After updating an Employee using a form, it just shows this error and the Url seems correct so I can really say where the error is coming from I've crosschecked all my url patterns my views and my url in the form and also tried using the solution in this question, this gives me a bigger error urls.py urlpatterns = [ path('edit/<int:pk>/', views.edit, name = 'edit'), ] views.py @login_required(login_url='/accounts/login') def edit(request, pk): employ = get_object_or_404(Employee, id=pk) logging.info(type(employ)) departments = Department.objects.all() context = { 'employ': employ, 'departments':departments } if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] name = last_name +' '+first_name employee_id = request.POST['employee_id'] email = request.POST['email'] department = Department.objects.get(dept_name = request.POST['department']) address = request.POST['address'] employment_type = request.POST['employment_type'] employment_status = request.POST['employment_status'] role = request.POST['role'] marital_status = request.POST['marital_status'] gender = request.POST['gender'] join_date = request.POST['join_date'] end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date'] location = request.POST['location'] credentials = request.POST['credentials'] passport = request.POST['passport'] hod = request.POST['hod'] phone_number = request.POST['phone_number'] date_of_birth = request.POST['date_of_birth'] date_added = datetime.now() if Employee.objects.filter(employee_id = employee_id).exists() or Employee.objects.filter(email = email).exists(): messages.error(request, 'That ID/Email is Taken') return redirect('edit') else: employee = Employee(first_name='first_name',last_name='last_name',email='email', employee_id='employee_id',department='department',address='address',employment_type='employment_type', employment_status='employment_status',role='role',marital_status='marital_status',gender='gender',join_date='join_date', end_date='end_date',location='location',credentials='credentials',passport='passport',hod='hod', phone_number='phone_number',date_added='date_added',date_of_birth='date_of_birth') employee.save() messages.success(request, 'Employee Created') return redirect('all') return render(request, 'employees/edit.html', context, … -
Create HTTP Server in Python
I am trying to create a django app in which I need to create a server on my PC and fetch data from a website or IP on the internet. The data i will fetch should be in the form of XML document. How shall I write a code in Python in order to establish a connection with the IP and fetch its data and display it on my localhost. -
What does [::1] mean in ALLOWED_HOSTS in Django?
I was going through the documentation for Django's ALLOWED_HOSTS here I came across a string ['localhost', '127.0.0.1', '[::1]'] in the ALLOWED_HOSTS. Everything looks fine except the '[::-1]' part. I can't find a realtime scenario where '[::-1]' is used. Can someone please explain in which use case we will use this [::-1] -
Django 2 apps same urls
i have 2 apps Post and espor i want like this; example.com/blog-post (post app) example.com/sk-telecom-vs-team-solomid (espor app) blog.urls path('',include('post.urls')), path('',include('espor.urls')), However, i got error. (If I combine 2 apps in a single app, it's okay, but I want to separate it.) -
ODBC Driver Manager Data source name not found and no default driver specified
I have problem connecting my 64 bit laptop with a database. I am working in a django project and my database (sql server 32 bit) is in a separate server. I have included the following in my settings file in Django. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'sales', 'USER': '*******', 'PASSWORD': '*********', 'PORT': '1433', 'HOST': 'xx.xx.xxx.xxx', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, } } I have tried installing "ODBC Driver 11 for SQL Server" in my laptop. (since the server also has the same driver installed). But when I make migrations, I get an error, django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manag er] Data source name not found and no default driver specified (0) (SQLDriverCon nect)') Am I getting the problem due to the different versions (64 bit & 32 bit) installed in my laptop and server? If so how can I handle this without changing the entire laptop system to 32 bit?Also, I haven't installed sql server in my laptop. Should I need to install sql server in my laptop also? -
How to get json from queryset?
This class has query for database: class arizakestirimi_func(ListAPIView): serializer_class = arizakestirimiserializer def get_queryset(self): queryset = isyeriarizabilgileri.objects.raw(""" SELECT M.id as id,M.isyeri as isyeri, DATE_PART('day',(M.tarih)::timestamp - (D.mindate)::timestamp) * 24 + DATE_PART('hour',(M.tarih)::timestamp - (D.mindate)::timestamp) + DATE_PART('minute',(M.tarih)::timestamp - (D.mindate)::timestamp) / 60 as zamanfarki FROM arizakestirimi_isyeriarizabilgileri M INNER JOIN (SELECT DISTINCT ON (isyeri) isyeri,id as id,durustahmini,tarih as mindate FROM arizakestirimi_isyeriarizabilgileri WHERE durustahmini='MEKANIK ARIZA' AND isyeri='15400001' ORDER BY isyeri, tarih ASC) D ON M.isyeri = D.isyeri AND M.durustahmini = D.durustahmini ORDER BY M.tarih ASC """) return queryset This is the serializer class, I have defined it in serializer.py: class arizakestirimiserializer(serializers.Serializer): isyeri = serializers.CharField(max_length=30) zamanfarki= serializers.FloatField() When ı use django rest framework ı got this json: [ { "isyeri": "15400001", "zamanfarki": 0.0 }, { "isyeri": "15400001", "zamanfarki": 7.0 }, { "isyeri": "15400001", "zamanfarki": 603.0 }, { "isyeri": "15400001", "zamanfarki": 607.0 }, { "isyeri": "15400001", "zamanfarki": 1655.0 }, { "isyeri": "15400001", "zamanfarki": 1661.0 } ] I want to use this json directly inside "get_queryset" method. How can convert queryset result to json with given field name like "serializers.py". Thanks -
Heroku Django ModuleNotFoundError
I'm a first timer working with Django and now trying to deploy to Heroku. I am able to push to heroku and their service recognizes my application as a python application. However, when I navigate to my application I get Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail checking the logs I get the following: 2019-07-09T06:00:29.052294+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2019-07-09T06:00:29.052301+00:00 app[web.1]: ModuleNotFoundError: No module named 'xxxx' 2019-07-09T06:00:29.052738+00:00 app[web.1]: [2019-07-09 06:00:29 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-07-09T06:00:29.198426+00:00 app[web.1]: [2019-07-09 06:00:29 +0000] [4] [INFO] Shutting down: Master 2019-07-09T06:00:29.198530+00:00 app[web.1]: [2019-07-09 06:00:29 +0000] [4] [INFO] Reason: Worker failed to boot. 2019-07-09T06:00:29.314321+00:00 heroku[web.1]: State changed from up to crashed 2019-07-09T06:00:29.296331+00:00 heroku[web.1]: Process exited with status 3 2019-07-09T06:00:29.937311+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=murmuring-dusk-96030.herokuapp.com request_id=38020b2b-dc63-42aa-91e6-63e1c377eadd fwd="155.93.179.40" dyno= connect= service= status=503 bytes= protocol=https 2019-07-09T06:00:30.382887+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=murmuring-dusk-96030.herokuapp.com request_id=133a6de4-be78-4ac9-9fcf-f65e74c41de3 fwd="155.93.179.40" dyno= connect= service= status=503 bytes= protocol=https I'm not 100% sure but I think the issue has to do with how I'm serving static files? … -
Obtaining queryset based on unrelated models
I've got the following models. I need to obtain a queryset of orders where the user's userprofile.setupstatus == 1. Is this possible or should I just add a foreign key field on the Order model to the UserProfile? class Order(models.Model): user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE) class UserCheckout(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) setupstatus = models.IntegerField(default=0) -
How to display form errors properly?
Here i am trying to display form's errors and the below code works also but the problem with this is when the form throws the field errors it also clears all the the previously added value from form.I looked through all the solution in this link https://docs.djangoproject.com/en/2.2/topics/forms/ but all the solution works as same. What i really want is to throw the field errors like the django {{form.as_p}} or {% bootstrap_form form %} throws, in my own custom forms.How it can be possible ? {% for field in form %} {% if field.errors %} <div class="alert alert-danger"> {{ field.label }}: {{ field.errors|striptags }} </div> {% endif %} {% endfor %} <div class="box-body"> <div class="row"> <div class="col"> <form action="{% url 'do_something' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <b>Name</b> <div class="controls"> {{# form.name.errors #}} <input type="text" name="name" class="form-control"> </div> </div> <div class="form-group"> <b>Address</b> <div class="controls"> <input type="text" name="address" class="form- control"> </div> </div> -
How I add totals row to django admin that show an admin method total
I get sum of other table records with an admin method. No I want to sum this virtual column in total row. I used. Django-admin-totals .but it can't sum virtual fields. What can I do to do that? -
Receiving error "This backend doesn't support absolute paths." when overwriting file in S3
I'm trying to implement crop and upload feature as per this blog post: https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html When attempting to save the cropped photo I get the error: "NotImplementedError: This backend doesn't support absolute paths." forms.py class LetterPictureModelForm(forms.ModelForm): picture = forms.ImageField( label='Picture', widget=ClearableFileInput(attrs={ 'class': 'form-control', 'placeholder': 'Picture' }) ) x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = LetterPicture fields = ['picture', 'x', 'y', 'width', 'height', ] widgets = { 'letter': forms.HiddenInput(), 'slot': forms.HiddenInput() } def save(self): letter_picture = super(LetterPictureModelForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(letter_picture.picture) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(letter_picture.picture.path) return letter_picture settings.py STATICFILES_STORAGE = 'custom_storages.StaticStorage' custom_storages.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION As you can see I'm using S3 to save media files, which has been working as expected so far. Can anyone tell me what's causing this error? I don't understand what it means. -
How can i Post value in radio button and also show available value in database?
HTML CODE- $("#id_emp").empty(); var countemp = 1; $(comjsonemp).each(function (index, item) { var itemnameemp_v = comjsonemp[index].itemid__item_name; var requiredemp_v = comjsonemp[index].required; var statusemp_v = comjsonemp[index].status; var itemidemp_v = comjsonemp[index].itemid; var remarksemp_v = comjsonemp[index].remarks; /* alert(itemnameemp_v); */ var html_emptb; if(comjsonemp.toString().length > 0) { /* alert("in emplo"); */ $("#div_empfolder").show(); if (requiredemp_v.trim()=='T') { html_emptb += "<td ><input type='checkbox' name='empreq' id='id_empreq' class='form-control' checked /><label for='option'></label></td>" ; } else { html_emptb += "<td><input type='checkbox' name='empreq' id='id_empreq' class='form-control' /><label for='option'></label></td>" ; } countemp += 1; if(statusemp_v.trim() =='T') { html_emptb +="<td> <input name='empreceived" +countemp+"' type='radio' id='id_empreceived_y" +countemp+"' class='with-gap radio-col-teal' checked/><label for='id_empreceived_y" +countemp+"'>Received</label><br><input name='empreceived" +countemp+"' type='radio' id='id_empreceived_n" +countemp+"' class='with-gap radio-col-teal' /><label for='id_empreceived_n" +countemp+"'>Not Received</label> </td>"; } else { html_emptb +="<td> <input name='empreceived" +countemp+"' type='radio' id='id_empreceived_y" +countemp+"' class='with-gap radio-col-teal'/><label for='id_empreceived_y" +countemp+"'>Received</label><br><input name='empreceived" +countemp+"' type='radio' id='id_empreceived_n" +countemp+"' class='with-gap radio-col-teal' checked /><label for='id_empreceived_n" +countemp+"'>Not Received</label> </td>"; } html_emptb +=" <td>" + itemnameemp_v + "</td>" ; html_emptb +="<input type='hidden' name='hid_Empitemid_v' id='id_hid_Empitemid_v' value='" + itemidemp_v + "' /></td>"; html_emptb +="<td><textarea rows='2' class='form-control' name='emp_check' id='id_empcheck' value='" + remarksemp_v + "' > </textarea> </td>" ; } $("<tr/>").html(html_emptb).appendTo("#id_emp"); }); VIEWS- comstatus = [(n, v) for n, v in request.POST.items() if n.startswith('hid_cklistcomid')] #comstatus = [name for name in request.POST.keys() if name.startswith('comreceived')] # print(comstatus) for i in comstatus: print(comstatus) comstatus_id … -
Is there a way to get foreign key instance from the QuerySet?
I trying to get the foreign key instance stored in the CandidateSkill model(In[5]) but want to avoid using loop. I have tried values() it only return the actual candidate_id(int) stored in Candidate model and not the instance. models.py class Candidate(models.Model): candidate_id = models.AutoField(primary_key = True) name = models.CharField(max_length = 255, null = False) class CandidateSkill(models.Model): candidate_id = models.ForeignKey('hr.Candidate', on_delete = models.CASCADE) skill = models.CharField(max_length = 255) Django Shell In [1]: from hr.models import CandidateSkill as cds In [2]: a = cds.objects.filter(skill__icontains = 'py') In [3]: a Out[3]: <QuerySet [<CandidateSkill: CandidateSkill object (1)>, <CandidateSkill: CandidateSkill object (2)>, <CandidateSkill: CandidateSkill object (3)>, <CandidateSkill: CandidateSkill object (4)>, <CandidateSkill: CandidateSkill object (10)>]> In [4]: a[0] Out[4]: <CandidateSkill: CandidateSkill object (1)> In [5]: a[0].candidate_id Out[5]: <Candidate: Clayton Cote> So I there a way to get only the foreign key instance and avoid using the loop. -
How to create a Django REST Framework View instance from a ViewSet class?
I'm trying to unit test Django REST Framework view set permissions for two reasons: speed and simplicity. In keeping with these goals I would also like to avoid using any mocking frameworks. Basically I want to do something like this: request = APIRequestFactory().post(…) view = MyViewSet.as_view(actions={"post": "create"}) self.assertTrue(MyPermission().has_permission(request, view)) The problem with this approach is that view is not actually a View but rather a function which does something with a view, and it does not have certain properties which I use in has_permission, such as action. How do I construct the kind of View object which can be passed to has_permission? The permission is already tested at both the integration and acceptance level, but I would like to avoid creating several complex and time-consuming tests to simply check that each of the relevant actions are protected. -
is there any way for using csrf token in rest api without using front end in django?
i am using django framework for making a rest api for registration but when i do that csrf token is not set since front end is not set. So it causes post request not to execute in POSTMAN. i want some way to make my rest api without disabling the csrf in my program. i tried to copy the csrf token into cookie and access those cookie to verify from POSTMAN that but it is not working for POST request also i tried to set header in postman but it also turn up to be GET request only. from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie '''@csrf_exempt''' def addToTable(request): response = HttpResponse('blah') response.set_cookie('csrftoken', get_token(request)) c = get_token(request) response.set_cookie('csrftoken', c) d = request.COOKIES['csrftoken'] if request.method == 'POST': row_data = request.read() data = json.loads(row_data) a = data['MyName'] b = data['MyPassword'] post = Post() post.MyName = a post.MyPassword = b post.save() response.delete_cookie('csrftoken') return JsonResponse({'My Name ':a+ "and " + c + " is added to database and it is a post request."}) else: response.delete_cookie('csrftoken') return JsonResponse({'username ': d + " Data is not added to database and it is a get request." + c}) return 0 i want my rest api work for registration when i … -
Is there any way to run the python script with django project?
I am new to django and python. I have created a django web application, I also have a python script which I have to run at the backend of the web application in real-time(Like it should always check for new updates and tell the web about new responses from the API by generating notifications). I am using an IBM-Qradar API from which I have to display the data on the web application. I have two problems 1) Is there any way I can use the below python code with my django project just like I described above? 2) and use the API response which is in json format to store the data into MySQL database directly from response variable. I could Only find ways to store data into the database by using forms, which is not required for my project. import json import os import sys import importlib sys.path.append(os.path.realpath('../modules')) client_module = importlib.import_module('RestApiClient') SampleUtilities = importlib.import_module('SampleUtilities') def main(): # First we have to create our client client = client_module.RestApiClient(version='9.0') # ------------------------------------------------------------------------- # Basic 'GET' # In this example we'll be using the GET endpoint of siem/offenses without # any parameters. This will print absolutely everything it can find, every # parameter … -
how to fix connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? error when running bitbucket pipelines
I am trying to run tests using bitbucket pipelines but unfortunately i can not connect with postgresql. So i have trying adding rm -rf /tmp/.s.PGSQL.5432/ to my bitbucket-pipeline.yml but nothing has changed when running my test This is the error that i get + python manage.py test /usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py:265: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. RuntimeWarning nosetests --with-coverage --cover-package=accounts,rest_v1, property --verbosity=1 Creating test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 174, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? bitbucket-pipelines.yml image: python:3.6.2 pipelines: default: - step: script: - pip install -r requirements.txt - python manage.py test branches: develop: - step: caches: - node script: - pip … -
Why my contextProcessor doesnt work for all templates? django 2.2.1
As the title says, i have set a input processor but it does not work for all the templates of my page, just for some of them but not for all. I have created the context_processor.py inside of my app. def categories_processor(request): enterprise = enterprisedata.objects.get(id=0) return {'enterprise': enterprise} I heard thats all that i need to do it. But it some templates when i try to call it like for example: {% block title %} <title>{{enterprise.name}} | Carrito</title> {% endblock %} Doesnt work. Any help? something that i am missing? thank you! -
django: redirect to another page after download is triggered
I would like the user to be redirected to another page after the download of his file is triggered. How should I do this? Below is my code on how the download is triggered. Alternatively, how could I parse the data frame created in the first web page to the web page the user is redirected to then trigger the download? Any help is appreciated. Thank you! from django.shortcuts import render from django.http import HttpResponse from .forms import * from .functions import * from . import models def index(request): if request.method == 'POST': # upload file file=request.FILES['excelfile'] df=createDF(file) # write to xlsx and trigger download response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="somefile.xlsx") df.to_excel(response, index=False) return response # render form for upload return render(request, 'webpage/index.html') -
Use multiple databases in Django having the other database contain tables not created by any model
Here are my questions and if you want to know the details, kindly refer further below (Sorry for the long post, I wanted the inquiry to be as detailed as possible): Questions Is it possible to retrieve data from an external database and use those inside your Django project even if the tables in that database are NOT created as models? If so, what's the basic concept to achieve such. If NOT, then the workaround left is to use the SAME DATABASE as the remote one, and save all models of the django project into a specific schema in that database? So we are trying to forcibly implement Cross-database referencing with a remote database my_remote_db, that contains tables which are not created by a Django model. We've read the Django doc telling it currently cannot handle such referencing method, but the fact we can define multiple databases in settings.py makes us optimistic that there is somehow a workaround. Databases as defined in our settings.py django_project_db - main database (the one used by our Django project for its models) my_remote_db - the remote database. Several applications are using this database e.g. our Scout and PHP applications, etc. What we want to … -
Django Admin Custom Url Path
Hi I would like to create a custom url in my django admin. The default URL when editing an object is. http://localhost:8000/admin/cart/cart_id/change In my admin http://localhost:8000/admin/cart/1/change I have a field called cart unique id. I want to create a custom url that behaves similar to the edit URL in django admin. http://localhost:8000/admin/cart/uniq_id/change http://localhost:8000/admin/cart/H2KPAT/change Is this implemation possible? -
Django Modelform - setting field value to foreign key
I created two models in my app: "Prescription" and "Prescription_status." When a user clicks save on my "Create new prescription" modelform, I need to add a "Prescription_status" to the "Prescription." In the below instance, I'd like to save as a 'Draft' status (PK=1). I don't want to set a default status. I've been trying everything, what am I missing?? Thanks in advance! models.py # Static Prescription Status Types class Prescription_status(models.Model): status = models.CharField(max_length=200) status_definition = models.TextField() def __str__(self): return '%s' % (self.status) # Prescription Model class Prescription(models.Model): order_id = models.AutoField(primary_key=True, unique=True) status = models.ForeignKey(Prescription_status, models.SET_NULL, null=True) I saved the following Prescription_status objects to the database, which I'd like to reference as users save or edit prescriptions: status_id for "Draft" status = 1 status_id for "Ready for Signing" status = 2 status_id for "Signed and Authorized" status = 3 database chart showing PK for each status forms.py class PrescriptionForm(forms.ModelForm): class Meta: model = Prescription fields = ('medication', 'quantity', 'directions', 'refills', 'earliest_permitted_fill_date', 'daw',) widgets = { 'earliest_permitted_fill_date': DatePickerInput(), # default date-format %m/%d/%Y will be used } views.py def new_rx(request): if request.method == "POST": form = PrescriptionForm(request.POST) if form.is_valid(): prescription = form.save(commit=False) prescription.status = Prescription_status.objects.get(pk=form.cleaned_data['1']) prescription.save() return redirect('home') else: form = PrescriptionForm() return … -
How to remove DELETE button from django admin page
I want to remove the Delete button from django admin page as shown below. -
django user fields shown empty in template
cannot access fields in templates model.py: class DSS(models.Model): title = models.CharField(max_length=255, null=True, blank=True, verbose_name='عنوان') usr = models.ForeignKey(User, related_name='owner', verbose_name='کاربر') view.py: def state(request): result = DSS.objects.values('usr').order_by('usr').annotate(count=Count('usr')) context = {'result': result,} return render(request, 'state.html', context) my template: <tr> <td>{{ item.usr }}{{ item.usr.get_username}}{{ item.usr.username}}{{ item.usr.get_full_name}}</td> <td>{% with item.usr.get_username as usrnm %} {{ item.usr.get_full_name|default:usrnm }} {% endwith %}</td> <td>{{ item.usr.first_name }} {{ item.usr.lastname }}</td> <td>{{ item.owner.first_name }}</td> <td>{{ item.count }}</td> </tr> {{ item.count }} work well and {{ item.usr }} just show user id, but I need to display username. -
Python django ImportError: cannot import name (unknown location)
I am starting to use Django and was able to get Django Rest Framework working. Now, I am trying out Elasticsearch using https://django-elasticsearch-dsl-drf.readthedocs.io/en/0.18/ and also following https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/tree/master/examples/simple I followed the examples, built my project along those lines. I am getting the ImportError when I try to start server, could anyone please review and give me pointers on what I may be missing. I am enclosing some details about my environment for reference. Thanks Environment: cmd > pip freeze | find "Django" django-cors-headers==3.0.2 django-elasticsearch-dsl==0.5.1 django-elasticsearch-dsl-drf==0.18 django-filter==2.1.0 django-nine==0.2.2 djangorestframework==3.9.4 Directory structure demosite demosite settings.py [INSTALLED_APPS contains my_rest_app, search_indexes] my_rest_app [which works with http://localhost:8000/my_rest_app/] search_indexes viewsets publisher.py [see below] urls.py [see below] documents publisher.py [see below] search_indexes/url.py --------------------- from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from search_indexes.viewsets import PublisherDocumentViewSet urlpatterns = [ url(r'^', include(router.urls)), ] # ********************************************************** # *********************** Publishers *********************** # ********************************************************** router.register( r'publishers', PublisherDocumentViewSet, basename='publisherdocument' ) search_indexes/viewsets/publisher.py ------------------------------------ from django_elasticsearch_dsl_drf.pagination import LimitOffsetPagination from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from ..documents import PublisherDocument from ..serializers import PublisherDocumentSerializer __all__ = ( 'PublisherDocumentViewSet', ) class PublisherDocumentViewSet(DocumentViewSet): """The PublisherDocument view.""" document = PublisherDocument serializer_class = PublisherDocumentSerializer search_indexes/documents/publisher.py -------------------------------------- from my_rest_app.models import Publisher __all__ = ('PublisherDocument',) INDEX = Index(settings.ELASTICSEARCH_INDEX_NAMES[__name__]) # See Elasticsearch Indices API reference for …