Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model object has no attribute 'get'
using Django 1.11 I'm stuck with uuid referencing in my views. I read through all similar looking questions here, but they either focus on forms or anything else. Minimal example It's an app called MegaTest. It's bound to /testuuid/ I have a working index view that generate links to /testuuid/<uuid> If I click on a link on my index page, I get: AttributeError at /testuuid/5a147a14-a9a9-4045-8e79-0ce2e8258a68/ 'MegaTest' object has no attribute 'get' models.py class MegaTest(models.Model): uuid = models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=128, blank=True, null=True) views.py class IndexView(generic.ListView): template_name = 'testuuid/index.html' context_object_name = 'test_list' def get_queryset(self): """Return the last five published questions.""" return MegaTest.objects.all() class MegaTestDetailView(generic.DetailView): model = MegaTest def get(self, request, uuid): try: megatest = MegaTest.objects.get(uuid=uuid) return megatest except MegaTest.DoesNotExist: raise Http404 urls.py app_name = 'testuuid' urlpatterns = [ # ex: /polls/ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<uuid>[\w-]+)/$', views.MegaTestDetailView.as_view(), name='detail'), ] testuuid/index.html {% if test_list %} <ul> {% for test in test_list %} <li> <a href="{% url 'testuuid:detail' test.uuid %}">{{ test.name }}</a></li> {% endfor %} </ul> {% else %} <p>No tests available.</p> {% endif %} I assume a damn simple mistake, but I really have no clue at this point. The complete traceback can be found here http://dpaste.com/140XDCN -
How to call javascript function from Django template tag
I'm trying to get the tab history length into url tag to pass it as parameter. What I tried in template (and didn't work out) is this: <li><a href="{% url 'polls:load_zip' javascript:history.length %}">Query</a></li> I also tried to create a javascript function and call it from the url tag but it didn't work out as well: <script> function history_len(){ return history.length; } </script> and <li><a href="{% url 'polls:load_zip' history_len() %}">Query</a></li> Any suggestions? -
better app architecture in django
I want to understand the app architecture in django with the screenshot I have attached as an example. I have done the research and found that some prefers there should be several apps because it will be easier to maintain code and test code. I have only seen the theory part with no clear example. That is why I am asking this basic question which might be already asked before. I want to get the answer based on specific example to be more clear than code with doubts and confusion. Suppose this is the project (Inventory Management System). Here you can see there are many entities like Master Setup which contains office setup, Dept/Section List etc and Human Resource Setup which contains several other setup related to it. Now my question is how should I architecure my django apps? Should I create a single app named inventory_management and create a separate table like Master Setup, Office Setup, Human Resource Setup etc or create a different app like Master Setup as one app and Human Resource Setup as another app and Opening Stock as another. The table in the Master Setup will be office setup, dept/section list etc. What is the … -
Return errors as json django rest api
Beginner alert. I am using ListCreateAPIView for listing and creating purposes. Whenever I create through an api it returns responses in json format. {"id":16,"title":"yyyyyyyy","destination_place":[1]} But if there are errors like duplicate slug or title it returns errors like this IntegrityError at /api/holidays/ duplicate key value violates unique constraint "holidays_holiday_slug_key" DETAIL: Key (slug)=(yyyyyyyy) already exists. Is there any way to return these errors in json format. My views class HolidayList(ListCreateAPIView): queryset = Holiday.objects.all() serializer_class = HolidaySerializer permission_classes = [IsAdminUser, IsAuthenticated] Model class Holiday(models.Model): title = models.CharField(verbose_name=_("Title"), max_length=255) slug = models.SlugField(unique=True) destination_place = models.ManyToManyField(to='places.Place',related_name='destination_place',null=True,blank=True) -
Django error templates in custom path
I have dir template with all templates, and I have dir errors, with all templates with errors 404.html. I found the following old solution: In urls.py my app I wrote from django.conf.urls import (handler400, handler403, handler404, handler500) handler404 = 'my_app.views.page_not_found' And in view my app from django.shortcuts import (render_to_response) from django.template import RequestContext def bad_request(request): response = render_to_response( 'errors/404.html', context_instance=RequestContext(request)) response.status_code = 404 return response But I use Django 1.11 and this doesn't work. -
Multicolumn table in django template
How to fill multicolumn table in django template? I have list of n elements (let's say just numbers there) and I want to create a table (looks like grid) with 5 cells in a row. Very easy to create table of 1 column, but to create 5? Of course we assume than list may have arbitrary number of items from zero to couple hundreds. <tbody> {% for item in data.items.all %} <tr class="item-{{ item.number }}">{{ item.number }}</tr> {% endfor %} </tbody> -
'if' VS `while` to a `funtions.partial.func`
In Django documentation django.conf.urls | Django documentation | Django There's such codes: class RegexURLPattern(LocaleRegexProvider): ... def lookup_str(self) callback = self.callback # Python 3.5 collapses nested partials, so can change "while" to "if" # when it's the minimum supported version. while isinstance(callback, functools.partial): callback = callback.func ... The code is to callback the argument of funtion 'view' and execute it. Why while is better than if excluding 'Python 3.5'? There is only one callback argument passed in from django.conf.urls.url,which seen in: def url(regex, view, kwargs=None, name=None): elif callable(view): return RegexURLPattern(regex, view, kwargs, name) It seems if is more readable than while. -
Excel file downloadeb by google chrome
I have request which download excel file! And some texts into cell very big, and I am trying to divide it into several lines. And I am using xlwt in django: this is my code: def parse_string(label=""): if len(label) == 0: return "", 1 t = "" mx_sym = 50 endl = 0 for i in label: if mx_sym > 0: t += i mx_sym -= 1 elif mx_sym <= 0 and i != ' ': t += i elif mx_sym <= 0 and i == ' ': t += "\n" endl += 1 mx_sym = 50 return t, endl this is my function to divide text into several lines def single_doc_report_to_xls(file, report): wb = xlwt.Workbook() ws = wb.add_sheet(u'Отчет #') al = xlwt.Alignment() al.wrap = xlwt.Alignment.WRAP_AT_RIGHT ws.write(0, 0, u"№ п/п") ws.write(0, 1, u"Наименование документа") ws.write(0, 2, u"Наличие документа") ws.write(0, 3, u"Дата вложения документа") ws.write(0, 4, u"Дата приема документа сотрудником ЦПМБ/ЦПСБ") ws.write(0, 5, u"Комментарии по документу (при наличии)") ws.write(0, 6, u"Статус документа (в обработке/ на доработке/ принят Банком для рассмотрения)") ws.col(0).width = 256 * 60 ws.col(1).width = 256 * 65 ws.col(2).width = 256 * 60 ws.col(3).width = 256 * 20 ws.col(4).width = 256 * 60 ws.col(5).width = 256 * 60 ws.col(6).width … -
Django: Filtering Distinct Data
I'm trying to build a messaging app. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in view, data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at') In my template, {% for abc in data %} {{ abc.receiver }}<br /> {% endfor %} How can I print out the distinct users? -
I need 1 row split into 2 rows in django
When i check my CSV there is duplicate record.I need to add specific record on accurate column.check image.Anyone know about this how i can solve? duplicate record filtered_record = BillManagement.objects.filter(creation_date__range=[date, date1], **kwargs).annotate( price=F('product__cost') - F('customerproductbill__discounted_price')).values_list( 'creation_date', 'bill_number', 'staff__user__first_name','service__name', 'product__product_name', 'quantity', 'total_amount', 'distype__percentage_discount', 'distype__discount_type', 'customerproductbill__discounted_price', 'product__cost', 'price', 'customer__first_name', 'customer__last_name', ).distinct() -
Django HTML template to pdf consisting JS (Vue.js) charts and graphs
I am trying to generate a PDF from Html page. The Html includes various data returned from django view and also from Vue.js I tried using 'Weasyprint' but it only generated data that returned from Django but not the charts and graphs that were generated from Vue. What will be an easy way to generate all the data as well as the graphs in PDF from the Html page. -
Updating info on html page using Ajax in Django
I have a problem with Ajax and how can I update info on my html page without reloading it. So, I have a function in my views.py file: def index(request): some stuff context = { some stuff } return render(request, "header.html", context) And I just use variables from {context} in my header.html file. And the question is - how can I perform index function and send new variables to my header.html file without reloading it? -
can any one explain me about stacked inline and tabular inline
this is my models.py file from django.db import models # Create your models here. class Item(models.Model): name=models.CharField(max_length=250) description = model.TextField() class Meta: oredering['name'] def __unicode__(self): return self.name @permalink def get_absolute_url: retun ('item_detail',None,{'object_id':self_id}) class Photo(models.Model): item = models.ForiegnKey(Item) title=models.ChaField(max_length=250) image=models.IMageField(upload_to='photos') caption=models.TextField(blank=True) class Meta: ordering=['title'] def __unicode__(self): return self.title @permalink def get_absolute_url(self): retun ('photo_detail',None,{'object_id':self_id}) and this is my admin.py : from django.contrib import admin from models import Item from models import Photo # Register your models here. class PhotoInline(admin.StackedInline): model = Photo class ItemAdmin(admin.ModelAdmin): inlines = [PhotoInline] admin.site.register(Item, ItemAdmin) admin.site.register(Photo) but i cant understand what is stacked inline and tabular inline(i reffered django doumentation but still couldn't understand what exactly it was ) and i cant see those models in my admin panel when i started server(i dont understand why my models aren't regestired in my admin page) any kind of help is appreciated thanks in advance -
How to use the serializers's DictField and ListField correctly?
I created a serializer with some extra serializer fields: class CloudServerCreateSerializer(ModelSerializer): cpu = serializers.IntegerField() # eg:1,2,4, ram = serializers.IntegerField() # eg: 1,2,4, os = serializers.DictField() # eg: {"os_big":"Linux", "os_detail":"CentOS7.2"} disk_os = serializers.DictField(child=serializers.CharField()) # {"disk_type":"SSD", "disk_size":"50"} disk_store = serializers.ListField(child=serializers.CharField()) # [{"disk_type":"SSD", "disk_size":"50"}, {"disk_type":"SSD", "disk_size":"50"}] bandwidth = serializers.IntegerField() # eg: 1, 2, 3, buytime = serializers.IntegerField() # eg: 1, 2, .... 12, 24, 36 count = serializers.IntegerField() # eg: 1, 2 vmrootname = serializers.CharField() # eg:root vmrootpassword = serializers.CharField() vmname = serializers.CharField() class Meta: model = CloudServer exclude = ['expiration_time'] In the views.py: class CloudServerCreateAPIView(CreateAPIView): serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() def post(self, request, *args, **kwargs): serializer = CloudServerCreateSerializer( data = request.data, context = {'request':request} ) serializer.is_valid(raise_exception=True) data = serializer.validated_data print(data) # There I print the data return Response(data="没有数据了", status=HTTP_404_NOT_FOUND, exception=Exception()) #serializer.save() return Response(data="创建成功", status=HTTP_200_OK, exception=None) The snapshot of rest framework: The traceback: [13/Nov/2017 14:17:32] "GET /api/cloudserver/create/ HTTP/1.1" 405 10925 OrderedDict([('cpu', 2), ('ram', 2), ('os', {}), ('disk_os', {}), ('disk_store', ['[{"disk_type":"SSD", "disk_size":"50"}, {"disk_type":"SSD", "disk_size":"50"}]']), ('bandwidth', 2), ('buytime', 2), ('count', 1), ('vmrootname', 'root'), ('vmrootpassword', 'qweqw'), ('vmname', 'asdas'), ('profile', 'asdas'), ('availablearea', <AvailableArea: xxxx>)]) In the traceback you can see, the os and disk_os dictionary data did not pass over. and the disk_store … -
Return models with relevant models of another table in django
I created models which are Contracts and ContractItems. ContractItems table contains a foreign key attribute of Contracts table. I need to return Contracts with their relevant ContractItems. I implemented a serializer like it. class ContractSerializer(ModelSerializer): class Meta: model = Contract fields = ('id', 'name') I could not get ContractItems to relevant Contract. Could anyone suggest any way to get Contracts with their relevant ContractItems? And also One Contract can have many ContractItems. -
Djnago Testing how to use actual database instead of test_db
I am currently trying to do some testing on django application, however info about testing on official documentation is quite small(or probably I didn't search enough). Here is my test (its start actually) from django.test import TestCase from django.contrib.auth.models import User from rest_framework.test import APIRequestFactory, force_authenticate class PassengerEditTest(TestCase): factory = APIRequestFactory() PASSENGER_DATA = { "id": 18, "given_name": "CHyna", "surname": "Jake", "birth_date": "1980-11-16", "gender": 0, "email": "chyna.jake25@gmail.com", "phone": "87017777777", "DOCO": "ololololo" } URL = '127.0.0.1:8000/api/v1/tickets/profile/passengers/' # def setup(self): # user = User.objects.get(username = 'admin') # # request = factory.post(self.URL, {'title': 'new idea'}, format='json') def test_given_name(self): # print "Test given_name start" user = User.objects.get(username='chynajake') request = self.factory.post(self.URL, self.PASSENGER_DATA, format='json') force_authenticate(request, user=self.user) # print "Test given_name finish" My problem is when I run on terminal: ./manage.py test -s path.to.test.PassengerEditTest it creates a new clean test database, but for this test I need db with actual data from my database. How can I make it so it also inserts all records from actual db not only tables? I am using postgresql P.S. I am very newbie at writing test, please suggest some convention, resources and tutorials to learn from. -
Django model structure (complex m2m) of Assessment app advice
I was hoping for some help with planning the model structure of an assessment tool. The tool will be used to assess each workstation of a line. The assessment will be comprised of a subset of standard questions and storing the scores of each of those questions. Then the station scores will be aggregated and analyzed. There will be multiple lines. Here is my thought but I am struggling with: modeling the scores, the many to many relationships and how to be able to record the scores: List of tables Questions -id -description Line -workstations -name Workstation -question set How would I be able to store each question scores per workstation per line? Any help is very appreciated! -
Disable Django Auth
I have two different Django Applications. Both the applications have there respective Auth. Applications are hosted on different servers. Now the use case is such that: There is a redirection link that can be provided from Application 1. Now i would want to disable auth on Application 2 when the link has been traversed from application 1 which already has a Single Sign on. To be noted, Each application can be access individually so i cannot disable auth on application2. How can this be achieved where Application 1 has a single sign on and when a link from application 1 is clicked, it gets redirected to application 2 but should not authentication that particular request as the request is from Application 1. Thank you. Arun. -
Django: Message App
I'm trying to create a messaging app. This is what I did so far. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Now I can filter the messages between request.user & any user but couldn't re-order the messages based upon the fact that if request.user sends someone a message the person whom he send a message his name should appear at the top or if some send a message to request.user his name should appear at the Top. As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message, whom request.user sends a message his name re-orders at the Top but It's not changing the ordering of messages in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. What is the right way of doing this? Thank You -
How to make user interface that connects to back-end
I am in the process of building some machines/devices (you could think of them as kiosk like info devices with touchscreen and interface) I am thinking about what the best way would be to write the code for the machine but I just don’t have enough experience and there seems to be so many options. The underlying processes that have to be executed are now written in python (3.6). Python is not needed perse so I could also rewrite it in a different language. My idea for now was to make an GUI with PyQT or Tkinter and run that locally on the machines. The problem with that idea for now is that 1) the machines will be deployed so I need remote acces to it and 2) It seems to be not be the best solutions to use python for the GUI. What I would prefer would be to have a server running from my office to which the machines all connect to. The server should run the underlaying processes and probably create a response page on the machines (?). What would be needed for this? A server running ubuntu server and Django with python, css, js and html? … -
Azure Active directory authentication for custom web service api
My project structure is as- Web service api [not rest] implemented using django single page application implemented using angular 2 and HTML MongoDB as database I have deployed both spa as well as api on azure cloud. What I want to achieve is as- Secure and Authorize every request going to web api as there is no authorization implemented at api side. Single page application will be authenticated using saml which is to be implemented I am new to azure cloud and gone to lot of articles by microsoft as well as other blogs What I have tried- Registered web api in azure active directory Registered single page application in azure active directory Please guide me from here- As per my understanding- 1. Web api can be configured such that it only be accessible to single page application [ considering my scenario], hence no request can be directly access to web api service. please correct me if I am wrong I don't have any user except admin in azure active directory Considering above scenario kindly guide me for configuration. Any help will be much appreciated. Thanks in advance -
Django renders information to wrong database field
so I was implementing a database in Django to take in username and password using the given Users model. However, when I hit submit the password gets taken into the email field. Any suggestions on what I could be doing wrong? This is for user signup. Thank you! could it be that Users does not come with a passwords section? How would I Add that in? forms.py class UserRegistrationForm(forms.Form): username = forms.CharField( required = True, label = 'Username', max_length = 32 ) password = forms.CharField( required = True, label = 'Password', max_length = 32, widget = forms.PasswordInput() ) views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django import forms from .forms import UserRegistrationForm #from django.contrib.auth import views as auth_views #from . import views # Create your views here. def login(request): return render(request, 'login.html') def profiles(request): return render(request, 'profiles.html') def signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data print(userObj) username = userObj['username'] password = userObj['password'] if not (User.objects.filter(username=username).exists()): User.objects.create_user(username,password) user = authenticate(username = username, password = password) login(request) return HttpResponseRedirect('/') else: raise … -
How can I get the serializer-fields in APIView?
How can I get the serializer-fields in APIView? In the document, it only say how to add serializer-fields in serializers, but did not state how to get the serializer-fields in the APIView. I add so many serializer-fields in the CloudServerCreateSerializer: class CloudServerCreateSerializer(ModelSerializer): cpu = serializers.IntegerField() # eg:1,2,4, ram = serializers.IntegerField() # eg: 1,2,4, os = serializers.DictField() # eg: {"os_big":"Linux", "os_detail":"CentOS7.2"} disk_os = serializers.DictField() # {"disk_type":"SSD", "disk_size":"50"} disk_store = serializers.ListField() # [{"disk_type":"SSD", "disk_size":"50"}, {"disk_type":"SSD", "disk_size":"50"}] class Meta: model = CloudServer exclude = ['expiration_time'] but I do not know how to get these values in the views: class CloudServerCreateAPIView(CreateAPIView): serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() def post(self, request, *args, **kwargs): print(*args, **kwargs) #serializer.save() return Response(data="创建成功", status=HTTP_200_OK, exception=None) How to get the serializer-fields in rest framework views? -
print('urlpatterns: ', urlpatterns) returns nothing in URLconf
I am learning Django following Writing your first Django app, part 1 | Django documentation | Django I attach print statement to URLconf for debugging. from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] print('urlpatterns:', urlpatterns) The server did not respond even with None Quit the server with CONTROL-C. 12/Nov/2017 19:13:36] "GET /polls/ HTTP/1.1" 200 40 [12/Nov/2017 19:13:43] "GET /polls/ HTTP/1.1" 200 40 I checked several times to make sure no bugs existing within such mininal codes,The following is all the codes: #views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") Contract to it,print statement works in my other project. urlpatterns: [<RegexURLResolver <RegexURLPattern list> (admin:admin) ^admin/>, <RegexURLPattern home ^$>, <RegexURLPattern login ^login/$>] System check identified no issues (0 silenced). The browser functions normally to display the message ("Hello, world. You're at the polls index.") What's the problem? -
django - TypeError how to get instance of a foreignkey from the user instance
I am getting the following type error and its due to this instance in view. The model as you can see below where Employee is onetoone relation to User and Company is the foreignkey to the Employee. How would I be able to solve this by getting the instance of company ? Or what is the problem. companysetting_form = CompanySettingEdit(instance = request.user.employee.company) Below is the typeerror TypeError at /employee/companysettings/ __init__() got an unexpected keyword argument 'instance' Request Method: GET Request URL: http://127.0.0.1:8000/employee/companysettings/ Django Version: 1.11.7 Exception Type: TypeError Exception Value: __init__() got an unexpected keyword argument 'instance' Exception Location: /Users/megasap/Documents/project/railercom/railercomapp/views.py in employee_companysettings, line 83 Python Executable: /Users/megasap/Documents/project/myvirtualenv/railercom/bin/python Python Version: 3.6.3 Python Path: ['/Users/megasap/Documents/project/railercom', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Users/megasap/Documents/project/myvirtualenv/railercom/lib/python3.6/site-packages'] Below are my code: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py @login_required(login_url='/employee/sign-in/') def employee_companysettings(request): companysetting_form = CompanySettingEdit(instance = request.user.employee.company) <---- this is the problem if request.method == "POST": companysetting_form = CompanySettingEdit(request.POST, instance = request.user.employee.company) if employee_form.is_valid(): employee_form.save() return render(request, 'employee/account.html', { "companysetting_form":companysetting_form }) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/forms.py class CompanySettingEdit(forms.Form): name = forms.CharField(max_length=50, required=False) tel = forms.CharField(max_length=50, required=False) address_1 = forms.CharField(max_length=50, required=False) address_2 = forms.CharField(max_length=50, required=False) address_zip = forms.CharField(max_length=50, required=False) address_city = forms.CharField(max_length=50, required=False) address_state = forms.CharField(max_length=50, required=False) address_country = forms.CharField(max_length=50, required=False) class Meta: model = Company fields = ("name", "tel", "address_1", "address_2", …