I would like to upload a folder to my application but on the server side the request.FILES collection is always empty.
Also form.is_valid evaluates to false
The solution for this problem seems to be to add enctype="multipart/form-data" but I have already added it an it doesn't work.
As described here SO TOPIC ABOUT THIS
Inside the browser I also get "This field is required" after pressing submit and yes I have choosen a directory.
Here my relevant code
model.py
# Create your models here.
class Datasets(models.Model):
dataset_name = models.CharField(max_length=100, blank=True, null=True)
description = models.CharField(max_length=1000, blank=True, null=True)
share_with = models.ManyToManyField(User)
uploaded_by = models.CharField(max_length=1000, blank=True, null=True)
upvotes = models.IntegerField(null=False, default=0)
downvotes = models.IntegerField(null=False, default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
datafiles = models.FileField(blank=True, null=True)
form.py
class UploadDatasetForm(forms.Form):
dataset_name = forms.CharField(
max_length=1000,
widget=forms.TextInput(attrs={'class': 'form-control'}))
description = forms.CharField(
max_length=1000,
widget=forms.TextInput(attrs={'class': 'form-control'}))
share_with = forms.MultipleChoiceField(
choices=tuple(UserProfile.objects.values_list('id', 'full_name')),
widget=forms.CheckboxSelectMultiple,
)
datafiles = forms.FileField(widget=forms.ClearableFileInput(
attrs={
'multiple': True,
'webkitdirectory': True,
'directory': True,
}))
the template
{% block content %}
<h2>Register Here</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
view.py
#login_required
def upload_dataset(request):
print(request.user)
form = UploadDatasetForm()
if request.method == "POST":
print('Receiving a post request')
form = UploadDatasetForm(request.POST, request.FILES)
print(request.FILES)
if form.is_valid():
print("The form is valid")
print(form.cleaned_data)
dataset_name = form.cleaned_data['dataset_name']
description = form.cleaned_data['description']
datafiles = form.cleaned_data['datafiles']
share_with = form.cleaned_data['share_with']
users_to_share_with = set()
print(datafiles)
instance = Datasets.objects.create(
uploaded_by=request.user,
dataset_name=dataset_name,
description=description,
datafiles = datafiles,
upvotes=0,
downvotes=0,
)
for i in share_with:
instance.share_with.add(i)
return redirect("public:data")
print("The Dataset has been uploaded")
context = {"form": form}
return render(request, "upload_dataset.html", context)
{% endblock %}
I receive the message Receiving a post request but it will not go inside the form.is_valid
The output after pressing the submit button is
System check identified no issues (0 silenced).
July 25, 2021 - 11:42:53
Django version 3.2.3, using settings 'platform_oliveoils.settings'
Starting development server at http://0.0.0.0:40/
Quit the server with CONTROL-C.
Max
Receiving a post request
<MultiValueDict: {}>
Related
I have a drop drop down list as in below image.It should only show the logged user campaigns (here the last free item. But it's showing the others users campaign.
Any help is apprecieated. Here are :
Is there a way to add parameter in my {filter.form} to show only the logged item and note the other users's item?
my form.html template:
<form class="#" method="get" enctype="multipart/form-data">
{% csrf_token %}
{{filter.form}}
<button type="submit">Search</button>
Reset
</form>
Here is my view:
def insertion_orders(request, pk):
if request.user.is_authenticated:
user = User.objects.get(id=pk)
insertion_orders = user.insertionorder_set.all().order_by('-created_date')
filter = InsertionOrdersFilter(request.GET, queryset=insertion_orders)
insertion_orders_filter = filter.qs
print(insertion_orders_filter)
context = {
'user': user,
'insertion_orders': insertion_orders_filter,
'filter': filter
}
return render(request, 'insertion_orders.html', context)
else:
return HttpResponse('You re not logged in ! Please log in first')
My model:
class UserInsertionOrder(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
campaign_naming_tool = models.ForeignKey(CampaignNamingTool,
on_delete=models.CASCADE)
budget = models.DecimalField(max_digits=20, decimal_places=2)
goal_value = models.DecimalField(max_digits=20, decimal_places=2)
start_date = models.DateField()
end_date = models.DateField()
created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return "%s" % self.campaign_naming_tool
# return "{} - [{}]".format(self.insertion_order, self.user)
class Meta:
db_table = 'InsertionOrder'
Change the insertion_orders line to:
insertion_orders = user.insertionorder_set.filter(user=request.user).order_by('-created_date')
Next, try commenting out the next 3 lines below the line I requested you to modify.
Finally, change the context statement to:
context = {
'user': user,
'insertion_orders': insertion_orders,
'filter': filter
}
I am trying to add client to my client model along with the user model using Django forms. But as of now I am getting a key error. I am not able to figure out what is wrong with this and would appreciate some help on this one.
My clients model is this
class Clients(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
primaryphone = models.CharField(max_length=15, unique=True)
location = models.CharField(max_length=30, choices=States)
project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1)
contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
The view for this are
def add_client(request):
form = AddClientForm()
context = {
"form": form
}
return render(request, 'admintemplate/add_client_template.html', context)
def add_client_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect('add_client')
else:
form = AddClientForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
phone = form.cleaned_data['phone']
location = form.cleaned_data['location']
project_id = form.cleaned_data['project_id']
contract_id = form.cleaned_data['contract_id']
try:
user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3)
user.clients.location = location
user.client.primaryphone = phone
project_obj = Projects.objects.get(id=project_id)
user.clients.project_id = project_obj
contract_obj = Contracts.objects.get(id=contract_id)
user.clients.contract_id = contract_obj
user.clients.save()
messages.success(request, "Client Added Successfully!")
return redirect('add_client')
except:
messages.error(request, "Failed to Add Client!")
return redirect('add_client')
else:
return redirect('add_client')
This is my forms.py
class AddClientForm(forms.Form):
email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"}))
password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"}))
first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
phone = forms.CharField(label="Phone", max_length=15, widget=forms.TextInput(attrs={"class":"form-control"}))
#For Displaying Projects
try:
projects = Projects.objects.all()
project_list = []
for project in projects:
single_project = (project.id, project.project_name)
project_list.append(single_project)
except:
project_list = []
#For Displaying Contracts
try:
contracts = Contracts.objects.all()
contract_list = []
for contract in contracts:
single_contract = (contract.id, contract.contract_name)
contract_list.append(single_contract)
except:
contract_list = []
project_name = forms.ChoiceField(label="Project", choices=project_list, widget=forms.Select(attrs={"class":"form-control"}))
contract_id = forms.ChoiceField(label="Contract", choices=contract_list, widget=forms.Select(attrs={"class":"form-control"}))
location = forms.ChoiceField(label="Location", choices=States, widget=forms.Select(attrs={"class":"form-control"}))
And this is my add client template
{% block main_content %}
{% load static %}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!--general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add Client</h3>
</div>
<!--/.card-header -->
<!--form start -->
{% url 'add_client_save' as action_path %}
{% include 'admintemplate/form_template.html' with messages=messages form=form action_path=action_path button_text="Add Client" %}
</div>
/.card
</div>
</div>
</div><!-- /.container-fluid -->
</section>
{% endblock main_content %}
I get the following error message
KeyError at /add_client_save/
'project_id'
Request Method: POST
Request URL: http://d1bbcb8e2c574d65bcfc28f937c87503.vfs.cloud9.us-east-2.amazonaws.com/add_client_save/
Django Version: 3.0.7
Exception Type: KeyError
Exception Value:
'project_id'
Exception Location: /home/ec2-user/environment/powercons/powercons_app/adminviews.py in add_client_save, line 337
Python Executable: /usr/bin/python3
Python Version: 3.7.10
Python Path:
['/home/ec2-user/environment/powercons',
'/usr/lib64/python37.zip',
'/usr/lib64/python3.7',
'/usr/lib64/python3.7/lib-dynload',
'/home/ec2-user/.local/lib/python3.7/site-packages',
'/usr/local/lib64/python3.7/site-packages',
'/usr/local/lib/python3.7/site-packages',
'/usr/lib64/python3.7/site-packages',
'/usr/lib/python3.7/site-packages']
Server time: Sun, 8 Aug 2021 10:23:08 -0600
Your form AddClientForm does not contains a project_id field but you want to use it in form.cleaned_data['project_id']
Your error is :
Exception Type: KeyError
Exception Value: 'project_id'
I have a view with a list of tasks and tried to do simple task allocation on click but it is not working. Could you please support? I see in my console sth like that:
"POST /task/allocate HTTP/1.1" 302 0.
Thank you.
L
model:
class Task(models.Model):
name = models.CharField(max_length=248)
note = models.TextField(blank=True, null=True)
priority = models.NullBooleanField(blank=True, null=True)
status = models.IntegerField(choices=TASK_STATUS, default=TASK_STATUS[0][0])
placed_date = models.DateField(auto_now=True)
due_date = models.DateTimeField(blank=True, null=True)
completed = models.BooleanField(default=False)
completed_date = models.DateField(blank=True, null=True)
created_by = models.ForeignKey(
User,
null=True,
blank=True,
related_name="hana_created_by",
on_delete=models.CASCADE)
assigned_to = models.ForeignKey(User,
null=True,
blank=True,
related_name="hana_assigned_to",
on_delete=models.CASCADE)
urls:
path('excel_table', ex_views.ExcelTableView.as_view(), name = "excel-table"),
path("task/add", ex_views.TaskAddView.as_view(), name="task-add"),
path("task/<int:task_id>/", ex_views.TaskDetailView.as_view(), name="task-detail"),
path("task/<int:pk>/edit", ex_views.TaskEditView.as_view(), name="task-update"),
path("task/allocate", views.task_allocator, name="task-allocate"),
views:
class TaskAllocateView(View):
def post(self, request):
if request.POST.get("task_allocate") is not None:
tasks = Task.objects.filter(assigned_to=None)
for task in tasks:
task.assigned_to = random.choice(User.objects.all())
task.status = 1
task.save()
current_site = get_current_site(request)
subject = render_to_string('email/assigned_subject.txt', {"task": task})
body = render_to_string('email/assigned_body.txt', {
'task': task,
'site': current_site,
})
to_email = task.assigned_to.email
email = EmailMessage(subject, body, to=[to_email])
email.send()
if tasks:
messages.success(request, "Tasks succesfully allocated to your employees. Check status!")
messages.success(request, ('Notification email has been sent to assignees!'))
else:
messages.warning(request, "All tasks already allocated!")
messages.warning(request, ('Notification email already sent!'))
return redirect(reverse("excel-table"))
return redirect(reverse("excel-table"))
template:
<form method="POST" action="{% url "task-allocate" %}" role="form" class="d-inline">
{% csrf_token %}
<div style="display:inline;">
<button class="btn btn-info btn-sm" type="submit" name="task_allocate">
Task Allocate
</button>
</div>
</form>
if t.assigned_to != None:
t.status = 1
t.save()
messages.success(request, "Tasks succesfully allocated to your employees. Check status!")
return redirect(reverse("excel-table"))
this if will never be executed because created_by will remain Non until you save it.
t.assigned_to = random.choice(User.objects.all())
if t.assigned_to != None:
you did this thinking that this t.assigned_to is not None anymore, well it remains None because you didnt save.
i hope this one will help you.
I am using custom user authentication for verifying user. I have table named voter and I am tacking username and password via from and matching that with username and password of table if it match user will be logged in and allowed them to pass to next page which contain form. In that form I initiated data but it will not appear automatically it will appear only when i refresh the page
code of my files is bellow (for some big file only relevant code is included that's why it is partial)
model.py (partial)
class Voter(models.Model):
serial_voter_id = models.AutoField(primary_key=True)
voter_id = models.CharField(unique=True, max_length=10)
voter_name = models.CharField(max_length=255)
voter_constituency = models.ForeignKey(Constituency, models.DO_NOTHING, blank=True, null=True)
username = models.CharField(unique=True, max_length=32)
password = models.TextField()
voter_address = models.CharField(max_length=255, blank=True, null=True)
area = models.CharField(max_length=10, blank=True, null=True)
city = models.CharField(max_length=10, blank=True, null=True)
pincode = models.IntegerField(blank=True, null=True)
adhar_no = models.BigIntegerField(unique=True)
birth_date = models.DateField()
age = models.IntegerField()
fingerprint = models.TextField(blank=True, null=True)
authenticity = models.CharField(max_length=3, blank=True, null=True)
wallet_id = models.TextField()
class Meta:
managed = False
db_table = 'voter'
forms.py
from django import forms
from .models import Voter
class VoterForm(forms.ModelForm):
class Meta:
model = Voter
fields = [
'serial_voter_id',
'voter_id',
'voter_name',
'voter_constituency',
'username',
'voter_address',
'area',
'city',
'pincode',
'adhar_no',
'birth_date',
'age',
'authenticity',
'wallet_id'
]
views.py (partial)
from .models import Voter
from .forms import VoterForm
def voter_login(request, *args, **kwargs):
contex = {}
return render(request, "poll/voter_login.html", contex)
def voter_verification(request, *args, **kwargs):
f_username = request.POST.get('username')
voter = Voter.objects.get(voter_id=1) # thing need to be dynamic hear by replacing it with username
f_username = request.POST.get('username')
f_password = request.POST.get('password')
u_password = voter.password # fetching the password from voter object
u_password = u_password.decode() # decoding binary password to string
form = VoterForm(request.POST or None, instance=voter)
if form.is_valid():
form.save()
form = VoterForm()
contex = {
'voter' : voter,
'f_username' : f_username,
'f_password' : f_password,
'u_password' : u_password,
'form' : form
}
# compare hear username and password entered by user and from database if these are correcgt then allow this view or redirect to voter_login view
if voter.username == f_username and u_password == f_password:
return render(request, "poll/voter_verification.html", contex)
else:
return render(request, "poll/voter_login.html", {})
voter_login.html
{% extends 'header.html' %}
{% block content %}
<table>
<form method="get" action='voter_verification'> {% csrf_token %}
username <input type="text" name="username">
password <input type="password" name="password">
<input type="submit" name="login" value="login">
</form>
{% endblock %}
voter_verification.html (template file)
<!DOCTYPE html>
<html>
<body>
{% if f_username == voter.username and f_password == u_password %}
<h1>verified</h1>
{% else %}
<h1>wrong id and password</h1>
{% endif %}
<form method='post' action='vote_page'> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value="sumbit">
</form>
</body>
</html>
changes query in view model ( def voter_verification(request, *args, **kwargs):)
def voter_verification(request, *args, **kwargs):
f_username = request.POST.get('username')
voter = Voter.objects.get(username=f_username)
then request user check in voter table which have exits with same user name.
Thanks to DrMaxwellEdison from reddit for providing answer
https://www.reddit.com/r/djangolearning/comments/fecn1f/question_django_data_in_form_only_appear_after/
Please do not have a separate model that stores usernames and passwords aside from your User model. You can simply add a OneToOneField to the User model to connect this Voter model to the authenticated User, and you don't need to do any extra data storage (plus, you are more likely to be handling the password information incorrectly, exposing it to being compromised if your site is breached).
Also per your comment on SO, the POST is not working because of CSRF protection (the traceback of your error would likely have indicated this already). Please see those docs for details on how to proceed (hint: do not disable CSRF!).
I've already read many other threads complaining about this error message but I still can't figure this out. I try removing the fields that give the error, and the error message just moves to another field the next time I try to submit. They are CharField, Foreign Key, and other types.
forms.py
class TemporaryresponseForm(forms.ModelForm):
gender_custom = forms.CharField(
required=False,
label="",
)
ethnicity = forms.ModelChoiceField(
queryset=Ethnicity.objects.all(),
widget=forms.RadioSelect(),
empty_label=None,
required=True,
label="Which of the following best describes your ethnicity?"
)
...
class Meta:
model = Temporaryresponse
fields = [...'gender_custom', 'ethnicity',...]
views.py
def tr(request):
if request.method == "POST":
form = TemporaryresponseForm(request.POST)
if form.is_valid():
tempresponse = form.save(commit=False)
tempresponse.ip = "123456"
tempresponse.save()
return redirect('politicalpollingapp/index.html')
else:
form = TemporaryresponseForm()
return render(request, 'politicalexperimentpollapp/tr.html', {'form': form})
def nr(request, pk):
return render(request, 'politicalexperimentpollapp/nr.html', {'tempresponse': tempresponse})
tr.html template
{% extends 'politicalexperimentpollapp/base.html' %}
{% block extrahead %}
{% load crispy_forms_tags %}
{{ form.media }}
{% endblock extrahead%}
...
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<div><br></div>
<div class="text-center"><button type="submit" class="save btn btn-primary">CONTINUE</button></div>
</form>
..
models.py
class Ethnicity(models.Model):
ethnicity = models.CharField(max_length=200)
def __str__(self):
return '%s' % (self.ethnicity)
...
class Temporaryresponse(models.Model):
birth_year = models.PositiveIntegerField()
voting_registration = models.ForeignKey(Voting_registration, models.SET_NULL, null=True)
party_identification = models.ForeignKey(Party_identification, models.SET_NULL, null=True)
gender = models.ForeignKey(Gender, models.SET_NULL, null=True)
gender_custom = models.CharField(max_length=200, blank=True)
ethnicity = models.ForeignKey(Ethnicity, models.SET_NULL, null=True)
race = models.ManyToManyField(Race)
zip_code = models.IntegerField()
ip = models.CharField(max_length=200, blank=True)
policy_areas_of_importance = models.ManyToManyField(Policy_category, blank=True)
likelihood_of_voting = models.PositiveIntegerField(models.SET_NULL, null=True, blank=True)
Oddly no error shows up in my Chrome console - it's only because I am showing errors on the actual page. I'm not sure if that's normal. Thanks in advance for any help, I'm ripping my hair out at this point.
I discovered that I was using the wrong language for the "race" form field. I had used ModelChoiceField but it should be ModelMultipleChoiceField as follows:
race = forms.ModelMultipleChoiceField(queryset=Race.objects.all(), widget=forms.CheckboxSelectMultiple, label="5. Which of the following best describes your race? Please select all that apply.")