Blender - Inserting a line of text using bpy - user-interface

I'm designing a simple GUI for a Blender 2.80 plug-in. I've created a dialog box to enter some data:
class ExportFDSCloudHPC(Operator):
bl_idname = "..."
bl_label = "Dialog Box"
bl_description = "..."
data1 = bpy.props.StringProperty(
name = "Data 1",
default = "..."
)
data2 = bpy.props.StringProperty(
name = "Data 2",
default = "..."
)
data3 = bpy.props.StringProperty(
name = "Data 3",
default = "..."
)
def draw(self, context):
col = self.layout.column(align = True)
col.prop(self, "data1")
col = self.layout.column(align = True)
col.prop(self, "data2")
col = self.layout.column(align = True)
col.prop(self, "data3")
def execute(self, context):
...
I would like to add a line of text above Data 1 with a message that has the same length as the dialog box. It's possible?

Add label() in draw() as you adding column:
def draw(self, context):
self.layout.label(text="text")
col = self.layout.column(align = True)
Here is label documentation

Related

Blender - Inserting a text button using bpy

I'm designing a simple GUI for a Blender 2.80 plug-in. I've created a dialog box to enter some data:
I would like to replace the line of text ("Lorem ipsum ...") with a button with a custom label (example "click here to visit our website").
Below is the code I am using:
class ExportFDSCloudHPC(Operator):
bl_idname = "..."
bl_label = "Title"
bl_description = "..."
data1 = bpy.props.StringProperty(
name = "Text 1",
default = "..."
)
data2 = bpy.props.StringProperty(
name = "Text 2",
default = "..."
)
data3 = bpy.props.StringProperty(
name = "Text 3",
default = "..."
)
def draw(self, context):
col = self.layout.column(align = True)
col.prop(self, "data1")
self.layout.label(text="Lorem ipsum dolor sit amet, consectetur adipisci elit...")
col = self.layout.column(align = True)
col.prop(self, "data2")
col = self.layout.column(align = True)
col.prop(self, "data3")
def execute(self, context):
...
To get button you need to provide an existing operator: row.operator("wm.save_as_mainfile") button text is defined in operator. If you want to change name of existing operator use row.operator("wm.save_as_mainfile", text='My Save Label')
You can create own operator:
import bpy
def main(context):
for ob in context.scene.objects:
print(ob)
class SimpleOperator(bpy.types.Operator):
"""Tooltip"""
bl_idname = "object.simple_operator" # <- put this string in layout.operator()
bl_label = "Simple Object Operator" # <- button name
#classmethod
def poll(cls, context):
return context.active_object is not None
def execute(self, context):
main(context)
return {'FINISHED'}
def register():
bpy.utils.register_class(SimpleOperator)
def unregister():
bpy.utils.unregister_class(SimpleOperator)
if __name__ == "__main__":
register()
# test call
bpy.ops.object.simple_operator()
and then use it like that:
[..]
col.prop(self, "data1")
col.operator("object.simple_operator")
# self.layout.label(text="Lorem ipsum dolor sit amet, consectetur adipisci elit...")
col = self.layout.column(align = True)
[..]

How to make a PUT/PATCH request with ListField field in Django-REST?

