I'm following this tutorial about ajax and crud. The tutorial uses function-based-views approach, instead, I want to use class-based-views, particularly for this view.
def book_create(request):
data = dict()
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
else:
form = BookForm()
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)
This is the example of the class based view based on your case.
from django.views import View
class BookCreateView(View):
def post(self, request):
form = BookForm(request.POST)
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)
def get(self, request):
data = dict()
form = BookForm()
context = {'form': form}
data['html_form'] = render_to_string('books/includes/partial_book_create.html',
context,
request=request
)
return JsonResponse(data)
Related
Dynamics 365 v8.2.2.
Why attributesMetadata is null? How can I get the entity attributes metadata list?
{
var req = new RetrieveEntityRequest {
LogicalName = "opportunity",
RetrieveAsIfPublished = true,
};
var resp = srv.Execute(req) as RetrieveEntityResponse;
var entityMetadata = resp.EntityMetadata;
var attributesMetadata = entityMetadata.Attributes; // null
}
You need to set EntityFilters in request like:
EntityFilters = EntityFilters.All
Or
EntityFilters = EntityFilters.Attributes
The complete snippet as follows:
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Attributes,
LogicalName = "opportunity"
};
RetrieveEntityResponse retrieveOpptyEntityResponse(RetrieveEntityResponse)service.Execute(retrieveEntityRequest);
EntityMetadata opptyEntity = retrieveOpptyEntityResponse.EntityMetadata;
By default, EntityFilters.Default only entity information will be retrieved, that’s why you have empty attribute list.
Read more
I have two tables with similar data for body insurance and third party car insurance ... I have used enum in the model to separate the insurances and I want to do the creation operation for it .... There are two modes for each insurance. One case when that car does not have insurance yet and the second case when we want to extend it.
I wrote this code to create the form, but it encounters the following error
I also get an error on the name of the Create function.error = not all code paths return a value.
Please advise
public async Task<IActionResult> Create(int id, int type)
{
InsuranceViewModel model;
ViewBag.Type = type;
var companies = await _context.InsuranceCompany
.Where(e => e.IsActice)
.ToListAsync();
ViewData["CompanyList"] = new SelectList(companies, "Id", "CompanyName");
if ((InsuranceType)type == InsuranceType.Body)
{
var bodyInsurance = await _context.BodyInsurance
.Include(e => e.InsuranceCompany)
.FirstOrDefaultAsync(e => e.Id == id);
if (bodyInsurance == null)
{
model = new InsuranceViewModel
{
CompanyId = bodyInsurance.InsuranceCompanyId,
CompanyName = bodyInsurance.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(bodyInsurance.IssueDate).Ticks,
ExpireDate = new DateTime(bodyInsurance.ExpireDate).Ticks,
VehicleInformationId = id
};
}
else
{
var lastBody = await _context.BodyInsurance.Include(e => e.InsuranceCompany)
.Where(e => e.VehicleInformationId == id)
.OrderBy(e => e.ExpireDate)
.LastAsync();
model = new InsuranceViewModel
{
ExpireDate = new DateTime(lastBody.ExpireDate).AddYears(1).AddDays(1).Ticks,
CompanyId = lastBody.InsuranceCompanyId,
CompanyName = lastBody.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(lastBody.ExpireDate).AddDays(1).Ticks,
VehicleInformationId = id
};
}
}
else
{
if ((InsuranceType)type == InsuranceType.Thirdpart)
{
var thirdParty = await _context.ThirdPartyInsurance
.Include(e => e.InsuranceCompany)
.FirstOrDefaultAsync(e => e.Id == id);
if (thirdParty == null)
{
model = new InsuranceViewModel
{
CompanyId = thirdParty.InsuranceCompanyId,
CompanyName = thirdParty.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(thirdParty.IssueDate).Ticks,
ExpireDate = new DateTime(thirdParty.ExpireDate).Ticks,
VehicleInformationId = id
};
}
else
{
var lastThirdParty = await _context.ThirdPartyInsurance.Include(e => e.InsuranceCompany)
.Where(e => e.VehicleInformationId == id)
.OrderBy(e => e.ExpireDate)
.LastAsync();
model = new InsuranceViewModel
{
ExpireDate = new DateTime(lastThirdParty.ExpireDate).AddYears(1).AddDays(1).Ticks,
CompanyId = lastThirdParty.InsuranceCompanyId,
CompanyName = lastThirdParty.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(lastThirdParty.ExpireDate).AddDays(1).Ticks,
VehicleInformationId = id
};
}
}
return View(model);
}
I have a class for a cart in a store and when the buy method gets run it skips the breakpoint and still hits the RedirectToAction at the bottom of the method. This is the code for the method
public ActionResult Buy(int productid /*string optionid*/)
{
Product productModel = new Product();
List<ProductOptionJoin> productOptionJoins = GetProductOptions();
var test = productOptionJoins.Where(x => x.ProductID == productid && x.OptionID.ToString() == "1" /*optionid*/).Select(x => new CartItem() { getProduct = x.GetProduct, getOption = x.GetOption });
var i = test;
if (Session["cart"] == null)
{
List<CartItem> cart = new List<CartItem>();
//cart.Add(new CartItem { getProduct = productModel.find(id), getOption = productModel.find(id), Quantity = 1 });
Session["cart"] = cart;
}
else
{
List<CartItem> cart = (List<CartItem>)Session["cart"];
int index = isExist(productid);
if (index != -1)
{
cart[index].Quantity++;
}
else
{
//cart.Add(new CartItem { getProduct = productModel.find(id), getOption = productModel.find(id), Quantity = productModel.find(id) });
}
Session["cart"] = cart;
}
return RedirectToAction("Index");
}
Any ideas?
You are only creating the session variable at the end, maybe put it above?
Product productModel = new Product();
List<ProductOptionJoin> productOptionJoins = GetProductOptions();
var test = productOptionJoins.Where(x => x.ProductID == productid && x.OptionID.ToString() == "1" /*optionid*/).Select(x => new CartItem() { getProduct = x.GetProduct, getOption = x.GetOption });
var i = test;
Session["cart"] = xyz;
model
class CustomerInfo(models.Model):
customer_name = models.CharField(max_length=50)
customer_letter= models.FileField(upload_to='/media/',null= True, blank=model
class CustomerInfo(models.Model):
customer_name = models.CharField(max_length=50)
customer_letter= models.FileField(upload_to='/media/',null=True,blank= True)
representative_name = models.CharField(max_length=50)
representative_letter = models.FileField(upload_to='/media/', null=True, blank=True)
ministry_approval = models.FileField(upload_to='/media/', null=True, blank=True)
date = models.DateField()
def __str__(self):
return self.customer_name + ' - ' + self.customer_letter + ' - ' + self.represntative_name + ' - ' + self.representative_letter + ' - ' + self.ministry_approval + ' - ' + self.date
def custmoer(request):
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/login/custmoer/')
else:
return HttpResponseRedirect('/login')
else:
form= CustomerForm()
return render(request, "custmoer.html", {'form':form})
form.py
class CustomerForm(forms.ModelForm):
class Meta:
model = CustomerInfo
fields = ('customer_name', 'customer_letter', 'representative_name', 'representative_letter', 'ministry_approval', 'date')
I tried to mke a request with GET and parameters. However, I got an exception for the WinPhone8.1 which meaned that GET was a violation protocol due to a content added in. So making a POST request is the solution.
Despite my searches, I'm still not able to set the content lenght property of my HttpWebRequest.. Why?
private static async void AsyncRequest(string url, string contentType, string methodType, int contentLenght, Action<Object, string> callback, Action<HttpStatusCode, JObject, Action<Object, string>> parserFunction)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = methodType;
request.Proxy = null;
if (methodType == Method.POST)
{
request.ContentLenght = "contentLenght";
request.Headers["content-length"] = "contentLenght";
request.Headers["Content-Length"] = "contentLenght";
request.Headers[HttpRequestHeader.ContentLength] = "contentLenght";
request.Headers["HttpRequestHeader.ContentLength"] = "contentLenght";
request.Content.Headers.ContentLength = "contentLenght";
...........
Nothing works ><
}
Debug.WriteLine("1");
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
Debug.WriteLine("2");
await task.ContinueWith(t => ReadStreamFromResponse(t.Result, callback, parserFunction));
}
Thank to jsonmcgraw for its answer on Xamarin Forums
If you want to make a POST request intead of GET request, then there is the two methods which can make you able to make GET/POST requests.
So, first, an async GET request.
public static async Task<string> MakeGetRequest(string url, string cookie)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.ContentType = "text/html";
request.Method = "GET";
request.Headers ["Cookie"] = cookie;
var response = await request.GetResponseAsync ();
var respStream = response.GetResponseStream();
respStream.Flush ();
using (StreamReader sr = new StreamReader (respStream)) {
//Need to return this response
string strContent = sr.ReadToEnd ();
respStream = null;
return strContent;
}
}
Sample usage:
public static async Task<MyModel[]> GetInfoAsync(int page, string searchString, string cookie)
{
string url = Constants.url + Constants.Path+
"page=" + page +
"&searchString=" + searchString;
string result = await WebControl.MakeGetRequest (url, cookie);
MyModel[] models = Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel[]> (result);
return models;
}
Next, an async POST request
public static async Task<string> MakePostRequest (string url, string data, string cookie, bool isJson = true)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
if (isJson)
request.ContentType = "application/json";
else
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Headers ["Cookie"] = cookie;
var stream = await request.GetRequestStreamAsync ();
using (var writer = new StreamWriter (stream)) {
writer.Write (data);
writer.Flush ();
writer.Dispose ();
}
var response = await request.GetResponseAsync ();
var respStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader (respStream)) {
//Need to return this response
return sr.ReadToEnd();
}
}
Sample usage:
public static async Task<ResultModel> PostInfoAsync(int id, string cookie)
{
string data = "id=" + id;
//third param means that the content type is not json
string resp = await WebControl.MakePostRequest (Constants.url + Constants.Path, data, cookie, false);
ResultModel model;
try {
model = JsonConvert.DeserializeObject<ResultModel> (resp);
}
catch (Exception) {
model = new ResultModel{ isSuccess = false, Message = resp };
}
return model;
}