I need to add an edit button to my django app but it only redirects me to the homepage and no edit is saved.
this is my views.py code, i think that's where the issue is coming from
def editPhoto (request, pk):
photo = Photo.objects.get(id=pk)
categories = Category.objects.all()
if request.method == 'POST':
description = request.FILES.get('description')
photo.save()
return redirect ('/')
context = {'categories': categories, 'photo': photo}
return render(request, 'photos/edit.html', context)`
models.py
class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return self.name
class Photo(models.Model): category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) description = models.TextField()
def __str__(self):
return self.description`
edit.html
<div class="container"> <div class="row justify-content-center"> <div class="col">
Go Back
<form method='POST' action="" enctype="multipart/form-data">
{% csrf_token %}
<div style="height: 90vh;">
<img style="max-width: 100%; max-height: 100%;" src="{{photo.image.url}}" class="center" >
</div>
<div>
<input required name="description" class="input" value="{{photo.description}}" type="text" size="60"></input>
</div>
<div class="center">
<button type="submit" class="btn btn-primary m-3; center">Update</button>
</div>
</div>
</div>
</div>`
The problem is that you are not saving any changes in your model.
description = request.FILES.get('description')
photo.save()
this should be changed to
photo.description = request.POST.get('description')
photo.save()
The problem is You are not passing id of photo you want to edit from your html file.
in Edit.html in form action="{% url photo.id %} , and make changes if needed in urls.py file.
by doing so id would be passed to views.py which acts as pk.
Related
I am new at Django I want some helps. Basically,I want from users that they can select multiple images and save it, but I got like this and I don't know how to do it. I want to display the images and user can select one of them.
please help me.
models.py
class Images(models.Model):
product_image=models.ImageField(upload_to='media',null=True, blank=True)
def __str__(self):
return "{}".format (self.product_image)
class user_select(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
product_image=models.ForeignKey(Images, on_delete=models.CASCADE)
def __str__(self):
return "{}".format (self.name)
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = user_select
fields = '__all__'
views.py
def home(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'home.html', {'form':form})
home.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container mt-5">
<div class="row mt-5 mr-5">
<div class="col-md-8 mt-5">
<div class="card border border-secondary mt-5">
<div class="col-md-8 mt-5" align='center'>
<form method="POST" action="" >
{% csrf_token %}
<div class="col-md-8">
{{ form|crispy }}
</div>
</form>
<button type="submit" class="btn btn-success mt-5 mb-5">Place Order</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
enter image description here
Good morning guys, I have a problem with a form.
My code:
models.py
class AnagraficaGenerale(models.Model):
ragionesociale = models.CharField(max_length=40, null=True, blank=True)
cf = models.CharField(max_length=40, null=True, blank=True)
piva = models.CharField(max_length=40, null=True, blank=True)
forms.py
class AnagraficaGeneraleForm(forms.ModelForm):
class Meta:
model = AnagraficaGenerale
fields = '__all__'
views.py
#login_required
def anagrafica_new(request):
if request.method == "POST":
form = AnagraficaGeneraleForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('anagrafica_list')
else:
form = AnagraficaGeneraleForm()
return render(request, 'Anagrafiche/anagrafica_new.html', {'form': form})
html
{% extends 'FBIsystem/basenobar.html' %}
{%load staticfiles %}
{% block content %}
<div id="page-wrapper">
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
Nuova Anagrafica
</h3>
<form method="POST" class="form-horizontal bordered-row">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
<label class="col-sm-2 control-label" > Ragione Sociale:</label>
<div class="col-sm-6">
{{ form.ragionesociale }}
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</form>
</div>
</div>
</div>
{% endblock %}
Everything seems ok but not save, if I try with {{form.as_table}} it save.
I think there is a problem with custom field but I don't know how.
whats wrong?
TY
Hi guys I'm a beginner to Django and I'm trying to implement a login system into my django planner.
The error:
FieldError at /login_user/
Cannot resolve keyword 'user' into field. Choices are: description, end_time, id, start_time, title
I've tried adding the user field into my event model on model.py and migrating it but it just makes the whole application crash.
views.py
def event(request, event_id=None):
instance = Event()
if event_id:
instance = get_object_or_404(Event, pk=event_id)
else:
instance = Event()
form = EventForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('cal:calendar'))
return render(request, 'cal/event.html', {'form': form})
def login_user(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
events = Event.objects.filter(user=request.user)
login(request, user)
return render(request, 'cal/calendar.html', {'calendar': calendar})
else:
return render(request, 'cal/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'cal/login.html', {'error_message': 'Invalid login'})
return render(request, 'cal/login.html')
forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password',]
models.py
from django.contrib.auth.models import Permission, User
from django.db import models
class Event(models.Model):
#user = models.ForeignKey(User, default=1)
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
#property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f' {self.title} '
calendar.html
{% extends 'cal/base.html' %}
{% block title %}
Calendar
{% endblock %}
{% block content %}
<div class="clearfix">
<a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a>
<a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a>
<a class="btn btn-info right" href="{% url 'cal:event_new' %}"> New Event </a>
</div>
{{ calendar }}
{% endblock %}
login.html
{% extends 'cal/base_visitor.html' %}
{% block title %}Log In{% endblock %}
{% block login_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<h3>Log In</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form class="form-horizontal" role="form" action="{% url 'cal:login_user'%}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label col-sm-2" for="id_username">
Username:
</label>
<div class="col-sm-10">
<input id="id_username" maxlength="30" name="username" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="id_password">
Password:
</label>
<div class="col-sm-10">
<input id="id_password" maxlength="30" name="password" type="password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">
Don't have an account? Click here to register.
</div>
</div>
</div>
</div>
</div>
{% endblock %}
In your view you are filtering Event objects with the keyword user, but your event model has no field called user. If you want your event associated with a user you can add a foreignkey to your Event model:
class Event(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
#property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f' {self.title} '
Or, in your view, you can simply filter your Event objects by another keyword the choices for which your error gave you, and which are just the fields you specified in your model. So in your view you could do this:
def login_user(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
events = Event.objects.filter(title='Title you want to filter by') # This line seems to be the source of your error. You just need to filter by a keyword that exists in your model.
login(request, user)
return render(request, 'cal/calendar.html', {'calendar': calendar})
else:
return render(request, 'cal/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'cal/login.html', {'error_message': 'Invalid login'})
return render(request, 'cal/login.html')
In your models.py you missed adding a relationship for your user table. add user and do a
python manage.py makemigrations myapp
python manage.py migrate myapp
from django.contrib.auth import get_user_model
class Event(models.Model):
user = models.ForeignKey(get_user_model(), null=True)
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
#property
def get_html_url(self):
url = reverse('cal:event_edit', args=(self.id,))
return f' {self.title} '
I have a problem which I want to help me solve.
I have a "Post" with comments included but, when I comment a "Post" the comment I made in "Post 1" appears in "Post 2" and in all "Posts" and I want to link the comment to a single post, I've been looking for solutions but I have not been able to make it work.
EDIT I ADDED MY post/models.py
class Post(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
autor = models.CharField(max_length=200)
description = models.TextField()
likes = models.PositiveIntegerField(default=0)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
files = models.FileField(upload_to=upload_location, validators=
[validate_file_extension])
post_type = models.CharField(max_length=100, choices=Book_Type_Choices)
tags = TaggableManager()
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='cooments')
user = models.ForeignKey(User, unique=False)
text = models.CharField(max_length=250)
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
views.py
#login_required
def add_comment_to_post(request, pk):
post= get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post= post
comment.user = request.user
comment.save()
return redirect('post_detail', slug=post.slug)
else:
form = CommentForm()
return render(request, 'comments/add_comment_to_post.html', {'form':form})
my add_comment.html, this code fragment is included on my post_detail.html
<form action="{% url 'add_comment_to_post' pk=post.pk %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-primary" value="Comentar">
</form>
my book_detail.html
<div class="container">
<div class="row">
<div class="col-md-6 comment" style="text-align: center;">
<!-- HERE IS WHERE I INCLUDE THE add_comment.html -->
{% include 'comments/add_comment_to_post.html' %}
</div>
{% for comment in comments %}
{% if user.is_authenticated or comment.approved_comment %}
<div class="col-sm-6 col-sm-offset-1">
<div class="media-body">
<div class="well well-lg">
<div class="avatar">
<img src="{{comment.user.profile.pic.thumbnail.url}}" class="img-responsive img-circle" alt="">
</div>
<h4 class="media-heading text-uppercase reviews">{{comment.user.get_full_name}} </h4>
<ul class="media-date text-uppercase reviews list-inline">
<li>{{comment.created_date}}</li>
</ul>
<p class="media-comment">
{{comment.text}}
</p>
<a class="btn btn-info btn-circle text-uppercase" href="#" id="reply"><span class="glyphicon glyphicon-share-alt"></span> Reply</a>
<a class="btn btn-warning btn-circle text-uppercase" data-toggle="collapse" href="#replyOne"><span class="glyphicon glyphicon-comment"></span> 2 comments</a>
</div>
</div>
</div>
{% endif %}
{% empty %}
<p>No hay comentarios que mostrar :(</p>
{% endfor %}
</div>
</div>
Any idea how I can make comments work? Thanks!
In the comment model try to remove the unique=False
Change
class Comment(models.Model):
user = models.ForeignKey(User, unique=False)
to
class Comment(models.Model):
user = models.ForeignKey(User) # remove unique=False
Do the above and take it from there
I've tried several of methods on how to retrieve an image from a model with no luck, this is where I'm at so far. I'd like to have the image show and when the user clicks on it, it opens a modal showing a projects detail.
models.py
class Project(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
client = models.CharField(max_length=200)
date = models.DateField(timezone.now())
service = models.CharField(max_length=200)
info = models.TextField()
photo = models.ImageField(upload_to='ports/static/img/',
default='ports/static/img/port_photo.png',
height_field='photo_height',
width_field='photo_width',)
photo_height = models.PositiveIntegerField(blank=True, default=900)
photo_width = models.PositiveIntegerField(blank=True, default=650)
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
index.html
<section id="portfolio">
{% for project in projects %}
<div class="row">
<div class="col-lg-12 text-center">
<h2>Portfolio</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-sm-4 portfolio-item">
<a href="#portfolioModal1" class="portfolio-link" data-toggle="modal">
<div class="caption">
<div class="caption-content">
<i class="fa fa-search-plus fa-3x"></i>
</div>
</div>
<img src="{{ projects.photo.url }}" class="img-responsive" alt="">
</a>
</div>
</div>
</div>
{% endfor %}
</section>
views.py
from django.shortcuts import render
from .forms import ContactForm
from django.utils import timezone
from .models import Project
# Create your views here.
def index(request):
form_class = ContactForm
projects = Project.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'ports/index.html', {'form': form_class, 'projects': projects})
Look at your img tag. In the src attribute, you are using {{ projects.photo.url }}. So, you cannot get image from a queryset, you can only do so from an object of Project model. Use {{ project.photo.url }}