Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'ModelFormOptions' object has no attribute 'private_fields'
I get this error when trying to create a custom Form on the Admin view, I don't see any solution on stackoverflow (yes similar problems) so I think it's a good idea to post it: My Models.py: class Webhook(models.Model): url = models.CharField('URL', max_length = 60, unique = True) description = models.CharField('Descripcion', max_length = 255) enabled = models.BooleanField('Enabled', default=True) event = models.CharField('Evento', max_length=1, choices=Events.EVENTS_CHOICES) My Forms: class WebhookForm(forms.ModelForm): class Meta: model = Webhook fields = '__all__' def save(self, commit=True): print('saveeeeeee') webhook = super().save(commit=False) webhook.code = webhook.id # Get token response_token = TOKEN.get() if response_token['success']: # Create Webhook url = 'https://sandbox.bind.com.ar/v1/webhooks' headers = { 'Content-type': 'application/json', 'Authorization': 'JWT ' + response_token['token'] } data = { 'url': webhook.url, # Debera responder status_code == 200 'description': webhook.description, 'code': webhook.id, 'enabled': webhook.enabled, 'events': webhook.event } data_json = json.dumps(data) response = requests.put(url, data= data_json, headers = headers) response_json = response.json() # Result result = {} if response.status_code == 409: result['success'] = False result['details'] = response_json else: result['success'] = True result['data'] = response_json # If ok, Save if commit & result['success']: webhook.save() return result['success'] My Admin.py class WebhookAdmin(forms.ModelForm): # Only to override a form in admin class Meta: model = WebhookForm fields = '__all__' # Style to … -
How to create a repeating generic field on a Django model that does not render entries from other objects in the admin?
I'm fairly new to Django, but wondering how to get one seemingly obvious thing to work in my model definitions. For a model "Product" I want to be able to add any number of links, so I made a more or less generic "Link" model with a display name field and a URL field. In Product I add this as ManyToManyField with the respective Link model. This works like intended in the admin view in that I can add any number of links and do so inline. However, I only want the admin view to list existing links of this product, let the user delete them, and let the user add new ones. What I do not want is for the inline link field to display all other product’s links. Am I confused with the Field Type or overall approach, or how can I get this to work? I was wondering if the through options is the way to do this, or if this is merely something you should do in the admin forms and not on model level? -
how to call two functions at a time in django ,
how to call two functions at a time in Django ,in which one function takes many minutes to executes and one functions takes fraction of seconds to executes but 2nd function which takes less minutes needs to be updated in the html page dynamically until the first function completes -
give template tags inside jquery prepend function
my jquery: else if(json.event == "Follow Notify"){ console.log(json.sender) $("#not").prepend('<li class="media">'+ '<a href="javascript:;">'+ '<div class="media-left">'+ '<i class="fa fa-bug media-object bg- silver-darker"></i>'+ '</div>'+ '<div class="media-body">'+ '<h6 class="media- heading">'+json.notification'+ '<i class="fa fa-exclamation-circle text- danger"></i></h6>'+ '<p>'+json.notification+'</p>'+ '<a href="{% url "student:accept_follow" pk=request.user.id notify='+json.sender+' %}">Accept</a>'+ '<a href="{% url "student:reject_follow" pk=request.user.id notify='+json.sender+' %}">Reject</a>'+ '</div></a></li>') } I want to prepend html code with django url tags ..Im receiving a json and parsing it with json.sender..but it seems its taking it as a string .HOw do i propelry allow django template tags inside this jquery function? -
Python Django 2 template blocks overriding is not working
I'm working on a Python(3.6) and django(2.0) project in which I need to implement multiple templates with inheritance. Here are my templates: The first template is: dashboard-base.html: {% block header %} // Header content like loading css and js files along with title {% endblock%} {% block body %} {% block dashboard_header %} Load dashboard specific header here - some html {% endblock %} {% block navbar %} Load dashboard specific navbar {% endblock %} {% block content %} Will load dynamic content here {% endblock %} {% block footer %} Footer content will go here {% endblock %} {% endblock %} Now I need to load the dynamic content in multiple templates like profile.html and dashboard-personal-info.html. Here's how I have inherited this templates: from profile.html: {% extends 'Utechdata/dashboard-base.html' %} {% block content %} <div class="mdl-grid demo-content"> <h1> This is the another content</h1> </div> {% endblock %} from dashboard-personal-info.html: {% extends 'Utechdata/dashboard-base.html' %} {% block content %} <div class="mdl-grid demo-content"> <h1> This is the another 2nd content</h1> </div> {% endblock %} But in these templates, the content inside the content block is not displaying. what can wrong here? Thank You, -
how to implement Response from flask in Django
I am trying to implement this project using django. What I want to do is once the server is started, I should be able to start the camera from any system that is connected to network and display the feed in that system. I am using Django because I have written other modules of my project with django This is my code so far views.py def index(request): return render(request, 'index.html') # the gen() is part of the server.py code. This has to be added to the start_server() function. # the start_server() function should be rectified def gen(): streamer = Streamer('localhost', 8000) streamer.start() while True: if streamer.client_connected(): yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + streamer.get_jpeg() + b'\r\n\r\n') def start_server(request): return render_to_response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') def start_client(request): cap = cv2.VideoCapture(0) clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) clientsocket.connect(('localhost',8000)) while(cap.isOpened()): ret,frame=cap.read() memfile = StringIO() np.save(memfile, frame) memfile.seek(0) data = json.dumps(memfile.read().decode('latin-1')) clientsocket.sendall(struct.pack("L", len(data))+data) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.imshow('frame', frame) cap.release() The client.py file from the repo is placed under start_client() function in views.py I have made a small change to the client.py file from the repo. I added cv2.imshow('frame', frame) to display the feed in the client's system index.html <html> <head> </head> <body> <div class='container'> <a href='/start_server'><button>Start Server</button></a> <a href='/start_client'><button>Start Client</button></a> … -
Django ORM bulk_create 1:1 related models
I've seen similar questions asked, but vague answers were provided so I would appreciate any feedback. I want to do a bulk create on some related 1:1 objects. I was hoping I could do something like this: class A(models.Model): class B(models.Model): A = models.ForeignKey(A) all_a = [] all_b = [] for i in range(10000): new_a = A() new_b = B(A=new_a) all_a.append(new_a) all_b.append(new_b) with transaction.atomic(): A.objects.bulk_create(all_a) B.objects.bulk_create(all_b) But I'm guessing the A models need to be written to the DB and the actual PK returned and associated with B models before I can write them. Has anyone got a good suggestion on how to do this efficiently? Thanks in advance -
button click event inside bootstrap not work
I use nested modal. when I open main modal for first time it works well but for next time it's button doe'st work. there are multiple button in main modal that lunch other modals. here is main modal <form method="post" action="{% url 'wo_update' form.instance.id %}" class="js-wo-update-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" id="closeCompanyModal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">ویرایش</h4> </div> <div class="modal-body"> {% include 'cmms/maintenance/partialWoForm.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">بستن</button> <button type="submit" class="btn btn-primary">ویرایش</button> </div> </form> and here is one the nested modal inside main modal. for first time buttom work well after reopen the main modal below buttom not work. <!--pip install django-widget-tweaks--> <div class="row"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>فعالیت ها </h5> </div> <div class="ibox-content"> <div class="table-responsive"> <table class="table table-striped" id="task-table"> <thead> <tr> <th></th> <th></th> <th>شرح</th> <th>کاربر مشخص شده</th> <th>زمان تخمینی</th> <th>زمان واقعی صرف شده</th> <th></th> </tr> </thead> <tbody id='tbody_task'> {% include 'cmms/tasks/partialTasklist.html' %} </tbody> </table> <!-- BUTTON TO TRIGGER THE ACTION --> <p> <button type="button" class="btn btn-primary js-create-task" data-url="{% url 'task_create' %}" > <span class="glyphicon glyphicon-plus" ></span> جدید </button> </p> </div> </div> </div> </div> <div class="modal fade" id="modal-task"> <div class="modal-dialog "> <div class="modal-content "> </div> </div> </div> </div> … -
ValueError: underlying buffer has been detached when i run python manager.py makemigrations
error 1 when i run python manager.py makemigrations , the problem as the picture. i check the django source code, find the problem code at here picture 2, it can work when i note this line:self._out.write(style_func(msg)). I don't know how make this problem. django source code -
How to use dot as thousand separator in Django
In my settings.py I have following code: LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = True USE_DECIMAL_SEPARATOR = True DECIMAL_SEPARATOR = "," USE_THOUSAND_SEPARATOR = True THOUSAND_SEPARATOR = "." And in my template I use the number as follows: {% load humanize %} {% load i18n %} {% load l10n %} <div>{% trans "Price" %}: € <b>{{ payment|floatformat:2|intcomma }}</b></div> But still the number is 18,300.00 and I want that it is 18.300,00. Any idea? -
Can't get user info getting error like "unauthorized_client
Error: Description KeycloakAuthenticationError at 401: b'{"error":"unauthorized_client","error_description":"Client certificate missing, or its thumbprint and one in the refresh token did NOT match"}' Please refer my code get solution # Configure client keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/", client_id="testclient1", realm_name="Realm", client_secret_key="******") token = keycloak_openid.token("kishore", "Kichakcb001@") print(token) userinfo = keycloak_openid.userinfo(token['access_token']) print(userinfo) Thanks, Kishore -
django performance is slow
enter image description here I has a performance question.look this image,total time is 231MS,but response time is 1255,every requests has more than about 800ms duration between response and cpu total time.where's consume these times? -
Django Channels Unit Test
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 = … -
django-mptt serialization return children nodes outside of parent node also
I am using django-mptt with django-rest-framework and for recursive serialization I am using djangorestframework-recursive package but it returns child node outside of parent node also. I have tried to_representation() also that leads to same result. from rest_framework import serializers from rest_framework_recursive.fields import RecursiveField from .models import Category class CategorySerializer(serializers.ModelSerializer): children = RecursiveField(many=True) class Meta: model = Category fields = ('id','name','parent', 'children') Output is [ { "id": 1, "name": "Rock", "parent": null, "children": [ { "id": 4, "name": "Corase Rock", "parent": 1, "children": [] }, { "id": 2, "name": "Hard Rock", "parent": 1, "children": [] }, { "id": 3, "name": "Soft Rock", "parent": 1, "children": [] } ] }, { "id": 4, "name": "Corase Rock", "parent": 1, "children": [] }, { "id": 2, "name": "Hard Rock", "parent": 1, "children": [] }, { "id": 3, "name": "Soft Rock", "parent": 1, "children": [] } ] -
How can I disallow the user to go to the register page when he is already logged in? Django 2.1.2
I made an admin panel in django. Which consists of login registration and dashboard for admin but i am facing a problem that: If suppose a user is logged in to the system, and then the user goes to the url and go to register page using the url for ex. localhost/register when he is already logged in and no need of going to register page to register another user account. I don,t want this to happen. How can I disallow the user to go to the register page when he is already logged in. How can we resolve this issue? Please help -
Django upload image failed
I use the ImageField to save the images uploaded. The code is below: //view class UploadImageView(View): def post(self,request): image_form = UploadImageForm( request.POST, request.FILES, instance=request.user) if image_form.is_valid(): image_form.save() return JsonResponse({"status":"success","message":"头像修改成功","icon":"6"}) else: return JsonResponse({"status": "fail", "message": "请尝试重新上传","icon":"5"}) //model image = models.ImageField( upload_to="image/%Y/%m", # upload_to="image", default=u"image/default.png", max_length=100, verbose_name=u"头像" ) //form class UploadImageForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['image'] //html <div class="layui-col-md3 layui-col-xs12 user_right"> <div class="layui-upload-list"> <img src="{{ MEDIA_URL }}{{ request.user.image }}" name="image" class="layui-circle" id="adminFace"> </div> <button type="button" class="layui-btn layui-btn-primary userFaceBtn"><i class="layui-icon">&#xe67c;</i> 更换头像</button> </div> //js, use a frame named layui upload.render({ elem: '.userFaceBtn', accept:'images', url: '/accounts/image/upload/', //Preview local files before:function(obj){ obj.preview(function(index,file,result){ $('#adminFace').attr('src',result); }); //add csrf parameter var data = {}; data.csrfmiddlewaretoken = $("input[name='csrfmiddlewaretoken']").attr("value"); this.data=data; }, done: function(res, index, upload){ return layer.msg(res.message,{icon: res.icon,time: 2000}); }, error:function(obj){ } }); The request is: enter image description here enter image description here But it doesn't get the image and validity is true: enter image description here I just stated learn django and not familiar with it. I hope get your help. Thank you very much. -
Django missed slash in url
I created a url like 'api/personal/'. Everything went right when I did local test using './manage.py runserver'. But when I used factoryboy to create a client and try to get the detail by 'self.user_client.get('api/personal/')', the response showed 404 NOTFOUND because the url had changed to apipersonal/. Does anyone know why did it happen? -
How i can create Model or form for Django admin that not create table in database ?
This technique create table in database but i don't want create table into database. class Email(models.Model): to = models.EmailField(null = False) subject = models.CharField(max_length = 255, null = False) message = models.TextField(max_length = 555, null = False,) class EmailAdmin(admin.ModelAdmin): list_display = ('to','subject','message',) #Here i can send emails to users. def save_model(self, request, obj, form, change): #I commented this line because i don't want to store this model into database. #super(MyAdminView, self).save_model(request, obj, form, change) admin.site.register(Email,EmailAdmin) Any other way to solve this problem ? -
Django testing in creating a user with email address which is from session input, assertRedirects is not working
The user creation is using an email address as USERNAME_FIELD and it is extracted from session and save in the form save(). It seems it is not going further down to the redirection. How can I test the redirection in this case? tests.py class RegistraionViewTest(TestCase): valid_data = { 'email': 'good@day.com', 'password1': 'test1234', } kwargs = { 'email': 'good@day.com' } def test_registration(self): response = self.client.post(reverse('registration'), data=self.valid_data, follow=True) self.assertTrue(response.context['form'].is_valid()) # mocking the session input response.context['form'].save(email=self.kwargs['email']) self.assertTrue(account.check_password(self.valid_data['password1'])) # working so far, but it seems there is no redirect url in response self.assertRedirects(response, reverse('next_url')) In views.py if request.method == 'POST': form = RegistraionForm(request.POST) if form.is_valid(): email = request.session.get('email') try: account = form.save(email=email) return HttpResponseRedirect('next_url')) In forms.py def save(self, **kwargs): user = super(RegistrationForm, self).save(commit=False) user.email = kwargs.pop('email') user.save() return user It seems there is no url in the response in tests.py. What went wrong here? -
Getting localtime with values_list in django
I have set settings.TIME_ZONE = Europe/Paris. In django I get dates like this:dates = (...).values_list('started_at', flat=True) But the resulting dates are in UTC. datetime.datetime(2018, 11, 28, 2, 23, 54, 361753, tzinfo=<UTC>) How do I get the dates in my local time without converting all those dates like following?: from django.utils.timezone import localtime dates = [localtime(d) for d in dates] -
hello I'm trying to do user control with django 2.1
hello I'm trying to do user control with django 2.1 but I've dealt with the following code but it throws me errors my code for views.py: > def login(request): context = RequestContext(request) > if request.method == 'POST': > username = request.POST.get['username'] > password = request.POST.get['password'] > user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request,user) return HttpResponseRedirect('/loggedin/') else: return HttpResponse("Inactive user.") else: return HttpResponseRedirect('login.html') return render_to_response('login.html') and I get the following error: File "C:\Users\asd\Desktop\Proyecto\MisPerris\urls.py", line 20, in <module> from Adoptar import views File "C:\Users\asd\Desktop\Proyecto\Adoptar\views.py", line 29 if request.method == 'POST': ^ IndentationError: unexpected indent -
User registration will not save
I want to save the user registration in Django but it always return "Existing". How am I going to solve this? My code is as follows class RegisterView(View): template = "#" context_data = ModelUser.objects.all() def get(self, *args, **kwargs): return render(self.request, self.template, {'context_data' : self.context_data}) def post(self, *args, **kwargs): user = ModelUser() if self.request.method == 'POST': if self.request.POST.get('fname') and self.request.POST.get('lname') and self.request.POST.get('email') and self.request.POST.get('username') and self.request.POST.get('password'): user.fname = self.request.POST.get('fname') user.lname = self.request.POST.get('lname') user.email = self.request.POST.get('email') user.username = self.request.POST.get('username') user.password = self.request.POST.get('password') for account in self.context_data: if self.request.POST.get('email') == user.email or self.request.POST.get('username') == user.username: return HttpResponse('Existing') if user.password != self.request.POST.get('repassword'): return HttpResponse('password not match!') else: user.save() return HttpResponse('Successfully created!') else: return HttpResponse('Invalid') -
Python args: django debugging arg set up for django manage.py
I want to enable debugging using visual studio debugging tool, ptvsd. Using that I have to attach the debugger to the application using ptvsd.enable_attach(address=(settings.REMOTE_URL, settings.DEBUG_PORT), redirect_output=True) ptvsd.wait_for_attach() Using ptvsd means I can't use threading and reloading, so I append the args sys.argv.append("--nothreading") sys.argv.append("--noreload") For convenience to enable debugging I created an args to execute those line of codes. I created named argument debug if __name__ == "__main__": #previous line omitted parser = argparse.ArgumentParser() parser.add_argument("--debug", help="enable debugging through vscode") args = parser.parse_args() if args.debug: sys.argv.append("--nothreading") sys.argv.append("--noreload") ptvsd.enable_attach(address=(settings.REMOTE_URL, settings.DEBUG_PORT), redirect_output=True) ptvsd.wait_for_attach() execute_from_command_line(sys.argv) but it returns an error when I tried to run using python manage.py runserver 0:8000 it says unrecognized arguments for runserver and 0:8000 by that, do I have to include all possible django positional argument to the parser ? and how to do that with the 0:8000? add all possible port? Is using named argument not viable for this case? -
module 'django.db.models' has no attribute 'TextArea'
this is the model i have im tring to make notes a textarea and when i try to makemigrations i get the module 'django.db.models' has no attribute 'TextArea' class Note(models.Model): timestamp = models.DateTimeField() notes = models.TextArea() Not sure if i should use django.forms model on this if so should i have two models one for Note and another NoteForms to handle the textarea feild. -
ModuleNotFoundError: No module named 'django.contrib.custom_post'
Using django and Pycharm. I am getting the above error when I try to run the server. I have searched everywhere in my code and I dont see the module named custom_post anywhere. At one point I created an app named messages. I then noticed that this already exists in django, so I renamed it (using Pycharm) custom_post. At which point i started getting WSGI errors, so I reverted back to a previous commit that had the app named messages (vs. custom_post), and deleted the messages app. Now here I am. I am not even sure which files to show you guys. I think when I refactored from "messages" to "custom_post" is changed something and I cant figure out what. Any guidance is great.