Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display values from a database in 3 columns
enter image description here Hello World, i need your help! I try to find how to display data in 3 columns.( like at picture ) I work in django-framework. Right now i have 1 column. I have: index.html {% block content %} {% for post in posts %} {% include 'face/includes/post_card_template.html' %} {% endfor %} {% endblock %} post_card_template.html <h1 class='mb-5'> </h1> <div class="card mb-3" style="width:400px; border-radius: 8px; " > {% if post.image %} <img src="{{ post.image.thumbnail.400x400 }}" class="img-responsive" style="border-radius: 8px;" alt="Card image" font-size:8px ;> {% endif %} <div class="card-body"> <h4 class="card-title">{{ post.title }}</h4> <p class="card-text">{{ post.body1 }}</p> <p class="card-text">{{ post.body2 }}</p> <p class="card-text">{{ post.body3 }}</p> <p class="card-text">{{ post.body4 }}</p> <p class="card-text">{{ post.body5 }}</p> <a href="{{ post.get_absolute_url }}" class="btn btn-secondary">Read</a> </div> </div> -
DRF: Parent-Child Relationship Serialization to Dictionary instead of List when using unique_together
I'm relatively new to using Django and Django Rest Framework, but here's what I'm trying to do. I have two models: class Parent(models.Model): name = models.CharField() class Child(models.Model): parent = models.ForeignKey(Parent) name = models.CharField() age = models.IntegerField() class Meta: unique_together = ('parent', 'name',) I want to serialize parent such that a GET on a parent returns something of the form: { name: <parent name>, children: { <child name 1>: <age>, <child name 2>: <age> } } Currently, I can only figure out how to return a list of the children by using a serializer such as: class ParentSerializer(serializers.ModelSerializer): children = ChildrenSerializer(many=True,read_only=True) class Meta: model = Parent fields = '__all__' Which returns: { name: <parent name>, children: [ { name: <child name 1>, age: <child age 1> }, { name: <child name 2>, age: <child age 2> } ] } How can I get the parent serializer to return a single dictionary under 'children' keyed by the child's name instead of a list of dictionaries? -
With statement with two variables
How would I combine a with with a firstof in the django template? For example: {% firstof item.item.master_id item.tracktitle.master_id %} {% with ^^ above as master_id %} -
Run wsgi with apache and django in anaconda environment
I am trying to run a django application with wsgi_mod and apache2. But for some strange reason it cannot import django. # /etc/apache2/apache2.conf WSGIDaemonProcess myapps python-home=/home/user/miniconda3/envs/django/ WSGIProcessGroup myapps WSGIScriptAlias /koala /var/www/production/Koala/Koala/wsgi.py <Directory /var/www/production/Koala/> <Files wsgi.py> Require all granted </Files> </Directory> The application sits in /var/www/production/Koala. My conda enviromnent is installed in /home/user/miniconda3/envs/django. I installed wsgi inside the conda environment. I tried different things, but nothing worked. This is what I did to get wsgi running. sudo apt-get install libapache2-mod-wsgi pip install mod_wsgi conda install -c https://conda.binstar.org/travis uwsgi It looks like wsgi is just not working with conda environments and I have to use virtualenv?? Wsgi works, I can render a test file just fine. Though, when I go to localhost/koala the /var/log/apache2/error.log shows: from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' I searched a lot, but could not find an answer that addresses this properly. -
Django For loop not outputting anything
Just getting into Django and im confused why this for loop isnt printing anything. Im not getting any errors, heres my code; My Views Page; GivenMovies = [ { 'Name': 'Thor', 'Genre': 'Action', 'Rating': '7.0', 'Content': 'Mad Movie', 'Date_Posted': 'January 18, 2017' }, { 'Name': 'Constantine', 'Genre': 'Action, Sci-Fi', 'Rating': '7.2', 'Content': 'Another madness of a movie', 'Date_Posted': 'January 18, 2015' } ] def MainPage(request): AllMovies = {'Movies': GivenMovies} return render(request, 'Movies/HomePage.html', AllMovies) my forloop; {% extends "Movies/Parent.html" %} {% block content %} <h1> is showing</h1> {% for Movies,Value in AllMovies.items %} <h1> {{ Movies.Name }} </h1> <p> Genre: {{ Values.Genre }} </p> <p> Rating: {{ Values.Rating }}</p> <p> Content: {{ Values.Content }} </p> <p> Posted on: {{ Values.Date_Posted }} </p> {% endfor %} {% endblock content %} Could someone please point out where i am going wrong, thank you. -
Take img url from form and save to an imagefield in django
Okay so I first compare two image files successfully. If they are equal, a drop down menu is populated with their hrefs allowing the user to select the href of one of the images. I use ajax requests to populate this drop down menu successfully. Now for the catch: the model field is an ImageField, but the form field is a select field holding the hrefs. How can I take the selected href and save it to the image field successfully in Django? Like i explained, I am rendering the data correctly and I am populating the drop down correctly, I just do not know how to take the selected href from the dropdown and assign it to the imagefield on the model. -
Django query after multiple keywords in database
I have a line of code that looks up in my database after Fields containing the string Waiting, but I also want it to look for the field named Timeout. My current code looks like this: query_running = Usertasks.objects.all().filter(user=request.user).filter(TaskStatus="Waiting") This works perfectly but I need to also search for the string Timeout I tried code that looked like this, but this doesn't work. query_running = Usertasks.objects.all().filter(user=request.user).filter(TaskStatus="Waiting", "Timeout") And just to be clear, it should search for either word. Both words are not going to be present at the same time. -
Foreign key in the database
I'm Brazilian then the table: Pessoa == Person Veiculo == Vehicle is a parking system with the Vehicle and Monthly tabs, and I need this when registering an entry in the Monthly. Since each person has many vehicles, but one vehicle has only one person. In other words, when registering an entry in the parking lot, it is necessary that, when the vehicle is accessed, only the vehicles that are registered in the name of the Person I'm using the SqlLite 3 from Django Foreign key in the database Models.py class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7) placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False, ) cor = models.CharField(max_length=15, blank=False) observacoes = models.TextField(blank=False) class Mensalista(models.Model): veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE, blank=False) inicio = models.DateField(blank=False) validade = models.DateField(blank=False) proprietario = models.ForeignKey( Pessoa, blank=False, on_delete=models.CASCADE) valor_mes = models.DecimalField( max_digits=6, decimal_places=2, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) -
Django Form ChoiceField not working for 1 element lists
I discovered a weird instance while working on a Django web app. I have a list of options that I would like users to select from a drop down list. To accomplish this I used the ChoiceField from Django forms. However, when my options contain only a single 2-tuple (eg. (("1", "one")) is invalid) nothing is displayed and I get the error "not enough values to unpack (expected 2, got 1) at line builds.as_p" in index.html. Once I add at least one more 2-tuple (eg. (("1", "one"), ("2", "two")) is valid) to my options this is fixed. What could be causing this? forms.py class BuildForm(forms.Form): OPTIONS = (("1", "One"), ("2", "two")) Build_IDs = forms.ChoiceField(choices=OPTIONS) views.py from .forms import BuildForm def index(request): builds = BuildForm() return render(request, 'ReportGenerator/index.html', {"builds":builds}) templates/App/index.html {% if builds %} <h2>Pick a Build</h2> <form method="POST" class="build-form">{% csrf_token %} {{ builds.as_p }} </form> {% else %} <p>No reports are available.</p> {% endif %} -
Unittesting Django Channels
I'm working on a project which makes use of Javascript and Python so I'm using sockets for communication. I'm having issues writing tests for the django channels part. I have this python celery task @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]) }) }) The javascript which sends net to the socket. exportNet(framework) { this.exportPrep(function(netData) { Object.keys(netData).forEach(layerId => { delete netData[layerId].state; if (netData[layerId]['comments']) { // not adding comments as part of export parameters of net delete netData[layerId].comments; } }); console.log("Net: "+JSON.stringify(netData)); this.sendSocketMessage({ framework: framework, net: JSON.stringify(netData), action: 'ExportNet', net_name: this.state.net_name, randomId: this.state.randomId }); }.bind(this)); } Now I'm trying to write tests for these. import unittest from celery import Celery from ide.tasks import export_caffe_prototxt from channels import Channel 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) response = … -
Filtering on foreign key in django
In django, why does it not allow: ItemInstance.objects.filter(provider_id__icontains='sting')) But it does allow: ItemInstance.objects.filter(provider__name__icontains='sting')) provider_id and provider__name would give the same value, as the foreign key is to the name field. Why doesn't it allow the first method of referencing it? -
django 2.1 celery not execute asyncron task
i try to execute background function using celery: this is my current code : from VideoPublish.models import TitleVideo, Videos from celery.decorators import task from UploadExpert.celery import app # Create your views here. demo_titles =['title1', 'title2', 'title3'] @app.task(ignore_result=True) def GetTitles(video_id): video = Videos.objects.get(pk=video_id) for title in demo_titles: t = TitleVideo( title=title, video_id=video.id ) t.save() this is call function : GetTitles.delay(video_id=obj.id) and this is a celery error: https://gist.github.com/scaltro/cc6152f82b0fbf501af396b8ad812e91 i want to know where i'am wrong, and how i can solve this problem -
How to go over JSON in JS
I'm developing an Ajax query to Django and works fine, returns the correct value but when i want to access to info appears this error: $ SyntaxError: missing name after . operator I returned the information query with these lines in python file: attributes = MyModel._meta.get_fields() objects = MyModel.objects.all() data = serializers.serialize('json', objects, fields=(attributes[1].name)) print(data) return HttpResponse(data, content_type='application/json') print(data) output: [{ "model": "contenttypes.contenttype", "pk": 11, "fields": { "model": "accountingseat"} }, { "model": "contenttypes.contenttype", "pk": 12, "fields": { "model": "bill" } }] javascript file: function functionName(param) { for (var i = 0; i < param.length; i++) { console.log(param[i]); console.log(param[i].pk); var fields = param[i]['fields']; for (var x = 0; x < fields.length; x++) { console.log(fields.[x]); //error line } } } console.log() output: Object { model: "general.module", pk: 1, fields: { name: "General" } } 1 The problem is that i cant access with name because name of attribute change in each model. Anybody could help me ? How can i access to fields Thanks in advance. -
How to INSERT INTO [local table] SELECT … FROM [foreign data wrapper table] in Django?
Setup A PostgreSQL database set up using Django Rest Framework (DRF) which will eventually take over from the legacy system. Contains hundreds of millions of rows. A single PostgreSQL remote instance with a legacy schema. Task Import the data from the legacy database into the Django database in a reasonable time (minutes) so that this task can be done during CI runs. Work so far We first created a separate Python script to use the Django API to import data. The team knew this was going to be slow, but we wanted to test the API and ended up getting some useful feedback. Inside our development environments (in a VM) this ended up creating maybe a couple dozen rows per second. We now want to import much more data. We first moved the script into a Django admin command so that we could instantiate the DRF serializers directly rather than calling the API. This was a little bit faster. We then tried to instantiate the DRF serializers with many=True, but this was not noticeably faster. The current fastest implementation imports maybe 80-100 rows per second, so we decided to change tack. The importer is thoroughly tested, so we decided to … -
django editable ListView
I have a model: class Question(models.Model): question_text = models.CharField(max_length=200, unique=True) pub_date = models.DateField(verbose_name='date published') def __str__(self): return self.question_text I want to list all questions and edit them like inline forms. I can list questions with ListView: class UpdateDirectry(generic.ListView): model = Question template_name = 'accounts/editable_directory.html' fields = ['question_text'] queryset = Question.objects.all() but this just list all questions. I can also edit each question with UpdateView but I want all questions on a page to edit them. -
Django Admin Inline static initial data
Is there a way to simply set default values for a new inlined model instance in Django Admin? I want the same default values to always appear when the "+ Add another" button is pressed. The same thing as using get_changeform_initial_data on a normal ModelAdmin, but for an inline: def get_changeform_initial_data(self, request): return {'fieldA': 'always here', 'fieldB': 0} I've tried every solution on the internet, played a lot with formsets, but couldn't make it work. Any ideas? -
Django Rest Framework - object has no attribute post
I have this url in my urls.py path('foo/bar/api', foo.APIBar.as_view(), name='foo-bar-api'), and in my view.py I have this class that hands the api: class APIBar(APIView): def post(request, self, format=None): date= request.POST['date'] person= get_object_or_404(Person, id=request.POST['person']) return Response(status=status.HTTP_201_CREATED) And I'm trying to send this ajax: $.ajax({ url: "{% url 'foo-bar-api' %}", method: "POST", data: { date: date.val(), person: person.val() } }); But Django it's giving this error to me: AttributeError: 'APIBar' object has no attribute 'POST' I don't know why this is happening. I used the same structure in other models and works like a charm, but this one it's giving this error. Please, can you tell me what am I doing wrong? I spent some hours trying to fix this error. -
django 2.1 execute function on add new item from admin panel
i need to execute command every time when admin add new item in tabele Videos. Example admin.py class VideosAdmin(admin.ModelAdmin): list_display = ('__str__', 'author', 'created_at', 'title_gen', 'deleted') list_filter = ['created_at', 'author', 'deleted'] search_fields = ['Title', 'Description', 'Tags', 'Playlist'] exclude = ['title_gen', 'Playlist', 'Tags', 'deleted', 'author', 'Category', 'Language'] class Meta: model = Videos def get_queryset(self, request): return self.model.all_objects.all() def save_model(self, request, obj, form, change): if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() admin.site.register(Videos, VideosAdmin) Every time when admin add new Video item i need to execute function proccessing(video_id), how i can do this ? -
Django-filters FilterView shows empty list on page load
So I want to link to a given page that has filters on it, and have it display every item in the table before I click search, and only stop displaying items when bad input is given. My problem is similar to the following problem, with a few differences. Empty result list on django-filter page startup The differences being the poster's default behavior is my desired behaviour and I am using class based views, not functional views. My urls: from django.urls import path from . import views app_name = 'advising' urlpatterns = [ path('', views.MyList.as_view(), name='MyList'), ] my views: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views import generic from django.template import loader from .models import * from django_filters.views import FilterView from .filter import * class MyList(FilterView): template_name = 'advising/MyList.html' context_object_name = 'tables' filterset_class = MyFilter def get_queryset(self): return Table.objects.order_by('Name') my filter: import django_filters from .models import Table class MyFilter(django_filters.FilterSet): Name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Table #The table this form will reference fields = ["Name"] my template: <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> {% if tables %} <ul> {% for table in tables %} <li>{{table}}</a></li> {% endfor %} </ul> {% else %} … -
Search function returning nothing -Django
def Search(request): if request.method == 'GET' and request.GET['x']: parameter = request.GET['x'] results = Category.objects.filter(advert__Seller_Name__icontains = parameter) return render(request, 'campusbuy/search.html', {'results': results}) else: return render(request, 'campusbuy/search.html') Above is my search function. When I try to search in my template, it returns nothing. However, when I deliberately search for a Seller_name that's not in the db it returns the {% else %} value. Below is the template: % extends 'campusbuy/base.html' %} {% block content %} {% if results %} {% for ads in results.advert_set.all %} <p>{{ads.Seller_Name }}</p> <p>{{ads.Location}}</p> <p>{{ads.Description}}</p> <p>{{ads.Asking_Price}}</p> {% endfor %} {% else %} <p>No Ad matched your search criteria.</p> {% endif %} {% endblock %} Thank you in advance! -
Django tables not updating column data
I'm trying to pull data from mongodb and display it as a table in display.html page. My data from table looks something like this: [{u'Subjects': u'[Sub1, Sub2, Sub3, Sub4]', u'Student Name': u'A'}, {u'Subjects': u'[Sub2, Sub12, Sub7, Sub9]', u'Student Name': u'B'},{u'Subjects': u'[Sub1, Sub2, Sub14]', u'Student Name': u'AC'}, Below is my code: views.py def data_list(): dis_data = db_data.find() table = DataTable(list(dis_data)) RequestConfig(request).configure(table) return render(request, 'app/dispaly.html', {'table': table}) My tables.py import django_tables2 as tables class DataTable(tables.Table): Names = tables.Column(verbose_name = "Student Name") Subjects = tables.Column() display.html <html> <body> {% load render_table from django_tables2 %} <div> {% render_table table %} </div> </body> </html> But when displaying its only displaying subjects but not Student Name. Where is it going wrong ? -
django 2.1 Cannot delete Item
i want to delete element from table Video, and return me this error, Deleting the Video 'add test video' would require deleting the following protected related objects: Video Title: dadsadas this is my curent models: class Videos(models.Model): Title = models.CharField(max_length=100, unique=False, help_text='video title') class TitleVideo(models.Model): title = models.CharField(max_length=100, unique=False, help_text='youtube video title') video = models.ForeignKey(Videos, related_name='video_id', null=False, blank=False, on_delete=models.PROTECT) i want do this : when i delete item from table Videos, automatic remove all titles related to videos items, how i can do this ? -
Django : ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'myblog.routing'
I searched stack over a day but still haven't got any solution till now. I made a chat app which uses websockets. setting.py ASGI_APPLICATION = "myblog.routing.application" directory structure mysite ->myblog ->chat ->myblog ->routing.py ->otherfiles routing.py inside of ,myblog directory from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) this is the error im getting File "C:\Users\JIDNYE~1.J\MYPROJ~1\mysite3\lib\site-packages\channels\routing.py", line 35, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'myblog.routing' Im stucked here from a very long time , searched every where but got no solution on web. Will be great help if someone can solve error. -
Is it possible to run a group containing chains in celery?
I am trying to run some chains inside a group and for some reason it is being blocked or and the task doesn't start at all. It just stops and halts. Basically the code boils down to this: group([ chain(chained_tasks[0]), chain(chained_tasks[1]) ] ).apply_async() which hangs forever, I would appreciate any help, I checked backendresult and rabbitmq they are running fine. I can even execute chained_tasks[0].apply_async() and it works properly. -
how to add downsampling using bokeh combined with django
i need downsampling for the following plot/figure: #plotting.py p1 = figure(title="Main Plot, start time: " + str(start_time), output_backend="webgl", toolbar_location="right", width=plot_width, height=plot_height) ... mass_spec["xs"].append(x) mass_spec["ys"].append(y) mass_spec["y_labels"].append(str(cycle) + " " + str(cycle_data[channel_name][0])) ... mass_spec['color'] = colours source = ColumnDataSource(mass_spec) p1.multi_line(xs="xs", ys="ys", legend="y_labels", line_width=2, line_color='color', line_alpha=0.8, # hover_line_color='color', hover_line_alpha=1.0, source=source) or p1.line(x, y, alpha=1, color=colours[colour_cnt], legend=(str(cycle) + " " + str(cycle_data[channel_name][0])) , line_width=2) ... script1, div1 = components(p1, CDN) in the html <div class="{{ plot_size }}"> {{ plotting_values.the_div1|safe }} {{ plotting_values.the_script1| </div> This all works fine. now i want to add downsampling, depending on the actual zoom of the chart (in total i got 2.8 million points) should be downsampled to 10%, 1% or even less) thaught about adding a Callback to the components() or somehow... or do i need to use curdoc() and implement the server view into my django template? if yes, please give a full example (plotting.py, template) --> its should be startable without terminal comand "bokeh serve", just by starting it with python manage.py runserver