facing problems in uploading files to a particular directory - html

i am using a html template to upload a file but i don't know how to process that file in django views file
i also have a model which is connected with the database
here is my html file
{% extends 'base.html' %}
{% block body %}
<form action="file" method="post" enctype="multipart/form-data" >
{% csrf_token %}
<input type="text" name="userName" placeholder="username">
<input name="file" type="file">
<input type="submit" value="submit">
</form>
{% for message in messages %}
{{ message }}
{%endfor%}
{% endblock %}
and here is my views.py function
def File(request):
if request.user.is_authenticated:
if request.method == 'POST':
user = request.POST['userName']
file = request.FILES
print(file)
# file = request.POST.copy()
# file.update(request.FILES)
# content_type = copied_data['file'].get('content-type')
# path = os.path.join(r'C:\Users\harsh\PycharmProjects\swatchBharat\SwatchBharat\media\files\\',file)
if User.objects.filter(username=user).exists():
file2 = points()
file_obj1 = DjangoFile(open(file, mode='rb'), name=file)
file_obj = File.objects.create(title=file, file=file_obj1, content_object=file, author=file.client)
file2.file =file2.save(ContentFile(file_obj))
file2.user = user
file2.save()
return HttpResponse('sucess bale bale!!!!!!!')
else:
messages.info(request,'the username you entered is incorrect')
return redirect("file")
return render(request, 'file.html')
else:
return HttpResponse('sorry this is restricted, login to continue')
my model.py file
from django.db import models
# Create your models here.
class points(models.Model):
user = models.TextField(max_length=50,default=None)
file = models.FileField(upload_to='files/')
point_3 = models.BooleanField(default=False)
point_5 = models.BooleanField(default=False)
point_9 = models.BooleanField(default=False)
i am stuck with it pls someone help me out

the solution for this is simple , thanks to shivendra-pratap-kushwaha for documentation link - docs.djangoproject.com/en/3.2/topics/http/file-uploads this was really helpfull
just need to specify request.FILES['file'] instead of request.FILES

Related

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed

I'm creating app with authentication. My project is dockerized. When I run the server everything works fine, except
authentication.User: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
But when I want to run docker-compose exec web python3 manage.py makemigrations or docker-compose exec web python3 manage.py migrate I get an error:
File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/init.py", line 176, in get_user_model
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed
I've thought it points to settings.py field AUTH_USER_MODEL, but I haven't got it.
My views.py:
def signup(request):
if request.method == "POST":
context = {'has_error': False, 'data': request.POST}
email = request.POST.get('email')
username = request.POST.get('username')
password = request.POST.get('password')
if len(password) < 6:
messages.add_message(request, messages.ERROR,
'Password should be at least 6 characters')
context['has_error'] = True
if not validate_email(email):
messages.add_message(request, messages.ERROR,
'Enter a valid email address')
context['has_error'] = True
if not username:
messages.add_message(request, messages.ERROR,
'Username is required')
context['has_error'] = True
if models.User.objects.filter(username=username).exists():
messages.add_message(request, messages.ERROR,
'Username is taken, choose another one')
context['has_error'] = True
return render(request, 'authentication/signup.html', context) # status=409
if models.User.objects.filter(email=email).exists():
messages.add_message(request, messages.ERROR,
'Email is taken, choose another one')
context['has_error'] = True
return render(request, 'authentication/signup.html', context) # status=409
if context['has_error']:
return render(request, 'authentication/signup.html', context)
user = models.User.objects.create_user(username=username, email=email)
user.set_password(password)
user.save()
return render(request, 'authentication/signup.html')
My models.py:
from django.db import models
class User(models.Model):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username = models.CharField(
max_length=200
)
def __str__(self):
return self.email
My signup.html:
{% include "_base.html" %}
{% load static %}
{% block title %}Sign Up{% endblock title %}
{% block content %}
<link rel="stylesheet" href="{% static 'css/authentication/signup.css' %}">
<div class="container">
<form class="signup_form" method="post" action="{% url 'signup' %}">
{% csrf_token %}
<input type="text" placeholder="Email" class="input_1" name="email">
<input type="text" placeholder="Username" class="input_2" name="username">
<input type="text" placeholder="Password" class="input_3" name="password">
<button type="submit" class="submit_btn">Sign Up</button>
</form>
</div>
{% endblock content %}
_base.html is just navbar.
When I add AUTH_USER_MODEL to settings.py it results in same error.
For this you should try adding an id field in the user model like so:
from uuid import uuid4
id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
Also in your user model add this to the class:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
I advice you also change the class name form User to CustomUser to avoid clashes with internal django backend, that will be.
From:
class User(models.Model):
to:
class CustomUser(AbstractUser):

How do I use a for loop to reuse a django form in a template

