Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get values from Raw Html for in Django
This maybe stupid. But I'm finding problem in it. I'm working with Django, I have read docs. But for the forms, there is class. If I use this then a form is generated in the view, But actually I hardcoded the entire form, I just need to take the values from it. Like PHP. How to achieve this, I don't wanna Django to generate my form. Thanks in advance! -
Chromedriver doesn't open on windows?
I have a django application that it uses selenium and chromedriver on ubuntu when I try to open the application from windows the chromedriver doesn't open -
Django : cannot find model when inserting values to model from html form?
I am trying to insert values to sqlite database using basic django forms. These are my Settings Models.py class Book(models.Model): def get_absolute_url(self): return reverse ('books:detail',kwargs={'pk':self.pk}) def __str__(self): return self.name+ '-'+self.author name = models.CharField(max_length=120) author = models.CharField(max_length=120) genere = models.CharField(max_length=120) year = models.CharField(max_length=120) image = models.ImageField(upload_to='img/',null=True,blank=True) forms.py from django import forms from .models import Book SOME_CHOICES = ( ('Science fiction','Science fiction'), ('Psychology','Psychology'), ('Philosophy','Philosophy'), ('Novel','Novel'), ('Poetry','Poetry'), ) class BookForm(forms.Form): name = forms.CharField() author = forms.CharField() genere = forms.CharField(label='Text',widget= forms .Select (choices=SOME_CHOICES)) year = forms.CharField() book_image = forms.ImageField() views.py from django.shortcuts import render,redirect from books.forms import BookForm from django import forms from books.models import Book from django.forms import ModelForm from django.core.urlresolvers import reverse_lazy from django.views import generic from django.shortcuts import render from django.http import HttpResponse from .models import Book from django.views.generic import (ListView,CreateView,UpdateView,DeleteView,TemplateView) from django.template import loader from django.http import Http404 from django.views.generic.edit import CreateView from django.core.urlresolvers import reverse def Book_Create_View(request): form=BookForm(request.POST,request.FILES) if form.is_valid(): book_obj=models.Book() book_obj.name = request.POST.get("name") book_obj.author = request.POST.get("author") book_obj.genere = request.POST.get("genere") book_obj.year = request.POST.get("year") book_obj.image = request.FILES book_obj.save() return redirect('books:index') else: form = BookForm() template ='books/book_form.html' return render(request,template,{'form':form}) book_form.html {% extends 'books/base.html'%} {%block content%} <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <div class="form-group"> <button type="submit" class="btn btn-sucess">Submit </button> … -
Syntax error using try: except within a for loop to handle DivideZeroError
Iterating across multiple dicts, I am trying to calculate the percentage of values from each dict, sum_allBlocks and sum_allBounds. I then add this data to a new dict as a list. Can someone help me to avoid my ZeroDivideError that I get whenever one of the values in sum_allBounds is zero? Got a syntax error when adding the try: except: inside the for loop. #Get Block% by Stand from allstands, add to daily_details as percent_allBlocks def get_flight_details(stand_data): for _key, allstands in stand_data.items(): daily_details = {} divide_allBlocks = ["{0:3.1f}%".format(a / b * 100) for a, b in zip(sum_allBlocks, sum_allBounds)] daily_details['percent_allBlocks'] = divide_allBlocks -
Django - how to print only the value of a variable
I'm working on a project for college and I'm trying to print out the value of a model in django but the result I'm getting on my webpage is ]>, lulll is name of a student. I'm trying to print out just the value without the queryset and the brackets. Below is my views.py file and my html http://prntscr.com/loko6n http://prntscr.com/lokoh6 Thank you :) -
RBAC with Django REST Framework
Any suggestions on what I should use to integrate RBAC with DRF? I have taken a look at django-rest-framework-roles and django-guardian but neither look too promising. Your feedback would be much appreciated. Thanks in advance. -
Test Django Channels
I'm writing unit tests for a project but I'm not able to figure out how to read a message from a channel after sending the message. @task(name="export_to_caffe", bind=True) def export_caffe_prototxt(self, net, net_name, reply_channel): net = yaml.safe_load(net) if net_name == '': net_name = 'Net' try: prototxt, input_dim = json_to_prototxt(net, net_name) randomId = datetime.now().strftime('%Y%m%d%H%M%S')+randomword(5) with open(BASE_DIR + '/media/' + randomId + '.prototxt', 'w+') as f: f.write(prototxt) Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'success', 'action': 'ExportNet', 'name': randomId + '.prototxt', 'url': '/media/' + randomId + '.prototxt' }) }) except: Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'error', 'action': 'ExportNet', 'error': str(sys.exc_info()[1]) }) }) This is the function I want to write tests for. class TestExportCaffePrototxt(unittest.TestCase): def test_task(self): net = '{"l36":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l35"],"output":["l37"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l36"}},"l37":{"info":{"phase":null,"type":"Dropout","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l36"],"output":["l38"]},"params":{"caffe":true,"rate":0.5,"trainable":false,"seed":42,"inplace":true},"props":{"name":"l37"}},"l34":{"info":{"phase":null,"type":"Dropout","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l33"],"output":["l35"]},"params":{"caffe":true,"rate":0.5,"trainable":false,"seed":42,"inplace":true},"props":{"name":"l34"}},"l35":{"info":{"phase":null,"type":"InnerProduct","parameters":16781312},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l34"],"output":["l36"]},"params":{"bias_filler":"constant","bias_regularizer":"None","kernel_constraint":"None","bias_constraint":"None","activity_regularizer":"None","num_output":4096,"weight_filler":"constant","kernel_regularizer":"None","caffe":true,"use_bias":true},"props":{"name":"l35"}},"l32":{"info":{"phase":null,"type":"InnerProduct","parameters":102764544},"shape":{"input":[512,7,7],"output":[4096]},"connection":{"input":["l31"],"output":["l33"]},"params":{"bias_filler":"constant","bias_regularizer":"None","kernel_constraint":"None","bias_constraint":"None","activity_regularizer":"None","num_output":4096,"weight_filler":"constant","kernel_regularizer":"None","caffe":true,"use_bias":true},"props":{"name":"l32"}},"l33":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l32"],"output":["l34"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l33"}},"l30":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l29"],"output":["l31"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l30"}},"l31":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[512,14,14],"output":[512,7,7]},"connection":{"input":["l30"],"output":["l32"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l31"}},"l38":{"info":{"phase":null,"type":"InnerProduct","parameters":4097000},"shape":{"input":[4096],"output":[1000]},"connection":{"input":["l37"],"output":["l39"]},"params":{"bias_filler":"constant","bias_regularizer":"None","kernel_constraint":"None","bias_constraint":"None","activity_regularizer":"None","num_output":1000,"weight_filler":"constant","kernel_regularizer":"None","caffe":true,"use_bias":true},"props":{"name":"l38"}},"l39":{"info":{"phase":null,"type":"Softmax","parameters":0},"shape":{"input":[1000],"output":[1000]},"connection":{"input":["l38"],"output":[]},"params":{"caffe":true},"props":{"name":"l39"}},"l18":{"info":{"phase":null,"type":"Convolution","parameters":1180160},"shape":{"input":[256,28,28],"output":[512,28,28]},"connection":{"input":["l17"],"output":["l19"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l18"}},"l19":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l18"],"output":["l20"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l19"}},"l14":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l13"],"output":["l15"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l14"}},"l15":{"info":{"phase":null,"type":"Convolution","parameters":590080},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l14"],"output":["l16"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":256,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l15"}},"l16":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l15"],"output":["l17"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l16"}},"l17":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[256,56,56],"output":[256,28,28]},"connection":{"input":["l16"],"output":["l18"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l17"}},"l10":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[128,112,112],"output":[128,56,56]},"connection":{"input":["l9"],"output":["l11"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l10"}},"l11":{"info":{"phase":null,"type":"Convolution","parameters":295168},"shape":{"input":[128,56,56],"output":[256,56,56]},"connection":{"input":["l10"],"output":["l12"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":256,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l11"}},"l12":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l11"],"output":["l13"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l12"}},"l13":{"info":{"phase":null,"type":"Convolution","parameters":590080},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l12"],"output":["l14"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":256,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l13"}},"l21":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l20"],"output":["l22"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l21"}},"l20":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l19"],"output":["l21"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l20"}},"l23":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l22"],"output":["l24"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l23"}},"l22":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l21"],"output":["l23"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l22"}},"l25":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l24"],"output":["l26"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l25"}},"l24":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[512,28,28],"output":[512,14,14]},"connection":{"input":["l23"],"output":["l25"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l24"}},"l27":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l26"],"output":["l28"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l27"}},"l26":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l25"],"output":["l27"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l26"}},"l29":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l28"],"output":["l30"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l29"}},"l28":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l27"],"output":["l29"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l28"}},"l6":{"info":{"phase":null,"type":"Convolution","parameters":73856},"shape":{"input":[64,112,112],"output":[128,112,112]},"connection":{"input":["l5"],"output":["l7"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":128,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l6"}},"l7":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[128,112,112],"output":[128,112,112]},"connection":{"input":["l6"],"output":["l8"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l7"}},"l4":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[64,224,224],"output":[64,224,224]},"connection":{"input":["l3"],"output":["l5"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l4"}},"l5":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[64,224,224],"output":[64,112,112]},"connection":{"input":["l4"],"output":["l6"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l5"}},"l2":{"info":{"phase":null,"type":"ReLU","parameters":0,"class":""},"shape":{"input":[64,224,224],"output":[64,224,224]},"connection":{"input":["l1"],"output":["l3"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l2"}},"l3":{"info":{"phase":null,"type":"Convolution","parameters":36928},"shape":{"input":[64,224,224],"output":[64,224,224]},"connection":{"input":["l2"],"output":["l4"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":64,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l3"}},"l0":{"info":{"phase":null,"type":"Input","parameters":0,"class":"hover"},"shape":{"input":[],"output":[3,224,224]},"connection":{"input":[],"output":["l1"]},"params":{"dim":"10, 3, 224, 224","caffe":true},"props":{"name":"l0"}},"l1":{"info":{"phase":null,"type":"Convolution","parameters":1792,"class":""},"shape":{"input":[3,224,224],"output":[64,224,224]},"connection":{"input":["l0"],"output":["l2"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":64,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l1"}},"l8":{"info":{"phase":null,"type":"Convolution","parameters":147584},"shape":{"input":[128,112,112],"output":[128,112,112]},"connection":{"input":["l7"],"output":["l9"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":128,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l8"}},"l9":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[128,112,112],"output":[128,112,112]},"connection":{"input":["l8"],"output":["l10"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l9"}}}' net_name = "Sample Net" reply_channel = "TestChannel" task = export_caffe_prototxt.delay(net, net_name, reply_channel) client = Client() response = client.send('websocket.receive', content=task) # self.assertEqual(response, 'SUCCESS') This is my attempt at writing test for the above function. I know it's not correct and I can't figure out how do I read the message value and then match it. -
how to fill xfa forms using API or coding?
I have a xfa form which I want to fill using API or coding. currently I'm using python (Django). is there any way to fill form using javascript or python ? I'm new to xfa form and googled for a solution but nothing fruitful came. -
BootStrap DashBoard and Django
I'm using the dashboard bootstrap of the link: BootStrapDashBoard for building my page and I already have a page with the listing of items done in Django with Html plus Python and it is working perfectly. So what I did was copy the code from the working table and paste it over the code of the bootstrap table, it shows the table header with the name of each one, but does not list all the items registered. I do not know what I did wrong. remembering that on the page that I copied this code it works perfectly and lists all the items <div class="table-responsive"> <table class="table table-bordered sortable""> <thead class="thead-dark"> <tr> <th scope="col">Id</th> <th scope="col">Nome</th> <th scope="col">Endereço</th> <th scope="col">Telefone</th> </tr> </thead> <tbody> {% for pessoa in pessoas %} <tr> <th scope="row" >{{pessoa.id}}</th> <td > <a href="{% url 'core_pessoa_update' pessoa.id %}" style="color:black">{{pessoa.nome}} </a></td> <td><a href="{% url 'core_pessoa_update' pessoa.id %}" style="color:black">{{pessoa.endereco}}</a></td> <td><a href="{% url 'core_pessoa_update' pessoa.id %}" style="color:black">{{pessoa.telefone}}</a></td> </tr> {% endfor %} </tbody> </table> -
Clearsessions command in Django
Can I run this command on my production server without any risk? Will all sessions be deleted or how is clearsessions affecting my database? -
Serialize two querysets with DjangoRestFramework
I'm trying to serialize more than one queryset, but I noticed that only one of them becomes serialized. This is the approach I'm currently trying. class GetDetails(APIView): def get(self, request): todays_date = time.strftime('%Y-%m-%d') #Get results according to specified criteria queryset = People.objects.filter(date = todays_date, assigned_to = 1) #Check if any querysets are available if queryset: #Iterate through each queryset, serialize and return a response for person in queryset: serializer=ASerializer(queryset) return Response(serializer.data) else: return Response({'TODO':'TODO'}) -
Django/Postgres: in a query with a conditional annotation, return an ArrayField with a certain value in it?
I am using Python 2.7, Postgres 9.6 and Django 1.11. I have a model, Person, with two CharFields on it, director_id and company_id. I'd like to annotate it according to a certain condition: when director_id is not null, do a subquery performing an ArrayAgg that gives me back an array of the company_ids associated with it (fine, got that working); when it is not I'd like to return an array of length 1 simply containing the company_id for this Person. Is there a way to specify that I want default to give back an array with a certain value in it? Person.objects.annotate( aggregated_company_ids=Case( When(director_id__isnull=False, then=Subquery(aggregated_company_ids)), default=[F("company_id")], # ProgrammingError: can't adapt type 'F' output_field=ArrayField(models.CharField()), ), ) -
Is it possible to recover overwritten files from Android Studio?
For a mistake i've overwritten my two project that has same names from android studio and i've dismissed that action today i've tryed to open the main project and i've found no Java classes in it and just the layout's files. While in the second project to which i was overwritting there is a huge confusion of files and trying to recover the project version by using history of Android Studio even those files has disappeared. Is it possible in anyway to recover the whole project? Ps: all that remain from that project is a generated apk. -
save url to image field in Django Rest Framework
purpose I want to make my input parameter image can be filled with url file base64 but save as a image. code models.py class Item(models.Model): image = models.ImageField(upload_to='item') ... views.py class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer def create(self, request): if request.data.get('type') == 'url': request.POST._mutable = True request.data['image'] = convert_from_url(request.data['image']) serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I modify the request data when input type is url. convert_from_url is a method to save a image to TemporaryFile and pack in InMemoryUploadedFile serializers.py class ItemSerializer(serializers.ModelSerializer): def create(self, validated_data): item = Item.objects.create( image=validated_data['image'] ) ... item.save() return item Problem serializer = ItemSerializer(data=request.data) this line didn't pass correct request.data (it didn't contain data) validated_data (serializers) didn't get image when I modified it before -
get_queryset for ListCreateAPIView not being called
I have a ListCreateAPIView that I'm trying to override get_queryset, but it is never being called. Here is my view: class DeviceView(generics.ListCreateAPIView): def get_queryset(self): # Threw this and some print statements, but no sign of # the exception or print statement raise Exception return None @swagger_auto_schema( responses={ 201: DeviceSerializer(), }, request_body=DeviceSerializer, ) def post(self, request, format=None): # This code works fine ... @swagger_auto_schema(responses={200: DeviceSerializer(many=True)}) def get(self, request, format=None): # This code DOES get hit and successfully retrieves all the devices Here is the urls.py: urlpatterns = [ path(r"devices/<serialnumber>/abc", views.AbcView.as_view()), path(r"devices/<serialnumber>", views.DeviceDetailView.as_view()), path(r"devices/", views.DeviceView.as_view()), path(r"api-auth/", include("rest_framework.urls", namespace="rest_framework")), path( r"swagger/", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui", ), url( r"^swagger(?P<format>\.json|\.yaml)$", schema_view.without_ui(cache_timeout=0), name="schema-json", ), url(r"^api-token-auth/", obtain_jwt_token), path("admin/", admin.site.urls), ] Any thoughts on why the get_queryset isn't being hit/overridden? -
DRF - return JSON from API view in the shell
I feel like I'm missing something simple but... from the shell how do you return the JSON data from a ListAPIView? Using requests you would do something like: r = requests.get(url, params={'status': '5'}) data = r.json() Basically I just want to take a queryset, serialize it, then return the JSON. -
Calling application running on Django Server from Servlet running on Tomcat server
Is it possible to call an application which is running on Django server from a Servlet on Tomcat Server? I tried getRequestDispacher and sendRedirect with the IP address of Django server on which another application is running. No success at all. Are these methods only to forward the request and response to jsp, servlet and html page which are already in the same server or we can redirect them to another server? -
Django - Exception Value: local variable 'form' referenced before assignment
In a definition for saving a search word in a form i got stack. This definition gives the error " local variable 'form' referenced before assignment". on the line ( if form.is_valid():). I tried to reorder it but didn't succeed. Maybe this is very easy for more experienced developers. def SearchCreateView(request): template_name = 'SearchCreateView_form.html' model = Search form_class = SearchCreateViewForm if request.method == 'POST': if form.is_valid(): form = SearchCreateViewForm(request.POST or None, instance=search.user) print(form.errors.as_text()) search = form.save(commit=False) form.instance.search.user = self.request.search.user return render_to_response(request, 'search.html', {'form': form}) else: context = {'form': form} return render_to_response(request, 'save.html', context) else: form = SearchCreateViewForm(request.POST or None) return render(request, 'SearchCreateView_form.html', {'form': form}) -
Django renaming field returns only int id not object
I have the following Django model fields: first_message = model.ForeignKey(FirstMessage) second_message = model.ForeignKey(SecondMessage) whereas only one of those will be filled in the DB, never both of them at the same time. Now I have following filter condtion: # state_model_field can be either 'first_message' or 'second_message' field_filter = {f'{stats_model_field}__isnull': False} objects = (MessageStats.objects .filter(**field_filter) .prefetch_related(stats_model_field) .annotate(message=F(stats_model_field)) .values('message') .order_by('message')) The objects field should contain all MessageStats with the joined FirstMessage or SecondMessage table. In order not to have to distinguish between the fields in the future, I want to rename whichever field state_model_field is to the alias message (with the annotate). However, the results are returned as a dict {'message': 1} but I want the full object of wither FirstMessage or SecondMessage!? -
django: same tabularInline for two foreignKeys
I have these "typical" models that more or less resemble my django application, for which I wanted to use the admin interface, good enough for my purposes (but also after 3 months I'm still not good at all with Django) models.py class genericItem(models.Model): #a genericItem can be a monitor (with its properties) a laptop (with its properties..) etc.. genericItem_ID = models.AutoField( primary_key=True) # Field name made lowercase. genericItemName = models.CharField(max_length=30, blank=True, null=True) category = models.ForeignKey('categories', models.DO_NOTHING, db_column='category_ID', null=True,blank=True) def __str__(self): return self.genericItemName class item(commonFields): #items are goods that may refer to genericItems, e.g. I buy 4 items and 3 of them are monitors (genericItems) item_ID = models.AutoField(db_column='item_ID', primary_key=True) # Field name made lowercase. genericItem = models.ForeignKey('genericItem', models.DO_NOTHING,related_name='genericItem', db_column='genericItem_ID') location = models.ForeignKey('location', models.DO_NOTHING,db_column='room_ID',blank=True, null=True) serialnumber = models.CharField(db_column='serialNumber', max_length=20, blank=True, null=True) # Field name made lowercase. accessory = models.ForeignKey('self', models.DO_NOTHING, db_column='accessory', blank=True, null=True) def __str__(self): return self.genericItem.genericItemName class tblFiles(models.Model): #one could upload files for a item or genericItem file_ID = models.AutoField(primary_key=True) filename = models.FileField(null=False, blank=False, upload_to=("somewhere")) description = models.CharField(max_length=200, blank=True, null=True) item = models.ForeignKey('item', models.DO_NOTHING, db_column='item_ID', blank=True, null=True, related_name="itemFile") genericItem = models.ForeignKey('genericItem', models.DO_NOTHING, db_column='genericItem_ID', blank=True, null=True, related_name="genericItemFile") def __str__(self): return os.path.basename(self.filename.name) admin.py class tblFilesInline(admin.TabularInline): model = tblFiles extra = 0 fields = … -
Django SearchVector on model IntegerField
If I have a simple model like: class Book(models.Model): title = models.TextField() year = models.IntegerField() How can I use SearchVector in postgres to allow for searching on both the title and year fields? E.g. so "Some Book 2018" would query over both the title and year fields. If I try doing this like: q = SearchQuery('Some') & SearchQuery('Book') & SearchQuery('2018') vector = SearchVector('title') + SearchVector('year') Book.objects.annotate(search=vector).filter(search=q) Then I hit the error DataError: invalid input syntax for integer: "" LINE 1: ...|| to_tsvector(COALESCE("book_book"."year", '') || ' '... Is there anyway I can search the Integer field too? -
What is the best way to save images when using docker?
In the same context of the question: Saving images on files or on database when using docker is there any service or better way to make this persistence offline? Another option, other than the database or files. -
React + Django app refreshes for every deletion in Django admin panel
I'm not really sure what to share (i.e. which part of my application code) as I'm still a beginner with React so please bear with me. I have a React application running on top of a Django application. Basically, there are Django Admin Panel URLS, REST API URLS in Django, and one path to catch all paths that don't belong to the first two groups. I have a page (or a React Container) that calls Django's REST API to query all entries in the users DB Table. This part is okay but what I've noticed is, everytime I manually delete a row in the Django Admin Panel, the whole page refreshes. What are possible reasons for this? By the way, I'm using Redux as well to manage the whole application state. -
How do I retrieve data from tables in Django that are not directly joined?
I have a Response table: class Response(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, default=13, on_delete=models.CASCADE) Response = models.TextField() Client = models.ForeignKey(ClientDetail, default=8, on_delete=models.CASCADE) Planit_location = models.ForeignKey(Planit_location, default=1, on_delete=models.CASCADE) Date_added = models.DateField(default=datetime.date.today) Document = models.ForeignKey(Document, default=0, on_delete=models.CASCADE) def __str__(self): return self.Response I am able to retrieve data from other tables that it is directly joined to e.g. Questions, Topic, Client: views.py clientList = ClientDetail.objects.all().order_by('Client_name') topicList = Topic.objects.all().order_by('Topic_name') Now I want to retrieve "Sector Name" from my Sector Table: class Sector(models.Model): Sector_name = models.CharField(max_length=255, default='Sector_name') def __str__(self): return self.Sector_name Which is joined to my Client Table: class ClientDetail(models.Model): Sector = models.ForeignKey(Sector, default=8, on_delete=models.CASCADE) Client_name = models.CharField(max_length=255, default='Client_name') class Meta: ordering = ['Client_name'] def __str__(self): return self.Client_name I cannot use the same method i did with Client as it cannot find a "Sector_id" field in the Response table: sectorList = Sector.objects.all().order_by('Sector_name') **THIS DOES NOT WORK** As of this moment, i am only able to retrieve "Sector_id" from my Client table but i what i want is the "Sector Name" Is there something i should be adding into my documents.py file? As i cannot use the same method i did for previous models: class ResponseDocument20(DocType): Client = fields.NestedField(properties={ 'Client_name': fields.TextField(), 'pk': fields.IntegerField(), }, … -
Can't override my resourcers.py class model attribute
I am using the django-import-export package. I need, everytime the user send a .csv table, to create a column in the .csv file and fill every row with the logged user. What I did is: In my resources.py file: class ProductListResource(resources.ModelResource): class Meta: model = ProductList skip_unchanged = True report_skipped = True exclude = ('id',) import_id_fields = ('sku',) In my models.py file: class ProductList(models.Model): sku = models.CharField(primary_key=True, max_length=200) client = models.ForeignKey(get_user_model(), default=1, on_delete=models.CASCADE) name = models.CharField(max_length=256) description = models.CharField(max_length=1000) storage = models.CharField(max_length=256) cost_price = models.CharField(max_length=256) sell_price = models.CharField(max_length=256) ncm = models.CharField(max_length=256) inventory = models.IntegerField(null=True) And finally in my views.py file: def simple_upload(request): if request.method == 'POST': product_resource = ProductListResource() product_resource.Meta.model.client = request.user.id dataset = Dataset() new_product_table = request.FILES['myfile'] dataset.load(new_product_table.read().decode('utf-8'), format='csv') result = product_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): product_resource.import_data(dataset, dry_run=False) # Actually import now context = {'product_list': ProductList.objects.filter(client=request.user.id).all()} #.filter(client=request.user.username) return render(request, 'Clientes/import.html', context) My problem is that in the table appears that the value was changed, but if I click in the object, at admin page, the user that is selected is the first one.