Why is fileChoice.value() None? - python

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">

Related

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})

Creating CRUD with pymongo in django

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]

How to use the same auth userprofile in multiple apps in Django 1.6

I'm using Django 1.6 auth module to login users and I have a project consisting of two apps and I want to use the same user by calling request.user.username in the view in my second app. That is, in my template login.html in the first app this works {% if user.is_authenticated %} but {% if user.is_authenticated %} does not work in the second apps templates and I'm wondering how I can fetch it in functions in the second app? I've tried to fetch it with user=request.user.username but it doesn't work.
In my first app:
models.py
from django.contrib.auth.models import User
class Userprofile(models.Model):
user = models.OneToOneField(User)
title = models.CharField(max_length = 70)
def __unicode__(self):
return self.title
class OneUser(models.Model):
Firstname = models.CharField(max_length = 35)
Lastname = models.CharField(max_length = 35)
Email = models.EmailField()
belongsTo = models.ForeignKey(Userprofile, related_name='pcslabeler_userprofile')
def __unicode__(self):
return self.Firstname
in views.py
def LoginIndex(request):
c = {}
c.update(csrf(request))
return render(request,"login.html", c)
#logins = Login.objects.all()
def one_login(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)# user firstname lastname
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/loggedin')# topic
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render(request,"loggedin.html",{'full_name': request.user.username})
def invalid_login(request):
return render(request,"invalid_login.html")
def logout(request):
auth.logout(request)
return render(request,"logout.html")
In the second apps view I'm trying to use it in the function postoneEval:
def EvalIndex(request):
evals = Evaluation.objects.all()
return render_to_response("evaluation_index.html",{"evals":evals})
def one_evaluation(request, postID):
one_eval = Evaluation.objects.get(id=postID)
one_part = Participation.objects.get(id=postID)
if request.method == 'POST':
form = EvalForm(request.POST)
form2 = ParticipationForm(request.POST)
if form.is_valid() and form2.is_valid():
postoneEval(request, one_eval)
postoneParticipant(request, one_part)
else:
form = EvalForm()
form2 = ParticipationForm()
c = {"one_eval":one_eval,"one_part":one_part, "form":form, "form2":form2}
c.update(csrf(request))
return render_to_response("one_evaluation_index.html", c )
def postoneEval(request, one_eval):
title = request.POST["title"]
user = request.user.username
oneEval = OneEvaluation(datetime=datetime.datetime.now(), belongsTo=one_eval, title=title, user=user)
oneEval.save()
The problem is in the render_to_reponse() call. You do not pass the RequesContext instance so context processors aren't run for your templates.
The simplest solution for this issue is to replace the render_to_response() with the render():
return render(request, "evaluation_index.html", {"evals":evals})
and:
return render(request, "one_evaluation_index.html", c)

Unable to save model instance with django

I am attempting to save simple data based on a button submission. But i keep getting following error:
TypeError at /exercise/1/
save() got an unexpected keyword argument 'commit'
models.py:
class StrategyHistory(models.Model):
user = models.ForeignKey(User)
strategy = models.ForeignKey(Strategies)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = datetime.datetime.today()
self.modified = datetime.datetime.today()
return super(StrategyHistory, self).save(*args, **kwargs)
def __unicode__(self):
return self.strategy.name
views.py:
def exercise_view(request, pk):
template_name = 'mobileApp/page/exercise.html'
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('mobile_user_login'))
strategy = Strategies.objects.get(pk=pk)
context = {
'strategy':strategy,
}
if request.method == 'POST':
strategyhistory = StrategyHistory()
entry = strategyhistory.save(commit=False)
entry.user = self.request.user
entry.strategy = Strategies.objects.get(id=pk)
entry.save()
if pk < 5:
return HttpResponseRedirect(reverse('mobile_exercise', kwargs={'pk':pk+1}))
else:
return HttpResponseRedirect(reverse('mobile_comeback_later'))
return render_to_response(template_name,
context,
context_instance = RC( request, {} ))
html-file:
<form action="" method="post">{% csrf_token %}
Prøv igen
<button type="submit" value="submit" data-inline="true" data-transition="flow" data-icon="check" data-theme="b">Fortsæt</button>
</form>
I am running Django 1.6.2
Your view use StrategyHistory model incorrect. That is the use of forms. This is correct.
def exercise_view(request, pk):
template_name = 'mobileApp/page/exercise.html'
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('mobile_user_login'))
strategy = Strategies.objects.get(pk=pk)
context = {
'strategy':strategy,
}
if request.method == 'POST':
strategyhistory = StrategyHistory.objects.create(
user=request.user,
strategy=strategy)
if pk < 5:
return HttpResponseRedirect(reverse('mobile_exercise', kwargs={'pk': pk + 1}))
else:
return HttpResponseRedirect(reverse('mobile_comeback_later'))
return render_to_response(template_name,
context,
context_instance = RC( request, {} ))
Also you cannot use self.request in that view. There is no self declared.
May be this is what you want:
class StrategyHistory(models.Model):
user = models.ForeignKey(User)
strategy = models.ForeignKey(Strategies)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.strategy.name

Categories

Resources