After struggling with this issue for a while, I am hoping someone here can point me in a more productive direction.
I am trying to take an indeterminate number of variables in a database (obtained through a different template) and render them on a webpage, each variable with a simple data entry form, to be saved back to the database. Basically, it's a tracker for analysis. Say I want to track my daily sleep, running time, and calorie intake (the variables). I have those saved in a database as variables and want to call upon those variables and show them on a webpage with a daily entry form. I am using a "for" loop right now and it renders the way I want it to, with the variable name and the form, but it is only saving the last item in the variable list. How do I amend the code below such that when I hit the save button for each form rendeded, it saves the information for that variable (not just the last one rendered).
Below is the code. Any and all help would be infinitely appreciated.
Models...
class Variable(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE) # id the active user
ENTRY_TYPE_CHOICES = [
('numeric', 'enter a daily number'),
('scale', 'rate daily on a scale of 1-10'),
('binary', "enter daily, 'yes' or 'no' "),
]
variable = models.CharField(max_length=50, default='')
entry_type = models.CharField(max_length=50, choices=ENTRY_TYPE_CHOICES, default="numeric")
def __str__(self):
return self.variable
class DailyEntry(models.Model):
date = models.DateField(default=datetime.date.today)
# date_added = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE) # id the active user
variable_name = models.CharField(max_length=50, default='')
variable_id = models.SmallIntegerField(default=0000)
entry = models.FloatField(default=9999)
class Meta:
verbose_name_plural = 'Daily Entries'
def __str__(self):
return self.variable
Form...
class VariablesForm(forms.ModelForm):
class Meta:
model = Variable
fields = ['variable', 'entry_type' ]
labels = {'variable':'Dependent variable to track', 'entry_type': 'Type of measure'}
class DailyEntryForm(forms.ModelForm):
class Meta:
model = DailyEntry
fields = ['variable_name', 'variable_id', 'entry', 'date']
labels = {'entry': 'Daily entry', 'date': 'Date'}
widgets = {'variable_name': forms.HiddenInput(), 'variable_id': forms.HiddenInput()}
Views...
def daily_entry(request):
''' page to make daily entries '''
vars = Variable.objects.filter(id__gt = 0 )
if request.method != 'POST':
# No data submitted. GET submitted. Create a blank form
form = DailyEntryForm()
else:
#POST data submitted. Process data
form = DailyEntryForm(data=request.POST)
if form.is_valid():
data = form.save(commit=False)
data.created_by = request.user
data.save()
return HttpResponseRedirect(reverse('entry_new'))
context = {'form': form, 'vars': vars}
return render(request, 'entry_new.html', context)
and HTML...
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
{% for var in vars %}
<div>
<ul>
<h3>{{ var.variable }}</h3>
<form class="" action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="hidden" name="variable_id" value="{{ var.id }}" >
<input type="hidden" name="variable_name" value="{{ var.variable }}">
<input type="submit" name="" value="Save" />
</ul>
</div>
{% endfor %}
{% endblock content %}
Any help, well, helps...
Thanks!

Django how to adding comments option on a post

I am developing a blog which i want to add comment form option to it, i have added the form to the same page directly under the article, i want that went a user comment it should redirect to the same page with the article but i keep getting and error
here is my code
view
def comment(request, article_id):
try:
article = Article.objects.get(pk=article_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.cleaned_data['comment']
article.comments_set.create(comment=comment)
#messages.infos(request,comment)
return redirect('blog:_article')
#else:
#pass
#form = CommentForm()
#context['form'] = form
#return render(request,'blog/comment.html', context)
except Exception as e:
#wriet error to file
return render(request,'blog/404.html')
urls
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
path('<int:article_id>/article', views._article, name='_article'),
path('<int:article_id>/comment', views.comment, name='comment'),
]
models
class Comments(models.Model):
comment = models.TextField()
date = models.DateTimeField(default=timezone.now)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
def __str__(self):
return self.comment
form
<form method="post" action="{% url 'blog:comment' article.id %}">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
{% render_field field class="form-control is-valid" rows="4" %}
{% endfor %}<br>
<button class="btn btn-success">Post</button>
</form>
I finally did it by adding the code to handle the comment in the same view that renders the articles this is my code
def _article(request, article_id):
try:
article = Article.objects.get(pk=article_id)
related_articles = Article.objects.filter(tags=article.tags).exclude(pk=article.pk)[:4]
context['article'] = article
context['related_articles'] = related_articles
context['form'] = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.cleaned_data['comment']
article.comments_set.create(comment=comment)
return render(request,'blog/article.html', context)
except Exception as e:
#write error to file
return render(request,'blog/404.html')
If you don't want the page to redirect to another page or update the page, you should use AJAX (https://www.w3schools.com/jquery/jquery_ajax_get_post.asp) in this case. Your form will hit the url in the action by changing your page to that url so you have to handle the redirecting and rendering in your commenting view to come back to same page if you don't wanna do this dynamically.

