Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Keep overrided User Model (via AUTH_USER_MODEL) in "Authentication and Authorization" group
I am on Django 2.1.2. What I am trying to do is override the user model as pre suggestion here It work perfectly fine, my problem is about the custom user model show under "Admin > myapp" instead of "Admin > Authentication and Authorization" After some search I have tried 2 things. 1) Make user of the app_label = 'auth' statement to put it back to app auth, but it break AUTH_USER_MODEL = myapp.User in setting.py, coz it is now auth_user. class User(AbstractUser): pass class Meta: app_label = 'auth' 2) Move Group to myapp with below statement, so I can put both User and Group together, but it break the user model coz it moved auth_group to myapp_group apps.get_model('auth.Group')._meta.app_label = 'myapp' Any input are welcome Bill -
Change the connection port of Django Channels chat
Currently in my website I am using a websocket chat feature using Django Channels which uses Redis as its channel Layer. Currently I am configuring channels in my Django app. in the following manner CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, "ROUTING": "main.routing.channel_routing", # We will create it in a moment }, } Now the chat works fine however in order to use it on my development machine I have to use the following address: ws://127.0.0.1:8000/chat/stream/ Is there anyway for me to change the connection port 8000 instead of 575 ? -
chart js and django: Uncaught SyntaxError: Unexpected number
Hi thanks for reading and helping I been trying to draw a line chart with charts on my Django template and did it with some random numbers. Now I try to put data form my Django database(PostgreSQL), but I receive this errors Uncaught SyntaxError: Unexpected number I suspect is because I'm putting a string list into my chart, as I can see my data from chrome debugger. If you know how please show me an example of code to solve this, is very hard for me visualize. This my code: <!--this top left side chart --> {%block ECchart%} <canvas class = "my-4 chartjs-render-monitor" id="ECChart"></canvas> <script> var X = []; var Y = []; var ctx = document.getElementById("ECChart"); var ECChart = new Chart(ctx, { type: 'pie', data: { labels: [{% for tank_system in tank %}{{forloop.counter}} {%endfor%}], //x-Axis datasets: [{ data: [{% for tank_system in tank %} {{tank_system.EC}} {%endfor%}], //Y-Axis borderColor: "#3e95cd", fill: false, }] }, options: { scales: { xAxes: [{ display:true }], yAxes: [{ ticks: { beginAtZero:false } }] } } }); </script> {%endblock%} This my django view codes: from django.shortcuts import render from zigview.models import tank_system from django.contrib.auth.decorators import login_required import logging logger = logging.getLogger(__name__) # object link index … -
Django selenium testing 403
class MySeleniumTests(LiveServerTestCase): def setUp(self): self.selenium = WebDriver() settings.CSRF_COOKIE_SECURE = False settings.SESSION_COOKIE_SECURE = False super(MySeleniumTests, self).setUp() def tearDown(self): self.selenium.quit() super(MySeleniumTests, self).tearDown() def test_register(self): selenium = self.selenium # Opening the link we want to test selenium.get(self.live_server_url) selenium.execute_script("return openLoginModal()") time.sleep(2) selenium.find_element_by_id('register-now').click() time.sleep(1) first_name = selenium.find_element_by_id('name') first_name.send_keys("test_firstname") last_name = selenium.find_element_by_id('lname') last_name.send_keys("test_lastname") email = selenium.find_element_by_id('email') email.send_keys("test@gmail.com") mobile = selenium.find_element_by_id('phone') password = selenium.find_element_by_id('password') password.send_keys('123456') mobile.send_keys("0123456789") primary_address = selenium.find_element_by_id('primary_address') primary_address.send_keys("primary address") secondary_address = selenium.find_element_by_id('secondary_address') secondary_address.send_keys("secondary address") select = Select(selenium.find_element_by_id('landmarkInput')) select.select_by_visible_text('Other') selenium.find_element_by_id('datepicker').click() time.sleep(1) month_from = selenium.find_element_by_xpath("//div/select[@class='ui-datepicker-month']") select_from_month = Select(month_from) select_from_month.select_by_visible_text("Apr") time.sleep(1) day_from = selenium.find_element_by_xpath("//table/tbody/tr/td/a[text()='1']") day_from.click() time.sleep(2) submit = selenium.find_element_by_id('signup-button') submit.send_keys(Keys.RETURN) time.sleep(20) in the signup form html there is csrf which works fine in production {% csrf_token %} While running test, on submitting the form, the csrf token is missing in the header in post call. Any help will be appreciated. -
The document created by mongoengine document model, is there a way to implement proxy model (similar to django mysql proxy model)?
how to implement the proxy model with mongoengine in django as the mysql backend? eg: import datetime from mongoengine import signals, document, StringField, BooleanField, DictField, DateTimeField, IntField, DynamicDocument, ListField, EmbeddedDocument, EmbeddedDocumentField class Job(document.Document): task_id = StringField(null=False) employees = ListField(field=IntField()) flows = ListField(field=IntField()) execute_time = DateTimeField(default=datetime.datetime.now) finished_time = DateTimeField() meta = { "indexes": [ 'task_id', ], 'collection': 'job', 'strict': False, 'auto_create_index': False, 'allow_inheritance': True } proxy model class JobProxy(Job): @classmethod def create_job(cls, **kwargs): raise NotImplementedError() Job created documents, there is no way to query through jobproxy.ojbects, is there any way to support in mongoengine? -
PyCharm code inspection settings for Django
I like PyCharm code inspection, which helps me to discover my code issues earlier. But when developing with some Python framework such as Django, it warns me for something that is not actually an issue. I don't want to simply disable the inspection for I still need it to help me checking my code. I just want it to be aware of the framework-specific features and specifically ignore those warnings. For example, for the example "polls" application on Django's official web site (https://docs.djangoproject.com/en/2.1/intro/tutorial02/), it suggests me to oeveride method str to return the record content: File: polls/models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text But when I want to change the the "return" line to: return 'id:%s, question:%s, date:%s' % (self.id, self.question_text, self.pub_date) PyCharm warns me for the "id" field (pointed by the red arrow): But the "id" field is automatically generated by Django. My code runs well with the code. So, I wonder if there is a way to make PyCharm being aware of the Django behavior. In this example: PyCharm should not warn for code "self.id", for field "id" is automatically added by Django and the code won't … -
I overrode the clean() method in my django form, and fixed a bug that arose. But I dont understand how the bug was fixed
I am trying to add some validation into a form. Validation 1: quantity_moved should be above 0. Validation 2: source and destination must be different Validation 3: quantity_moved must be lower than the quantity at source location. Buggy Code # NOTE: Overriding the default method def clean(self): cleaned_data = super().clean() source = str(cleaned_data['source']) destination = str(cleaned_data['destination']) quantity_moved = cleaned_data['quantity_moved'] item = cleaned_data['item'] # Checking if the source and destination are same if destination == source: msg = 'エラー:移動先と移動元が同じです。' self.add_error('source', msg) self.add_error('destination', msg) # Checking if the quantity to move is more than the current stock at the source location max_qty = ActualStock.objects.filter(item=item, location=cleaned_data['source'])[0].current_stock print(">" * 80, max_qty) if quantity_moved > max_qty: msg = "エラー:移動元に商品の数は足りません。現在, {0}に {1}の数は {2} です。".format(source, item, max_qty) self.add_error('quantity_moved', msg) return cleaned_data Now, during testing if i enter same values for both source and destination(both are selected from respective dropdowns which points a same table in DB), I get a KeyError. Now, if I change the order of the checks that I am performing as shown below, the code works. Working Code: # NOTE: Overriding the default method def clean(self): cleaned_data = super().clean() source = str(cleaned_data['source']) destination = str(cleaned_data['destination']) quantity_moved = cleaned_data['quantity_moved'] item = cleaned_data['item'] # Checking if … -
Check for installed django apps using django tags
I'm writing code for an app can be installed like a module on multiple django projects, each of which could each be configured differently. I'm looking for a way to conditionally load a package depending on how the project is configured. If a specific package is listed in INSTALLED_APPS in the settings.py file of the project, then load the package with {% load my_package $}. I'm envisioning something like: {% if package_is_installed %} {% load package %} {% endif %} <body> {% if package_is_installed %} {% use part of the package %} {% endif %} </body> Is this possible with tags or some other html or javascript implementation? -
Can't submit form with UserCreationForm
I'm learning django with v1.8 and I'm trying to create a form, but submit doesn't work and I don't have error.. If someone can help me, it will be very nice. Thank you views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render def register(request): if request.method == "POST" : form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = UserCreationForm() args = {'form': form} return render(request, 'polls/register.html', args) register.htlm {% block content %} <form action="polls/register.html" method="post"> {% csrf_token %} {{ form.as_p }} <button type="button">button</button> </form> {% endblock %} -
2 Separate user accounts in django admin
I m wondering if it is possible to have 2 separate accounts for django/python. I have a user(CLIENT) account but also looking to have a service provider account with a a login on the same project. Is this possible and what is the best method? -
Why does DjangoFilterBackend returns no result if query value does not exist in my data?
I am using drf and django-filters to perform some filtering on my data. For the filtering backend I use django_filters.rest_framework.DjangoFilterBackend. class ProductsViewSet(LoginRequiredMixin, ModelViewSet): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend, rest_framework.filters.SearchFilter, rest_framework.filters.OrderingFilter,) filter_class = ProductFilter filter_fields = ("title", "description", "company", "country", "status",) search_fields = ("title", "description", "company", "country", "status",) ordering_fields = ("title", "description", "company", "country", "status",) My issue is that if I try to filter with multiple values and one of them does not exist I get no results. For example, if I want to filter based on the field company which is a ForeignKey, using 2 values: company google with an id=2 does not exist in any of my objects and company microsoft with an id =3 that does exist, the following will return no results api/products?company=2&company=3 The same happens if the field is just a CharField. At first, I had implemented my own filtering customizing get_queryset , but I thought that I might make things less complicated using a filter backend. I am not sure why this is happening, if the two values that I am filtering with exist everything works fine. -
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 …