I want the value of username from forms that I get as a string so that when I upload an image it is stored in a subdirectory with that username.
i.e. if 'bob' registers the image should be saved in 'static/auth_image/bob/image_name.extension'.
Also if I could it during the registration form filling that would be great.
models.py
class User_data(models.Model):
username = models.CharField(max_length=256, null=True, blank=True)
email = models.EmailField(max_length=254, null=True, blank=True)
four_digit_pass = models.CharField(max_length=256, null=True, blank=True)
private_key = models.CharField(max_length=256, null=True, blank=True)
profile_pic = models.ImageField(upload_to='static/profilepic', null=True)
def getUsername(self):
return self.username
def __str__(self):
return str(self.username)
class AuthImages(models.Model):
owner = models.ForeignKey('User_data', null=True, on_delete=models.CASCADE)
uname=owner.
def save_auth_image(self):
uname = self.username
self.auth_image_file = models.ImageField(
upload_to='static/auth_image/%s' % uname, null=True)
forms.py
class RegistrationForm(forms.ModelForm):
four_digit_pass = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User_data
fields = ['username', 'email', 'four_digit_pass',
'profile_pic', 'private_key']
register.html
{% extends "storage_app/base.html" %}
{% block body_block %}
<div class="jumbotron">
<h1>Register Page</h1>
</div>
<div>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<p>Private Key should not be changed or shared with anyone</p>
<button type="submit">Upload</button>
</form>
</div>
{% endblock body_block %}
here in HTML, i want to take input for the second i.e. auth_image directly from webcam if possible
This is my first question also I am new to Django so please help me out if there is a cleaner way to write this and please excuse any mistakes.
Related
USERS can Upvote or Downvote Posts/Projects posted by Other Users:
screenshot of 'jammed' active dropdown selection box
THIS CODE DIRECTLY BELOW is the models.py that contains the Project class (model) with the vote_total and vote_ratio fields.
It also contains the Review class (model) which is the basis for the ReviewForm in forms.py (code included later)
class Project(models.Model):
owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
featured_image = models.ImageField(null=True, blank=True, default="default.jpg")
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.title
class Meta:
# ordering = ['-created']
ordering = ['-vote_ratio', 'vote_total', 'title']
AND here is the Review class (model)
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class Meta:
unique_together = [['owner', 'project']]
def __str__(self):
return self.value
Here is the ReviewForm from the forms.py
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ['value', 'body']
labels = {
'value': 'Place your vote',
'body': 'Add a comment with your vote'
}
def __init__(self, *args, **kwargs):
super(ReviewForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Here is the html template where the form is located
<div class="comments">
<h3 class="singleProject__subtitle">Comments</h3>
<h5 class="project--rating">
{{project.vote_ratio}}% Postitive ({{project.vote_total}} Vote{{project.vote_total|pluralize:"s"}})
</h5>
{% if request.user.profile.id in project.reviewers %}
<p>You have already submitted a comment!</p>
{% elif request.user.profile == project.owner %}
<p>You can't comment your own work!</p>
{% elif request.user.is_authenticated %}
<form class="form" action="{% url 'project' project.id %}" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#textarea">{{field.label}} </label>
{{field}}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg" type="submit" value="Add Review" />
</form>
{% else %}
Please login to leave a comment
{% endif %}
It was working okay when first implemented and has somehow developed this issue
This is running in venv with Python 3.9.6
Thank you for considering this question !
ADDED - rendered html
rendered html
I have these Models, Tipos, Prioridad and Estado, related to Tarea
as defined below:
class Tipos(models.Model):
tipo = models.CharField(max_length=16,
verbose_name='tipo')
abrv = models.CharField(max_length=4,
null=True,
blank=True,
default='')
class Meta:
verbose_name = "Tipo"
verbose_name_plural = "Tipos"
def __str__(self):
return self.tipo
class Prioridad(models.Model):
prioridad = models.CharField(max_length=16,
verbose_name='prioridad')
abrv = models.CharField(max_length=4,
null=True,
blank=True,
default='')
orden = models.IntegerField(u'orden', blank=False)
class Meta:
verbose_name = "Prioridad"
verbose_name_plural = "Prioridades"
def __str__(self):
return self.prioridad
class Estado(models.Model):
estado = models.CharField(max_length=16,
verbose_name='estado')
abrv = models.CharField(max_length=4,
null=True,
blank=True,
default='')
class Meta:
verbose_name = "Estado"
verbose_name_plural = "Estados"
def __str__(self):
return self.estado
class Tarea(models.Model):
numtar = models.AutoField(primary_key=True)
cliente = models.ForeignKey(User,
related_name='user_cliente',
null=True,
on_delete=models.DO_NOTHING)
apoyo = models.ForeignKey(User,
related_name='user_apoyo',
null=True,
on_delete=models.DO_NOTHING)
asignado = models.ForeignKey(User,
related_name='user_asignado',
null=True,
on_delete=models.DO_NOTHING)
descorta = models.CharField(max_length=140)
deslarga = models.TextField(max_length=8195)
estado = models.ForeignKey(Estado,
null=True,
on_delete=models.SET_NULL)
tipo = models.ForeignKey(Tipos,
null=True,
on_delete=models.SET_NULL)
prioridad = models.ForeignKey(Prioridad,
null=True,
on_delete=models.SET_NULL)
creacion = models.DateTimeField(auto_now_add=True)
revision = models.DateTimeField(auto_now=True, blank=True)
cierre = models.DateTimeField(null=True, blank=True)
class Meta:
verbose_name = "Tarea"
verbose_name_plural = "Tareas"
def __str__(self):
return '%s' % (str(self.numtar))
and I call the following view:
#login_required(login_url='/login')
def newincid_view(request):
perfil = ExUserProfile.objects.get(user=request.user)
prioridad_media = Prioridad.objects.get(prioridad='Media')
estado_abierta = Estado.objects.get(estado='Abierta')
tipo_incidencia = Tipos.objects.get(tipo='Incidencia')
datos_apertura = {'cliente': perfil.user,
'tipo': tipo_incidencia,
'prioridad:': prioridad_media,
'estado': estado_abierta
}
if request.method == 'POST':
form = newincidForm(request.POST,initial=datos_apertura)
if form.is_valid():
tar=form.save(commit=True)
apertura = TipoNota.objects.get(tiponota='Apertura')
anotacion = Nota(numtar=tar, tiponota=apertura,
anotador=perfil.user,
contenido='Incidencia Abierta')
anotacion.save()
else:
form = newincidForm(initial=datos_apertura)
return render(request, "incid/newincid.html", {'form':form})
with this form:
class newincidForm(ModelForm):
class Meta:
model = Tarea
exclude = ['numtar', 'creacion', 'revision', 'cierre']
def __init__(self, *args, **kwargs):
super(newincidForm, self).__init__(*args, **kwargs)
self.fields['descorta'].widget.attrs['class'] = 'form-control no-resize'
self.fields['deslarga'].widget.attrs['class'] = 'form-control no-resize autogrowth'
and this template:
{% extends "incid/base_incid.html" %}
{% load bootstrap3 %}
{% load static %}
{% load logo %}
{% load i18n %} <!-- Hooks para poder hacerlo multilingüe -->
{% load tags_html %}
{% block css %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<link rel="stylesheet"
href="{% static 'adminbsb/plugins/jquery-datatable/skin/bootstrap/css/dataTables.bootstrap.css' %}"/>
{% endblock %}
{% block content %}
<div class="container-fluid">
<div class="row clearfix">
<h4 style="margin-bottom: 10px; margin-top: 10px; padding-left: 15px">NUEVA INCIDENCIA</h4>
</div>
<div class="body">
<form action= "{% url 'incid:newincid' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
{{ form.errors }}
</div>
</div>
{% endblock %}
extending a standard base with no references to either prioridad, tipo or estado.
Nevertheless, when rendered, tipo and estado show the initial values but prioridad doesn't. I have rewritten view, form and template from scratch twice as I couldn't find a typo but it still happens. I would appreciate any clues or hints on what to do.
Note: This is a revisitation of another problem I posted that I do not know how to delete or edit.
Forget about it. It was something as silly as that I had included the semicolon into the quotes in the datos_apertura definition:
It was written this way:
'prioridad:': prioridad_media,
when it should have been
'prioridad': prioridad_media
Several days lost in such idiocy. An error should raise if I try to initiate an unknown field of a form ,Shouldn't it?. Also if PyCharm didn't take every thing as typos I wouldn't have had it silenced.
Thanks a lot and thanks for the patience in reading my posts.
Getting error when fields are selected from the down. Not seeing why it is throwing error
Django Dropdown form.error: ERROR ALERT:
location_name Select a valid choice. That choice is not one of the available choices.
Here is the model, form, view and html looks like
MODEL
class Code (models.Model):
name = models.CharField(max_length=4, default=None, blank=True)
def __str__(self): return self.name
class Device (models.Model):
code = models.ForeignKey(Code, on_delete=models.CASCADE, null=True)
ip = models.GenericIPAddressField(protocol='IPv4', unique=True)
def __str__(self): return self.ip
class SiteData (models.Model):
site = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True)
site_ip = models.ForeignKey(Device, on_delete=models.SET_NULL, null=True)
site_data1 = models.CharField(max_length=3, default='120')
class CombineData(models.Model):
location = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True)
device = models.ForeignKey(AddData, on_delete=models.SET_NULL, null=True)
locdata = models.ForeignKey(SiteData, on_delete=models.SET_NULL, null=True)
FORM
class CombineData_form(forms.ModelForm):
class Meta:
model = P2_NexusLeafPair
fields = '__all__'
VIEW
def comboView(request, *args, **kwargs):
template_name = 'site_display.html'
code = Code.objects.order_by('-name')
device = Device.objects.order_by('-ip')
sitename = SiteData.objects.order_by('-site')
content = {
'code': code,
'device': device,
'sitename': sitename
}
if request.method == 'POST':
form = CombineData_form(request.POST or None)
print(form.is_valid())
#print(form.errors)
if form.is_valid():
. . .
else:
messages.error(request, form.errors)
else:
form = CombineData_form()
return render(request, template_name, content)
HTML
<form id="comboView" class="post-form" role=form method="POST" action="comboView">{% csrf_token %}
<div name="code" class="dropdown" id="mainselection" required>
<select name="dc_name">
<option class="dropdown-item" value="">---------</option>
{% for item in code %}
<option value="{{ item }}">{{ item }}</option>
{% endfor %}
</div>
<input type="submit" value="Submit" />
</form>
{same as other fields: device, sitename}
{% for item in content %}
{{item.code}}
{% endfor %}
Try that.
I build a Blogpost App with Django and want comments under the blogpost. I can already post new comments, and see comments, but I see every comment under every blogpost. .
class blogpost(models.Model):
user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL)
title = models.TextField()
slug = models.SlugField(unique=True)
content = models.TextField(null=True, blank=True)
class blogcommment(models.Model):
user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL)
post = models.ForeignKey(blogpost, default=1, null=True, on_delete=models.SET_NULL)
title = models.TextField()
content = models.TextField(null=True, blank=True)
def blogpost_detail_view (request, slug):
# Blogeintrag anzeigen
obj = blogpost.objects.get(slug=slug)
form = blogcommentform(request.POST or None)
qs = blogcommment.objects.filter(***What should stay here and why?***)
if form.is_valid():
comment = blogcommment.objects.create(**form.cleaned_data)
form = blogcommentform
template_name = 'blogpost_detail.html'
context = {"object": obj,'form': form,'object_list': qs}
return render(request, template_name, context)
{% extends "base.html" %}
{% block content %}
<h1>{{ object.title }}</h1>
<p>{{ object.content }}</p>
<form method="POST" action=""> {% csrf_token %}
{{ form.as_p }}
<button type='submit'>Senden</button>
</form>
{% for object in object_list %}
{{ object.content }}
{% endfor %}
{% endblock %}
class blogcommentform(forms.Form):
title = forms.CharField()
content = forms.CharField(widget=forms.Textarea)
Try this
qs = blogcommment.objects.filter(post_id=obj.id)
In blogcommment model you have a reference to blogpost. So, you can easily filter comment for which blog post related to it.
qs = blogcommment.objects.filter(post=obj)
This will tell the queryset to filter all blogcomments that have the current specific blogpost as their post reference.
I was able to render the form onto the html, input data and submit it but i got a NOT NULL constraint failure. Isn't the owner assigned to its respective owners when as i have indicated in my views? i do not know what is wrong here please help!
Models
class Car(models.Model):
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
model = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now_add=False)
mileage = models.IntegerField()
open_market_value = models.DecimalField(max_digits=12, decimal_places=2)
depreciation = models.DecimalField(max_digits=10, decimal_places=2)
down_payment = models.DecimalField(max_digits=10, decimal_places=2)
road_tax = models.DecimalField(max_digits=8, decimal_places=2)
installment = models.DecimalField(max_digits=8, decimal_places=2)
objects = models.Manager()
def __str__(self):
return self.name
Views
class CarCreate(CreateView):
model = Car
fields = [
'name', 'model',
'description', 'image',
'updated', 'mileage',
'open_market_value', 'depreciation',
'down_payment', 'road_tax',
'installment']
template_name = 'cars/create_car.html'
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
HTML
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<!-- Default form contact -->
<form action="{% url 'cars:create' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form | crispy}}
<input type="submit" value="save">
</form>
<!-- Default form contact -->
{% endblock %}
Your model has a foreign key to the User model from 'django.auth'. While you are trying to save the object of 'Car' model as there was no object mentioned for the 'owner' field of the model, it is showing the error. So, you might want to explicitly mention it.
You can do something like this. Assuming that you have 'CarForm', a model form for you 'Car' model.
user = request.user
car_form = CarForm(request.POST)
if car_form.is_valid():
car = car_form.save(False)
car.owner = user
car.save()
This is most likely because owner is a required field in your model Car but you have not included it in the fields in your CreateView.