Flask validate and upload file to web page to

I've been attempting to upload and use a file to my web page but continually run into errors. I have searched repeatedly and tried many different solutions with no success. Any direction would be appreciated.
/app/forms.py
class UploadForm(FlaskForm):
cadfile = FileField('cadfile', validators=[FileRequired(), FileAllowed(['STEP','STP'], 'Step Files Only')])
upload = SubmitField('Upload')
def __init__(self, *args, **kwargs):
super(UploadForm, self).__init__(*args, **kwargs)
self.user = None
def validate(self):
initial_validation = super(UploadForm, self).validate()
if not initial_validation:
print('Fails')
return False
return True
This part of the code fails everytime at "not initial_validation", regardless of no file, incorrect file type or correct file type.
/app/routes.py
#app.route('/index', methods=['GET', 'POST'])
def index():
form = UploadForm()
if form.validate_on_submit():
if 'cadfile' in request.files:
cadfile = request.files['cadfile']
cadfile.save('/app/tmp/' + cadfile.filename)
print('Success')
else:
print('No Go')
return redirect(url_for('details'))
return render_template('index.html', title='Home', form=form)
And my html file
/app/templates/index.html
<html>
<head>
<title>Upload</title>
</head>
<body>
<h1>Let's Do This</h1>
<form method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.cadfile }}
{{ form.upload() }}
</form>
</body>
</html>
I would like to have it print out 'No File' when no file is selected, 'Invalid File Type' when not a STP or STEP file, and 'Success' when file is successfully uploaded.
Got it working. Here is my final code
/app/forms.py
class UploadForm(FlaskForm):
print('called uploadform')
cadfile = FileField('cadfile', validators=[FileRequired()])
upload = SubmitField('Upload')
/app/routes.py
def index():
form = UploadForm()
FILE_TYPES = set(['STEP'])
var.company_id = current_user.company_id
if form.validate_on_submit():
print('Validated')
submit_name = form.cadfile.data.filename
if '.' in submit_name and submit_name.rsplit('.', 1)[1] in FILE_TYPES:
print('Yea Baby it is!')
...
code
...
return redirect(url_for('details'))
else:
form.cadfile.errors.append('File is not an accepted format')
return render_template('index.html', title='Home', form=form)
/app/templates/index.html
<form method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<p>
{{ form.cadfile }}
{{ form.upload() }}<br>
{% for error in form.cadfile.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
</form>
</body>
Thanks

Uploading A file in django with ModelForms

I have been hacking away at this project for many hours now and just cannot figure out how to create a simple file upload app. I have looked at all the tutorials but none quite apply to my situation and i just cant get the code right. I know the code I have at this point wont run but I was hoping somone might be able to push me in the right direction with what I have. I know its not great but Im getting frustrated and I hope someone could help especially with my views.py Thank you so much. Thank you in advance!
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class WorkSheet(models.Model):
worksheet_name = models.CharField(max_length= 150, default = True)
creator = models.ForeignKey(User, default = True)
worksheet_file = models.FileField(upload_to = 'worksheets', default = True)
number_of_stars = models.PositiveIntegerField(default = True)
category = models.CharField(max_length = 100, default = 0)
class UploadWorkSheetForm(ModelForm):
class Meta:
model = WorkSheet
Views.py
from django.shortcuts import render, render_to_response, HttpResponseRedirect
from django.conf import settings
from django import http
from models import WorkSheet
from forms import UploadWorkSheetForm
def upload(request):
template = 'upload.html'
if request.method == 'POST':
if 'file' in request.FILES:
file = request.FILES['file']
filename = file['filename']
fd = open('%s/%s' % (settings.MEDIA_ROOT, filename), 'wb')
fd.write(file['content'])
fd.close()
return http.HttpResponseRedirect('upload_success.html')
else:
form = UploadWorkSheetForm()
return render_to_response(template, {'form': form})
return render(request, 'upload.html', {'form': form})
Upload.html
<!DOCTYPE html>
<html>
<head>
<title>WSD Upload</title>
</head>
<body>
<h1>Upload WorkSheet</h1>
{% block body %}
<form action="." method="post" enctype="multipart/form-data"> {{ form }}
<type="submit" value = "Upload"/>
</form>
{% endblock %}
</body>
</html>
If there is anything else you need please tell me. Thank you thank you thank you!
views.py
def upload(request):
template = 'upload.html'
if request.method == 'POST':
form = UploadWorkSheetForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('upload_success.html') <---change this to your valid url not template name
else:
form = UploadWorkSheetForm()
return render(request, 'upload.html', {'form': form})
template
...................
{% block body %}
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value = "Upload"/>
</form>
{% endblock %}
....................