Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
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>