Creating CRUD with pymongo in django - python

I'm trying to build a CRUD view with MongoDB using PyMongo (and I'm a little bit new to mongo/pymongo).
I created the full CRUD view using the normal forms and mysql, how can I use Mongo to do the same?
these are the main parts for my contacts app so far:
models.py:
class Contact(models.Model):
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
phone_number = models.CharField(max_length=60)
email_address = models.EmailField()
forms.py:
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = '__all__'
and views.py:
def contact_list(request):
contacts = Contact.objects.all().order_by("phone_number")
return render(request, 'contacts/contact_list.html', {'contacts': contacts})
def save_contact_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
contacts = Contact.objects.all().order_by("phone_number")
data['html_contact_list'] = render_to_string('contacts/includes/partial_contact_list.html', {
'contacts': contacts
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def contact_create(request):
if request.method == 'POST':
form = ContactForm(request.POST)
else:
form = ContactForm()
return save_contact_form(request, form, 'contacts/includes/partial_contact_create.html')
def contact_update(request, pk):
contact = get_object_or_404(Contact, pk=pk)
if request.method == 'POST':
form = ContactForm(request.POST, instance=contact)
else:
form = ContactForm(instance=contact)
return save_contact_form(request, form, 'contacts/includes/partial_contact_update.html')
def contact_delete(request, pk):
contact = get_object_or_404(Contact, pk=pk)
data = dict()
if request.method == 'POST':
contact.delete()
data['form_is_valid'] = True
contacts = Contact.objects.all()
data['html_book_list'] = render_to_string('contacts/includes/partial_contact_list.html', {
'contacts': contacts
})
else:
context = {'contact': contact}
data['html_form'] = render_to_string('contacts/includes/partial_contact_delete.html', context, request=request)
return JsonResponse(data)
I also have a mongo.py to set a simple connection.
I would appreciate the help!
I've looked at the docs of pymongo, and mongodb, and django but I couldn't find anything that matches what I'm looking for.
Thanks, and sorry for the long post!
<------EDIT 1 : PyMongo File ---->
mongo.py:
from django.conf import settings
from pymongo import MongoClient
class MongoConn(object):
clients = {}
#classmethod
def client(cls, name='default'):
if name not in cls.clients:
if name not in settings.MONGODB:
return None
cls.clients[name] = cls(settings.MONGODB.get(name))
return cls.clients.get(name)
def __init__(self, db_config):
self.conn = MongoClient(host=db_config.get('HOST'), port=db_config.get('PORT'))
self.db_name = db_config.get('NAME')
self._db = None
#property
def db(self):
if not self._db:
self._db = self.get_db()
return self._db
def get_db_name(self):
"""
:rtype: string
"""
return self.db_name
def get_db(self, db_name=None):
"""
:param db_name:
:rtype: pymongo.database.Database
"""
return self.conn[db_name or self.get_db_name()]
def get_collection(self, collection_name):
"""
:param string collection_name:
:rtype: pymongo.collection.Collection
"""
return self.db[collection_name]

Related

Why is fileChoice.value() None?

I am working in Django 3.2.13 trying to create a simple upload form for a file model with a chained foreign key. I have tried creating a form with a basic form model and a ModelForm, however, even when checking request.FILES there is no data and request_file = request.FILES['document'] if 'document' in request.FILES else Noneyields None.
views.py
def home(request):
if handleAuth(request) is not None:
return handleAuth(request)
user = request.user
if request.method == "POST":
# if the post request has a file under the input name 'document', then save the file.
form = FileSubmissionForm(user, request.POST, request.FILES)
#print(request.FILES)
#request_file = request.FILES['document'] if 'document' in request.FILES else None
#if request_file:
form.save()
#else:
# print("NO FILE")
userFiles = []
if user.is_company_admin:
temp = StorageFile.objects.filter(company_key=user.company_key)
else:
temp = StorageFile.objects.filter(company_key=user.company_key,
profile__in=user.user_profiles.all())
temp.order_by("profile")
for file in temp:
userFiles.append({"name": file.getFileName(), "path": file.getMediaPath()})
form = FileSubmissionForm(user)
return render(request=request,
template_name="fileCloudApp/home.html",
context={"userHasAdmin": user.is_company_admin, "files": userFiles, "form": form})
forms.py
from django import forms
from fileCloudApp.models import StorageFile
from loginApp.models import UserProfile
class FileSubmissionForm(forms.Form):
fileChoice = forms.FileField()
profileChoice = forms.ModelChoiceField(queryset=UserProfile.objects.none(), label="Choose profile")
def __init__(self, user, *args, **kwargs):
super(FileSubmissionForm, self).__init__(*args, **kwargs)
if user.is_company_admin:
temp = UserProfile.objects.filter(company_key=user.company_key)
else:
temp = user.user_profiles.all()
temp.order_by("label")
self.fields["profileChoice"].queryset = temp
self.user = user
def save(self):
print(self["fileChoice"].value()) # None
pro = UserProfile.objects.filter(id=int(self["profileChoice"].value()))
if len(pro) > 0:
pro = pro[0]
print(pro)
models.py
class StorageFile(models.Model):
date_updated = models.DateTimeField('Date Updated', default=timezone.now)
company_key = models.ForeignKey(CompanyModel, verbose_name="Company", on_delete=models.CASCADE)
file_upload = models.FileField(upload_to=company_directory_path)
profile = ChainedForeignKey(
UserProfile,
chained_field="company_key",
chained_model_field="company_key",
show_all=False,
auto_choose=True,
sort=True,
on_delete=models.PROTECT)
def getLocalPath(self):
return self.file_upload.name.split(str(self.company_key.id) + "/")[1]
def getMediaPath(self):
return "get/{0}/0/{1}".format(self.id, self.getFileName())
def getFileName(self):
return self.file_upload.name.split("/")[-1]
def getFilePath(self):
return settings.MEDIA_ROOT + "{0}/{1}".format(str(self.company_key.id), self.getFileName())
def __str__(self):
return str(self.company_key) + ": " + str(self.file_upload)
Form must contain enctype="multipart/form-data"
<form action="" method="post" enctype="multipart/form-data">

How to update an item in django without creating a new item?

I'm trying to update an item(book) present in the database, Even though I've added instance so that a new item is not created but instead the item is only updated, but unfortunately it's not working as it is supposed to, Instead of updating the item, a new item is being created, am I missing something in here?
models.py
class Book(models.Model):
book_name = models.CharField(max_length= 100)
author_name = models.CharField(max_length=100)
publisher = models.CharField(max_length=100)
published_on = models.DateTimeField(blank=True, null=True)
Language = models.CharField(max_length=100)
image = models.ImageField(blank = True, upload_to='images/')
created = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.book_name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = " "
return url
views.py
def book_register(request):
if request.method == 'POST':
form = BookForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/')
else :
return render(request, 'crud_operation/book_form.html', {'form': form})
else:
form = BookForm()
context = {'form':form}
return render(request,'crud_operation/book_form.html',context)
def book_update(request,pk):
book = Book.objects.get(id=pk)
form = BookForm(instance = book)
if request.method == 'POST':
form = BookForm(request.POST, request.FILES, instance=book)
if form.is_valid():
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'crud_operation/book_form.html',context)
urls.py
urlpatterns = [
path('create-book/',views.book_register, name = 'books'),
path('update-book/<int:pk>/',views.book_update, name = 'book_update'),
]
forms.py
class BookForm(ModelForm):
class Meta:
model = Book
fields = '__all__'
widgets = {
'published_on': DateInput(attrs={'type': 'date'})
}

Create #login_required like function for used Form(Modelform). So that User can't access confidential url without login-by typing just url?

I know that I can use #login_required but it is only used when we store user in User But in my case I stored model in form So it is not working for me. Also my created user is not getting authenticated when I use user.is_authenticated So I need custom login_required decorator which can be use to stop anyone from accessing direct url (confidential URl which are only accessed when you Login).
forms.py
class usrForm(forms.ModelForm):
password = forms.CharField(initial=123)
class Meta:
model = Person
fields = ('first_name','last_name','username','email','password','position')
def __init__(self, *args, **kwargs):
super(usrForm,self).__init__(*args,**kwargs)
self.fields['position'].empty_label = "Select"
class usrChange(forms.ModelForm):
class Meta:
model = Person
fields = ('username','password')
widgets= {
'password' : forms.PasswordInput(),
}
class loginForm(forms.ModelForm):
class Meta:
model = Person
fields = ('username','password')
widgets= {
'password' : forms.PasswordInput(),
}
models.py
class Position(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.title
class Person(models.Model):
first_name = models.CharField(max_length=50,default='')
last_name = models.CharField(max_length=50,default='')
username = models.CharField(max_length=50,default='')
password = models.CharField(max_length=50,default='')
email = models.EmailField(max_length=50)
position = models.ForeignKey(Position, on_delete=models.CASCADE)
def __str__(self):
return self.username
views.py
def user_list(request):
context = {'user_list' : Person.objects.all()}
return render(request, "usr_list.html", context)
def user_chnged_list(request):
form = usrForm(request.POST)
if form.is_valid():
form.save()
context = {'user_list' : Person.objects.all()}
return render(request, "usr_list.html", context)
def user_form(request, id=0):
if request.method == "GET":
if id ==0:
form = usrForm(initial={'password': 123}) # register
else:
auser = Person.objects.get(pk=id)
form = usrForm(instance=auser) #update
return render(request, "usr_form.html",{'form': form})
else:
if id == 0:
form = usrForm(request.POST , initial={'password': 123}) # register
else:
auser = Person.objects.get(pk=id) #update
form = usrForm(request.POST,instance=auser)
if form.is_valid():
form.save()
return redirect('login')
def user_delete(request,id):
auser = Person.objects.get(pk=id)
auser.delete()
return redirect('list')
def user_login(request):
form = loginForm()
if request.method == 'POST':
form = loginForm(data=request.POST)
if form.is_valid():
username=form.cleaned_data.get('username')
password=form.cleaned_data.get('password')
i = Person.objects.filter(username=username,password=password).exists()
user = {'user_list' : Person.objects.filter(username=username,password=password)}
if i == True:
j = Person.objects.filter(username=username, position_id = 1).exists()
if j == True:
return redirect('list')
return render(request,"usr_wlc.html", user )
else:
messages.error(request, 'Invalid username or password!')
context = {'form':form}
return render(request,'usr_login.html',context)
def user_detail(request,id):
auser = Person.objects.get(pk=id)
form = usrChange(request.POST,instance=auser)
if form.is_valid():
form.save()
return redirect('login')
def user_logout(request):
return redirect('/')
def user_change(request,id):
auser = Person.objects.get(pk=id) #update
form = usrChange(request.POST,instance=auser)
return render(request, "usr_chnge.html",{'form': form})

How to create a URL for templateView?

How can I write a url for a form using TemplateView. I wrote a method to validate and pass the company details through form. Using that form object that I'm trying to access the HTML fields.
Form.py
class CompanyDetailsForm(forms.Form):
class meta:
fields = ['company_name','contact_person','employee_count','email','mobile_number']
widgets = {
'comment':Textarea(attrs={'cols':30,'rows':5}),
}
company_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'company Name'}))
contact_person = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Contact Person'}))
email = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Email'}))
employee_count = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Number Of Employee'}))
mobile_number = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Mobile Number'}))
View.py
class GetCompanyView(TemplateView):
template_name = "astra/company_details.html"
form = CompanyDetailsForm()
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['form']=self.form
return context
def company_details(request):
if request.method =="POST":
form = CompanyDetailsForm(request.POST)
if form.is_valid():
company_name = form.cleaned_data['company_name']
contact_person = form.cleaned_data['contact_person']
email = form.cleaned_data['email']
employee_count = form.cleaned_data['employee_count']
mobile_number = form.cleaned_data['mobile_number']
try:
form.save()
send_mail(company_name,contact_person,email,employee_count,mobile_number,['salesastra500#gmail.com'])
except BadHeaderError:
return BadHeaderError
return render(request,'astra/company_details.html',{'form':form})
else:
return render(request,'astra/company_details.html')
I want to run my company_details.html file using TemplateView. I'm not able to write the url for same. Plz suggest
TemplateView only have get method
def get(self, request, *args, **kwargs):
return render(request,self.template_name, {'form': self.form})
if you have get and post methods use FormView

post() takes exactly 1 argument (2 given) django

I've been coding this, so i wanted to create like a forum, and this is the comments part, if you guys can help me i will be really thankfull.
views.py
class createComment(View):
form_class = CommentForm
template_name = "createComment.html"
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form':form})
def post(request):
try:
if request.method == "POST":
form = createComment()
if form.is_valid():
obj = form.save(commit=False)
obj.user_comment = request.user
obj.body_comment = request.POST["body_comment"]
obj.post_comment = request.POST[id]
obj.status_comment = False
obj.save()
return redirect('/')
else:
form = createComment()
except Exception, e:
return render_to_response("errorTemplate.html", {"message" : e.message})
return redirect('/')
models.py
class Comment(models.Model):
user_comment = models.ForeignKey("auth.User")
body_comment = models.TextField()
timestamp_comment = models.DateTimeField(auto_now=True)
post_comment = models.ForeignKey("Post", null=True)
status_comment = models.BooleanField()
def __unicode__(self):
return unicode(self.user_comment)
def __str__(self):
return self.title_comment
def get(self, request):
...
def post(request):
...
You forgot the self argument.

Categories

Resources