How to build the JSON API for add the post. I am creating the Rails application and connect it with iphone application by using the JSON API. User can add the Blog/Post from application so how I can add the blog data like title, text and image in rails database(using the new method).
You can have your controllers return JSON by doing something like:
class ProjectsController < ApplicationController
def index
respond_to do |format|
format.json { render json: Project.all }
end
end
def show
respond_to do |format|
format.json { render json: Project.where(name: params[:name])}
end
end
end
This is essentially turning rails into a JSON API. Make sure to add your model attributes to the Active::Model::serializers
class ProjectSerializer < ApplicationSerializer
attributes :id, :name, :description, :imgUrl, :deployUrl
end
class ApiController < ApplicationController
respond_to :json
def patient
#patients = Patient.all
respond_with(#patients)
end
def disease
#diseasecode = Diseasecode.all
respond_with(#diseasecode)
end
def addpatient
#patient = Patient.new(params[:id])
flash[:notice] = 'Patient was successfully created.' if #patient.save
respond_with(#patient)
end
def patient_params
params.require(:patient).permit(:name, :gender, :date_of_birth, :contact_no, :billing_id, :physician)
end
end
I am getting still problem def addpatient method is never add the post if I hit the url www.localhost:3000/api/addpatient.json?name=test&gender=male&date_of_birth=10/02/2010&contact_no=58475896&billing_id=25&physician=48
Related
I have a custom user model that have a preferred_language field. I want all the emails (activation and password reset) to be sent translated to the language that user specified in profile.
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
LANGUAGE_CHOICES = (
(1, "English"),
(2, "Русский")
)
preferred_language = models.PositiveSmallIntegerField(choices=LANGUAGE_CHOICES, default=2,
verbose_name=_("Preferred language"))
I thought about setting custom email class but didn't saw in navive djoser's classes any points where I could explicitly set the language of outcome emails despite of ready-to-be-translated style of email templates:
class ActivationEmail(BaseEmailMessage):
template_name = 'email/activation.html'
def get_context_data(self):
context = super(ActivationEmail, self).get_context_data()
user = context.get('user')
context['uid'] = utils.encode_uid(user.pk)
context['token'] = default_token_generator.make_token(user)
context['url'] = settings.ACTIVATION_URL.format(**context)
return context
Reset password view (which's refference is settings.EMAIL.activation used in ActivationEmail class above):
class ResetPassword(ActionViewMixin, generics.GenericAPIView):
...
def send_password_reset_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
settings.EMAIL.password_reset(self.request, context).send(to)
def send_activation_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
settings.EMAIL.activation(self.request, context).send(to)
In your case I would use the override context manager that stores the current language on enter (in order to sent the email) and restores it on exit.
from django.utils import translation
def send_password_reset_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
lang_code = user.lang_code # retrieve user's language code here
with translation.override(lang_code):
settings.EMAIL.password_reset(self.request, context).send(to)
def send_activation_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
lang_code = user.lang_code # retrieve user's language code here
with translation.override(lang_code):
settings.EMAIL.activation(self.request, context).send(to)
I am really new to django and stuck in using foreign key in django queries.Can anyone help me.
Situation:I created a sign up page with username and email field.So when a new user registered, its username and email address saved to auth_user table.
Q: I want to create a model instance in class UserDetails each time a new user register. or you can say entry of user as a foregien key in table userdetails. I am using postgresql database.
Myapp/models.py
class Pincode(models.Model):
pincode = models.CharField("PinCode",null=False)
geom = GeopositionField("Location")
objects = models.GeoManager()
def __unicode__(self):
return u'%s' %(self.pincode)
class UserDetails(models.Model):
user = models.OneToOneField(User, related_name='User_Details',unique=True)
pin= models.ForeignKey(Pincode,related_name='pin', null= True, blank=True)
rating= models.CharField(max_length=12, null=True, blank=True)
def __unicode__(self):
return u'%s, %s, %s' % (self.user, self.pin, self.rating)
views.py
def index(request):
update_user_details()
return render_to_response("larb/index.html",
RequestContext(request))
def update_user_details(request): ## **Stuck here**
user_details = UserDetails.objects.all()
new_entry= User.objects.exclude() # Don't know how to do
currently i am thinking of creating a function in the views that update the table.
first it checks for new entries means entries in auth_user which are not in userdetails table. If found update userdetails table.
I hope i solved it and it's seems fine now:
Here is views.py code
def index(request):
update_user_details()
return render_to_response("larb/index.html",
RequestContext(request))
def update_user_details():
id_past_entries = UserDetails.objects.all().values_list('user_id', flat = True)
new_entries = User.objects.exclude(id__in=id_past_entries)
if new_entries:
for new_id in new_entries:
new = User.objects.get(id=new_id)
UserDetails.objects.create(user=new)
UserDetails.save()
There is a real lack of documentation on how to work with WTForms' FieldList. So thanks to the internet I've been able to hack together the following:
Form:
class BranchForm(Form):
name = StringField('Name', validators = [Required()])
equipment = FieldList(SelectField('Equipment', validators=[Required()], coerce=int,
choices = [(x.id, x.name) for x in Equipment.query.all()]))
mod = FieldList(StringField('Method of Delivery', validators = [Optional()]))
View:
def edit_branch(id):
branch = Branch.query.filter_by(id=id).first()
#populate data_in to be used by BranchForm
data_in = []
for eq_obj in branch.equipment_assoc:
data_in.append(('equipment', eq_obj.equipment.id))
data_in.append(('mod', eq_obj.mod))
editform = BranchForm(data=MultiDict(data_in))
if editform.validate_on_submit():
branch.name = editform.name.data
db.session.add(branch)
db.session.commit()
return redirect('/admin/branches/' + str(branch.id))
editform.name.data = branch.name
return render_template("branch_edit.html",
title="Edit Branch",
branch = branch,
editform = editform)
What's throwing me off is that everywhere else that I've used a WTForm Form and populated the fields with data from my db (like for edit forms), I've had to populate these form fields after the form.validate_on_submit() block, because if not, then the form will never update as whatever is submitted is immediately overwritten.
See "editform.name.data = branch.name" (this is how I've always done it)
From every example I've found online about populating a FieldList, it apparently must be done during instantiation, but the form has to be instantiated before the validate_on_submit() as well because validate_on_submit() is a method of the form object.
See "editform = BranchForm(data=MultiDict(data_in))" (this is how I've seen FieldLists populated in all the examples I've seen.)
How can I go about populating my form with its field lists?
Alright, so a buddy helped me figure this one out. Here's what I ended up with:
Form:
class BranchForm(Form):
name = StringField('Name', validators = [Required()])
equipment = FieldList(SelectField('Equipment', validators=[Required()], coerce=int,
choices = [(x.id, x.name) for x in Equipment.query.all()]))
mod = FieldList(StringField('Method of Delivery', validators = [Optional()]))
def populate_assoc(self, branch_obj):
i = 0
branch_obj.name = self.name.data
for assoc_obj in branch_obj.equipment_assoc:
assoc_obj.equipment_id = self.equipment[i].data
assoc_obj.mod = self.mod[i].data
i += 1
View:
def edit_branch(id):
branch = Branch.query.filter_by(id=id).first()
if request.method == 'POST':
editform = BranchForm()
if editform.validate_on_submit():
editform.populate_assoc(branch)
db.session.add(branch)
db.session.commit()
return redirect('/admin/branches/' + str(branch.id))
#populate data_in to be used
data_in = []
for eq_obj in branch.equipment_assoc:
data_in.append(('equipment', eq_obj.equipment.id))
data_in.append(('mod', eq_obj.mod))
editform = BranchForm(data=MultiDict(data_in))
editform.name.data = branch.name
return render_template("branch_edit.html",
title="Edit Branch",
branch = branch,
editform = editform)
The trick was really to step away from using form.validate_on_submit() as my logic separator, since it relies on the form object. His idea was to use the if request.method == 'POST': for this purpose. This way I can instantiate my form in two different ways. One gets populated for display, the other is only instantiated if the request method is POST, thus retaining the information submitted in the form.
To finish the job I added the populate_assoc method to my form class so that I can easily place the information from the form into my association model.
WtForms has a populate_obj() method. Maybe that's what you're after?
def edit_branch(id):
branch = Branch.query.filter_by(id=id).first()
editform = BranchForm(obj=branch)
if editform.validate_on_submit():
editform.populate_obj(branch)
db.session.commit()
return redirect('/admin/branches/' + str(branch.id))
return render_template("branch_edit.html",
title="Edit Branch",
branch = branch,
editform = editform)
Please help me to add a multipart/form data parameter on api help page.
I'm using Microsoft.AspNet.WebApi.HelpPage.VB 5.2.2.
I want to add CustomerName, fdStreet1, fdStreet2 parameter information on to the api help page. How can I do this?
Here's what I have so far.
<HttpPost> _
<ResponseType(GetType(TestModel))> _
<Route("TestAdd")> _
Public Function TestAdd() As IHttpActionResult
Dim ServerUploadFolder = HttpContext.Current.Server.MapPath("~/Uploaded/")
If Not Request.Content.IsMimeMultipartContent Then
Throw New HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType))
End If
Dim streamProvider = New CustomMultipartFormDataStreamProvider(ServerUploadFolder)
Request.Content.ReadAsMultipartAsync(streamProvider)
'Read form data
Dim _testModel As New TestModel
_testModel.fdCustomerName = streamProvider.FormData("CustomerName")
_testModel.fdStreet1 = streamProvider.FormData("fdStreet1")
_testModel.fdStreet2 = streamProvider.FormData("fdStreet2")
Return Json(_testModel)
I have a restservice running by exposing a simple domain class. I can acces by
http://localhost:8080/Bic/bic/17.json
and I get:
{"class":"org.strotmann.bic.BankIdentCode","id":17,"bankname":"ABK-Kreditbank","bic":"ABKBDEB1XXX","blz":10030400,"ort":"Berlin","plz":10115}
I want to acces by something like blz=10030400 or any other item of the domain class except the id.
How to ?
peter
Dortmund, Germany
the controller action code (you should have posted here!) can look like:
def bic(){
def entry = params.find{ k, v -> Bic.metaClass.hasMetaProperty k }
if( entry )
render( Bic.withCriteria( uniqueResult:true ){ eq entry.key, entry.value } as JSON )
else
render text:'not found!`
}