I am trying to build a rest-api for a movie-review website. The movie model contains a cast-field which is a list-field, when using ModelViewSets one can't POST ListFields through HTML, so I set blank = true for all list-fields thinking that I'll make a raw PATCH request to update the blank fields, but I am unable to do so.
models.py
class Movie(models.Model):
movie_name = models.CharField(max_length = 100, unique = True)
release_date = models.DateField(blank = True)
description = models.TextField(max_length = 500)
movie_poster = models.ImageField(blank = True)
directors = ListCharField(
base_field = models.CharField(max_length = 500),
max_length = 6 * 500,
blank = True
)
trailer_url = models.URLField()
cast = ListCharField(
base_field = models.CharField(max_length = 225),
max_length = 11 * 225,
blank = True
)
genre = ListCharField(
base_field = models.CharField(max_length = 225),
max_length = 11 * 255,
blank = True
)
avg_rating = models.FloatField(validators = [MinValueValidator(0), MaxValueValidator(5)])
country = models.CharField(max_length = 100)
language = models.CharField(max_length = 100)
budget = models.BigIntegerField(blank = True)
revenue = models.BigIntegerField(blank = True)
runtime = models.DurationField(blank = True)
Serializer
class MovieSerializer(ModelSerializer):
cast = ListField(
child = CharField(required = False), required = False,
min_length = 0
)
genre = ListField(
child = CharField(required = False), required = False,
min_length = 0
)
directors = ListField(
child = CharField(required = False), required = False,
min_length = 0
)
class Meta:
model = Movie
fields = '__all__'
I used djano-mysql for adding the ListCharField field-type.
https://i.stack.imgur.com/sC6Vw.png [The data without list field values]
https://i.stack.imgur.com/W3xea.png [request I tried to make]
https://i.stack.imgur.com/OPeJn.png [response that I received]
Original put request which resulted in an error response
https://i.stack.imgur.com/W3xea.png
The request had some trailing commas, due to which the API expected more values.
Here's the correct request-content -
{
"cast": [
"aamir",
"sakshi"
],
"genre": [
"biopic"
],
"directors": [
"nitesh tiwari"
]
}

django rest framework:In Serializer how to show the field properties also

I have model:
class Ingredient(models.Model):
KILOGRAM = 'kg'
LITER = 'ltr'
PIECES = 'pcs'
MUNITS_CHOICES = (
(KILOGRAM, 'Kilogram'),
(LITER, 'Liter'),
(PIECES, 'Pieces'),
)
name = models.CharField(max_length=200,unique=True,null=False)
slug = models.SlugField(unique=True)
munit = models.CharField(max_length=10,choices=MUNITS_CHOICES,default=KILOGRAM)
rate = models.DecimalField(max_digits=19, decimal_places=2,validators=[MinValueValidator(0)],default=0)
typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT)
density_kg_per_lt = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (kg/lt)',null=True,blank=True,validators=[MinValueValidator(0)])
density_pcs_per_kg = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (pcs/kg)',null=True,blank=True,validators=[MinValueValidator(0)])
density_pcs_per_lt = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (pcs/lt)',null=True,blank=True,validators=[MinValueValidator(0)])
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
When i get the api i also want to get field types like char, decimal, datetime etc
Something like the below api result, is it possible. Because i am using reactJs as frontend, i have tell the input what kind of field it can accept and also helps in sorting by text or number
{
"id": {value: 1,type: number},
"name": {value: "adark",type: charfield},
"rate": {value: "12.00",type: decimal},
"updated": {value: "2017-07-14T10:51:47.847171Z",type: datetime},
.......so on
}
The Corresponding Serializer would be as follows:
class IngredientSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField()
rate = serializers.SerializerMethodField()
updated = serializers.SerializerMethodField()
class Meta:
model = Ingredient
fields = ('name', 'rate', 'updated')
def get_name(self, obj):
response = dict()
response['value'] = obj.name
response['type'] = obj.name.get_internal_type()
return Response(response)
def get_rate(self, obj):
response = dict()
response['value'] = obj.rate
response['type'] = obj.rate.get_internal_type()
return Response(response)
def get_updated(self, obj):
response = dict()
response['value'] = obj.updated
response['type'] = obj.updated.get_internal_type()
return Response(response)

Convert a text to JSON

