Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicate record issue in python CSV
MY Record show in CSV FILE LIkE THis 12/11/2017 |PK-LHR-20171112164753_15 |HEAD MASSAGE MENS| SPRAY WITH 10 MINERALS revitalizing care 12/11/2017| PK-LHR-20171112164753_15 |HEAD MASSAGE MENS |SPRAY WITH 10 MINERALS revitalizing care I need 12/11/2017 |PK-LHR-20171112164753_15| HEAD MASSAGE MENS |NULL 12/11/2017 |PK-LHR-20171112164753_15| NULL| MENS SPRAY WITH 10 MINERALS revitalizing care | if filtered_record: #print filtered_record.query for row in filtered_record: #print row writer.writerow(row) file_name = 'reports/invoice_reports/' + timezone.now().strftime('%Y_%m_%d_%H_%M_%S.csv') file_path = os.path.join(BASE_DIR, 'static/' + file_name) with open(file_path, 'wb') as f: f.write(response.content) -
ManytoMany Relation and Custom widget in Django
I have two models Categories and Products. A Product can have multiple Categories, a Category can have multiple Products. The Categories have a circular Foreign key, to itself. class Product: categories = models.ManyToManyField(Category) name = models.CharField(max_length=255) class Category: categories = models.ManyToManyField(Category) name = models.CharField(max_length=255) Not all Categories have the same depth level. A Category can have no children and a Category can have multiple grandchildren. What I want to achieve: When a user add/create a Product, only a select-box containing the parents will appear. After the parent is selected, if the parent has children another select will appear with that parent children. Also the possibility to add more categories. When a user what to edit a product the select boxes for what was already chosen should be available. From where I start: I know that to ManyToMany relation corresponds a ModelMultipleChoiceField Field. To a ModelMultipleChoiceField corresponds a SelectMultiple widget. I thought of creating an widget that inherits from SelectMultiple and change the templates manipulating the get_context_data on the Widget. But my problem is that in context I don't have (know to find) the parent relation inside categories. What are my options ? -
How to realize with a serializer, when the admin user request, serialize all the fields, but the normal user request, serialize part fields?
How to realize with a serializer, when the admin user request, serialize all the fields, but the normal user request, serialize part fields in Rest Framework? In my serializers: class UserListSerializer(ModelSerializer): """ user serializer """ account = AccountSerializer(many=False, read_only=True) class Meta: model = User exclude = [ 'password', ] ... class AccountSerializer(ModelSerializer): """ user's accout """ class Meta: model = Account exclude = [ 'total_charge', 'total_consume', ] In the views: class UserListAPIView(ListAPIView): """ the user view """ queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4) serializer_class = UserListSerializer filter_backends = [SearchFilter, OrderingFilter] search_fields = ['username', 'qq', 'email'] pagination_class = UserPageNumberPagination class Meta: ordering = ['-id'] My requirement is that when I use normal user request the APIView, I want to exclude the bellow fields: 'total_charge','total_consume' If I use the admin user request the APIView, I want to serialize all the fields. -
Django-Filter | Looping over form fields
I am using django-filter which works as intended. I am however trying to loop over the form fields but the standard django attributes aren't working. The only one that does is {{ form.id_for_label }}. Am I missing something? My template code: <form action="" method="get"> {% for form in forms.form.product_colours %} <div class="form-group"> <input type="checkbox" name="product_colours" id="{{ form.id_for_label }}" value="{{ form.value }}"> <label for="{{ form.id_for_label }}">{{ form.label }}</label> </div> {% endfor %} <input type="submit" /> </form> The reason I don't want to simply use {{ form }} is because it loads the <label> before the <input> whereas I'd need it to work viceversa to fit into my styling. I would prefer not to have to change the styling. In case they are needed, here are my FilterSet and my view: FilterSet: class ProductFilter(django_filters.FilterSet): product_colours = django_filters.ModelMultipleChoiceFilter(name="product_colours", label="Product Colour", widget=forms.CheckboxSelectMultiple, queryset=ProductColour.objects.all(), conjoined=False) class Meta: model = Product fields = ['product_colours'] View: def get_context(self, request): context = super(Page, self).get_context(request) all_products = ProductFilter(request.GET, queryset=Product.objects.live()).qs forms = ProductFilter(request.GET, queryset=Product.objects.live()) paginator = Paginator(all_products, 9) # Show 9 resources per page page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context['forms'] = forms context['products'] = products return context -
Nested Seriliazers with multiple tables not working
I have the below tables in models.py class ProductLine(models.Model): availability = models.CharField(max_length=20, blank=True, null=True) series = models.CharField(max_length=20, blank=True, null=True) model = models.CharField(max_length=20, blank=True, null=True) class Meta: db_table = "product_line" class DriveType(models.Model): drive_name = models.CharField(max_length=20, blank=True, null=True) product_line = models.ForeignKey(ProductLine, related_name="drive_type") class Requirements(models.Model): performance_unit = models.CharField(max_length=100, blank=True, null=True) drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True) class Meta: db_table = "requirements" class WorkloadType(models.Model): workload_type_options = models.CharField(max_length=50, blank=True, null=True) drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True) class Meta: db_table = "workload_type" I have below serializers: class WorkloadTypeSerializer(serializers.ModelSerializer): class Meta: model = WorkloadType fields = "__all__" class RequirementsSerializer(serializers.ModelSerializer): class Meta: model = Requirements fields = "__all__" class DriveTypeSerializer(serializers.ModelSerializer): requirements = RequirementsSerializer(many = False, read_only = True) workload_type = WorkloadTypeSerializer(many=False,read_only=True) class Meta: model = DriveType fields = ( "drive_name", "available_drive_type", "capacity", "raid_type", "raid_size", "workload", "workload_percentage", "raid_groups", "compression", "compression_value","requirements","workload_type") class ProductLineSerializer(serializers.ModelSerializer): drive_type = DriveTypeSerializer(many=True, read_only=True) class Meta: model = ProductLine fields = ('availability','series','model','drive_type') In my views I have this: class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): def get_queryset(self): return ProductLine.objects.filter(id=self.kwargs.get("pk")) serializer_class = ProductLineSerializer I am getting output as below : { "availability": "Current", "series": "G1000", "model": "F1500", "drive_type": [ { "drive_name": "drive1", "requirements": { "drive_type": 2, "performance_unit": "by_iops", } } ] } Why I am not able to see WorkLoadType tables data in json where as I am able … -
What approach should I use in mysql database designing that includes more than billion of rows to find particular value using minimum of time?
I have a Django project where I have to solve the following task: client paste the phone number to the search field and application returns full address. If there is no requested address in database, it should be added to another database table of unknown numbers. So, when admin uploads the list of number-address pairs, application should check if everey number exists in database table of unknown numbers. And if exists - it should be removed. This database after some time will contain more than billion rows. My approach is to create two database tables: first - the main table with two columns: "number" and "address". For the column "number" I provide indexation for the faster searching for address. And second one - table with unknown numbers where will be single column "number" which also should be indexed. So, asking for help of experts: do I think right? Or what approach should be the best to solve this task? I can not ask you for deep answer, I just need to which direction I should move on. Thank you very much. I will be happy for any kind of help (comments, links etc). -
How to enable/disable textbox based on selected value of radio button on Django?
I've tried enabling and disabling textbox based on radio button using javascript but it doesn't work. is it possible? Any one can help? Here is template.py <form id="myform" name="myform" action="" method="post"> <td>Radio1</td> <td>{{form.group.1 }}</td> <td>text1</td> <td>{{ form.Text1 }}</td> <td>text2</td> <td>{{ form.Text2 }}</td> <td>Radio2</td> <td>{{form.group.2 }}</td> <td>text1</td> <td>{{ form.Text3 }}</td> <td>text2</td> <td>{{ form.Text4 }}</td> </form> <script> $(document).ready(function(){ $('input[type=radio][name=group]').click(function () { if ($('input[name=group]:checked').val() == "1") { $('#text1').attr("disabled", false); $('#text2').attr("disabled", false); $('#text3').attr("disabled", true); $('#text4').attr("disabled", true); } else if ($('input[name=group]:checked').val() == "2") { $('#text1').attr("disabled", true); $('#text2').attr("disabled", true); $('#text3').attr("disabled", false); $('#text4').attr("disabled", false); } }); </script> form.py text1= forms.CharField(widget=forms.TextInput(attrs={'id':'text1', 'name':'text1'})) text2= forms.CharField(widget=forms.TextInput(attrs={'id':'text2', 'name':'text2'})) text3= forms.CharField(widget=forms.TextInput(attrs={'id':'text3', 'name':'text3'})) text4= forms.CharField(widget=forms.TextInput(attrs={'id':'text4', 'name':'text4'})) group1= forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'group', 'id':"group"}), choices=get_payment_choices()) -
Django with Angular 4 app
How can I serve my Angular 4 app from a Django server? I've tried doing an ng build and then render the index.html in a Django view, but the resulting page is blank. What is the best way to achieve this? -
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!