def insertCompany_type(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
c_type = data["subject"]
user = get_user_id(request)
print user
c_ty=Company_Type(user_id=user,type=c_type)
c_ty.save(force_insert=True)
except:
print 'nope'
return JsonResponse({'status': 'success'})
print user
displays [{'user_id': 1L}]
.. How can i assign 1 to user_id in Company_Type(user_id=user,type=c_type)for creating objects
If user is a list of length 1, containing a dict, you can extract the value of a dict as follows:
value = user[0]['user_id']
You could modify your code as:
if request.method == 'POST':
try:
data = json.loads(request.body)
c_type = data["subject"]
user = get_user_id(request)
id = user[0]['user_id']
c_ty=Company_Type(user_id=id,type=c_type)
c_ty.save(force_insert=True)
except:
print 'nope'
return JsonResponse({'status': 'success'})
Also if you need to make sure the id is an integer cast it to the right data type as int(id)
When you actually make a user (which doesnt happen your snippet of code) you can pass a constuctor argument setting user_id. e.g.
myUser = User(name="shalin", user_id=1)
myUser.save()
Also, you can get user objects from requests simply by doing this:
user = request.user
which is a bit easier than what you're doing I think.
Related
I just wanna get profile with full form or empty form.
def local_cabinet(request):
user_id = request.user.id
caruser = Checkout.objects.filter(user=request.user)
# form = CheckoutForms()
orders = request.user.orderitem_set.all()
total_orders = orders.count()
ready_order = request.user.order_set.all()
customer = Customer.objects.filter(user=request.user)
customer_form = CustomerForm()
Maybe here's problem I don't know:
if request.method == 'POST':
if customer.exists():
form = CustomerForm(request.POST, request.FILES, instance=customer)
else:
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
context = {
'caruser': caruser,
'orders': orders,
'total_orders': total_orders,
'ready_order': ready_order,
'cat_selected': 0,
'customer_form': customer_form,
'customer': customer,
}
return render(request, 'localcabinet.html', context=context)
I don't know why I get this, maybe because I'm not right at saving the form.
You are missing User instance in form, that you probably need to pass it after form creation and before saving it.
You didn't provide model nor forms, but I guess it will look like this:
if request.method == 'POST':
...
else:
form = CustomerForm(request.POST)
form.user = request.user
if form.is_valid():
form.save()
...
Another thing is that you assign queryset instead of single object with filter method:
customer = Customer.objects.filter(user=request.user) # gives queryset with probably one object
customer = Customer.objects.get(user=request.user) # gives an object - but gives Error if there is None or more than one
Probably the best approach to get single object is with try and except:
try:
customer = Customer.objects.get(user=request.user)
except Customer.DoesNotExists:
customer = None
then later instead of if customer.exists() you can use simple if customer.
I create a database for my functioning website since last year, I forgot to set the input for my model as unique. it allows multiple entry for the same record is there anyway i can change this in my route? I use python flask and mysqlite as the database
#app.route("/", methods=['POST', 'GET'])
def create_numbers():
if request.method =="GET":
return render_template('index.html')
else:
title = request.form["name"]
phone = request.form["phone"]
validated = False
if title == '' or phone == '':
flash("All fields are required")
else:
validated = True
if not validated:
return render_template("index.html")
watch = Watch(name=title ,phone=phone)
db.session.add(watch)
db.session.commit()
return redirect(url_for("userindexes"))
You have two options. You can first edit the Watch database model and make certain columns unique in the database layer. This will prevent entries being added that violate this rule.
If you need to have multiple unique columns, use the UniqueConstraint feature of SQLAlchemy.
class Watch(Model):
#... other elements
name = Column(db.String(80), unique=True, nullable=False)
The downside to this approach is that attempts to add duplicate entries will raise an Exception that you will now have to catch and handle otherwise you will send a 500 HTTP response back to the user if they enter duplicate input.
The other approach is to simply do a query in your flask route that checks for duplicates before adding the new database entry.
#app.route("/", methods=['POST', 'GET'])
def create_numbers():
if request.method =="GET":
return render_template('index.html')
else:
title = request.form["name"]
phone = request.form["phone"]
duplicate = Watch.query.filter(
(Watch.name == title) &
(Watch.phone == phone)
).first()
if duplicate:
return 'That entry is already in the database.'
validated = False
if title == '' or phone == '':
flash("All fields are required")
else:
validated = True
if not validated:
return render_template("index.html")
watch = Watch(name=title ,phone=phone)
db.session.add(watch)
db.session.commit()
return redirect(url_for("userindexes"))
I am trying to show orders by customer id by i am getting this error :
TypeError at /orders
Field 'id' expected a number but got {'id': 3, 'phone_number': '01622153196', 'email': 'sakibovi#gmail.com', 'password': 'pbkdf2_sha256$216000$H2o5Do81kxI0$2tmMwSnSJHBVBTU9tQ8/tkN7h1ZQpRKrTAKkax1xp2Y=', 'coin': 1200.0}.
Actually i want to fetc only customer id but getting whole dictionary.
Here in Login Class in views.py i fetch whole customers info like this
request.session['customer'] = customer.__dict__
Here is the details :
class Login(View):
def get(self, request):
return render(request, 'signupsignin/signin.html')
def post(self, request):
phone_number = request.POST.get('phone_number')
password = request.POST.get('password')
customer = Customer.get_customer(phone_number)
error_message = None
if customer:
match = check_password(password, customer.password)
if match:
customer.__dict__.pop('_state')
request.session['customer'] = customer.__dict__
# request.session['customer'] = customer.id
#request.session['customer'] = customer.coin
#request.session['phone_number'] = customer.phone_number
return redirect('Home')
else:
error_message = 'Phone number or Password didnt match on our record'
else:
error_message = 'No Customer Found! Please Registrer First!'
print(phone_number, password)
context = {'error_message':error_message}
return render(request, 'signupsignin/signin.html', context)
I think for that reason i am getting the whole informaton of a customer
Here is my Views.py for userorders by customer id ::
class UserOrders(View):
def get(self, request):
customer = request.session.get('customer')
user_orders = Order.get_orders_by_customer(customer)
print(user_orders)
args = {'user_orders':user_orders}
return render(self.request, 'Home/all_orders.html', args)
Here i have a method named get_orders_by_customer() i made this in models.py
Here it is ::
#staticmethod
def get_orders_by_customer(customer__id):
return Order.objects.filter(customer=customer__id)
So what i am trying to do is customers can see their own orders.I have a panel called "all orders" here a customer can see their own order only.
Please Help me i got really confused here
As per my understanding, you have to pass a number, but you're passing a whole dictionary.
#staticmethod
def get_orders_by_customer(customer__id):
return Order.objects.filter(customer=customer__id)
here before return try to debug with a print or something. and you'll see what I mean.
try this and it should work, if im not wrong:
costomer__id['id'] instead of costomer__id
or change your code into this:
#staticmethod
def get_orders_by_customer(customer):
return Order.objects.filter(customer=customer['id'])
You can try using values() query to achieve your purpose.
Here is the link to the documentation - https://docs.djangoproject.com/en/3.1/ref/models/querysets/#values
I have the following view:
def process(request):
if request.method == 'POST':
data = request.POST
results = Specs.objects.filter(screenGroup = data['screen_user'], storage = data['storage_user'], mSystem = data['system_user'] )
context = {'results' : results}
return render(request, 'process.html', context)
When the user inputs the three values it filters correctly, but when it just inputs one or two (or nothing), then it filters passing the value None. Is there any way to ignore the filter if it's not set?
Thanks!
EDIT:
The following code is working, but it's obviously a very unefficient way:
def process(request):
if request.method == 'POST':
data = request.POST
if(data['screen_user'] != None):
results = Specs.objects.filter(screenGroup = data['screen_user'])
elif (data['storage_user'] != None):
results = Specs.objects.filter(storage = data['storage_user'])
else:
results = Specs.objects.all()
#plus all the other options...
context = {'results' : results}
return render(request, 'process.html', context)
You can build the filter beforehand:
def process(request):
if request.method == 'POST':
data = request.POST
spec_filter = {}
for attribute in ['screenGroup', 'storage', 'mSystem']:
if attribute in data and data[attribute]:
spec_filter[attribute] = data[attribute]
results = Specs.objects.filter(**spec_filter)
context = {'results' : results}
return render(request, 'process.html', context)
NB: To use this verbatim you would have to change the names of the variables being passed in the request.POST to match those in the Specs model. I did this just to illustrate, but you can easily use the same principle with your variable names. In that case you'll have to be a bit more verbose.
It's called validating your form.. There are two ways of doing this:
create a django form and use myform.is_valid(). You can read about it in the docs
validate it yourself with a few 'if' statements (either on server side or with javascript before sending the ajax call)
class Member(models.Model):# member db table
userID = models.CharField(max_length=80,primary_key=True) #user id
password = models.CharField(max_length=32)# password
nickname = models.CharField(max_length=100)# user nickname
penalty = models.PositiveSmallIntegerField(max_length=10,default=0,null=True)
participation=models.ForeignKey('Room',default=None,blank=True,null=True)
def __unicode__(self):
return self.userID
def doJoin(request):
if request.is_ajax() and request.method == 'POST':
# check validation
userID = request.POST['userID']
userNickname = request.POST['nickname']
if (checkID(userID) == False) and (checkNickname(userNickname) == False) :
#save to the database
newUser = Member()
newUser.userID = userID
newUser.nickname = userNickname
newUser.password = request.POST['password']
print newUser.userID , newUser.nickname , newUser.password , newUser.penalty , newUser.participation
newUser.save() #<------------error line!!!!
return HttpResponse('true')
else:
return HttpResponse('false')
else:
HttpResponse('false')
line about 8
In function doJoin:
newUser.save() # <--- error... so sad...
What should I do? Help me please.
What's wrong in this source?
Do you have debugging turned off? If you're getting a 500 and you have debugging turned on, you'll get a stack trace with the exception.
What are checkID() and checkNickname() doing? If those are performing some sort of validation, you really should be doing that in a form class instead of in the view. I also wouldn't be pulling values directly out of the request.POST to populate your model. I would highly recommend retrieving those values from a form's cleaned_data dictionary.