I have a text file say data.txt which contains content of format:
( {
city = Leesburg;
country = USA;
dob = "";
email = "email#domain.com";
firstName = "EricM.";
homePhone = "";
lastName = Abcdef;
mobilePhone = 12312312;
state = Virginia;
workPhone = 12312312;
},
{
city = "Mt. Uncle";
dob = "";
email = "";
firstName = first;
homePhone = "";
lastName = Berry;
mobilePhone = 234234;
state = MD;
workPhone = "";
}
)
require "json"
file = File.open("data.txt")
contents = file.read
hashes = contents.scan(/{(.*?)}/mx)
arr = []
hashes.each do |hash|
hashitems = hash[0].scan(/(\w+\s=\s.+?);/)
ahash = {}
hashitems.each do |hashitem|
itemarr = hashitem[0].split(" = ")
ahash[itemarr[0]] = itemarr[1]
end
arr << ahash
end
print JSON.dump(arr)
What I've done here is use two regex functions to break down your data into a Ruby object, then I've used the JSON library to dump the object to JSON.

Creating object in django model form with foreign key

I am inserting a new record in my model form where my model is child form containing a foriegn key. When I am submitting the form it give error it should be instance of the foriegn key.
Here is my model
class MMEditidState(models.Model):
state_id = models.IntegerField(primary_key = True)
state_dremelid = models.ForeignKey(MMDremelDump, db_column = 'state_dremelid')
assignee = models.CharField(max_length = 50)
state = models.CharField(max_length = 50)
role = models.CharField(max_length = 50)
date = models.DateTimeField()
class Meta:
db_table = u'mm_editid_state'
def __unicode__(self):
return u'%s %s' % (self.state_dremelid, self.assignee)
class MMEditidErrors(models.Model):
error_id = models.IntegerField(primary_key = True)
error_stateid = models.ForeignKey(MMEditidState, db_column = 'error_stateid')
feature_type = models.CharField(max_length = 20)
error_type = models.CharField(max_length = 20)
error_nature = models.CharField(max_length = 50, null = True)
error_details = models.CharField(max_length = 50)
error_subtype = models.CharField(max_length = 200)
date = models.DateTimeField()
class Meta:
db_table = u'mm_editid_errors'
def __str__(self):
return "%s" % (self.error_dremelid)
def __unicode__(self):
return u'%s' % (self.error_dremelid)
Here is my View
def qcthisedit(request, get_id):
if request.method == "POST":
form = forms.MMEditidErrorForm(get_id, request.POST)
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/mmqc/dremel_list/')
else:
form = forms.MMEditidErrorForm(get_id)
return shortcuts.render_to_response('qcthisedit.html',locals(),
context_instance = context.RequestContext(request))
Here is my form
class MMEditidErrorForm(forms.ModelForm):
def __init__(self,get_id, *args, **kwargs):
super(MMEditidErrorForm, self).__init__(*args, **kwargs)
dremel = MMEditidState.objects.filter(pk=get_id).values('state_id')
dremelid = int(dremel[0]['state_id'])
self.fields['error_stateid'] = forms.IntegerField(initial = dremelid,
widget = forms.TextInput(
attrs{'readonly':'readonly'}))
feature_type = forms.TypedChoiceField(choices = formfields.FeatureType)
error_type = forms.TypedChoiceField(choices = formfields.ErrorType)
error_nature = forms.TypedChoiceField(choices = formfields.ErrorNature)
error_details = forms.TypedChoiceField(choices = formfields.ErrorDetails)
error_subtype = forms.TypedChoiceField(choices = formfields.ErrorSubType)
class Meta:
model = models.MMEditidErrors
exclude = ('error_id','date')
When I submit the form I am getting the error
Cannot assign "1": "MMEditidErrors.error_stateid" must be a "MMEditidState" instance.
So I have added line
get_id = MMEditidState.objects.get(pk = get_id)
Now I am getting the below mentioned error
int() argument must be a string or a number, not 'MMEditidState'
in form = forms.MMEditidErrorForm(get_id, request.POST)
Can someone help on this
Thanks
Vikram
I have solved this problem by simply using the custom forms instead of model forms. While storing the data in the database, I managed myself in the views.py

Resources