I have the codes below in my views and models. But I want a situation in which a user cannot submit the same form twice. once a user submits the form he or she can only see a preview of what has been submitted but is unable to submit the same form.
Any help would be highly appreciated. Thanks
#views.py
def index(request):
form = MembershipForm()
if request.method == 'POST':
form = MembershipForm(request.POST)
if form.is_valid():
form.save()
return redirect("home")
return render(request, 'index.html', {'form': form)
#models.py
class Membership(models.Model):
fullname = models.CharField(max_length=500, blank=True, null=True)
location = models.IntegerField(default='0',blank=True, null=True)
department = models.IntegerField(default='0',blank=True, null=True)
last_update = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return str(self.fullname)
Related
Comments are saving to DB but not linking to Post, unless I manually go to Admin page and link.
MODELS.PY
class Post(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=50)
info = models.TextField(max_length=2000)
slug = models.SlugField(null=True, unique=True, max_length=300)
created = models.DateField(null=True, auto_now_add=True)
approved = models.BooleanField(default=False, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=50, verbose_name="Name")
comment = models.TextField(max_length=500, verbose_name="Comment")
created = models.DateField(null=True, auto_now_add=True)
approved = models.BooleanField(default=False, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
FORMS.PY
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name','comment']
VIEWS.PY
def create_comment(request, slug):
form = CommentForm()
post = Post.objects.get(slug=slug)
if request.method == "POST":
form = CommentForm(request.POST)
comment = form.save()
comment.post = post
comment.save()
messages.success(request, 'Your comment was successfully submitted!')
return render(request, 'post.html', {'post': post, 'form':form})
return render(request, 'post.html', {'post': post, 'form':form})
From Admin page I can add comment and manually link to post, but from frontend form, comment is created and saved to DB but not linked to any post. Any idea what I'm doing incorrectly?
Where does this review object instance come from, woudn't it be the comment object?
Also, check if the the form is valid:
def create_comment(request, slug):
form = CommentForm()
post = Post.objects.get(slug=slug)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save()
comment.post = post
comment.save()
messages.success(request, 'Your comment was successfully submitted!')
return render(request, 'post.html', {'post': post, 'form':form})
return render(request, 'post.html', {'post': post, 'form':form})
I tried to make a creation form for vacancy on my job search site, but i faced with problem. I have User model, company model and vacancy model. They are inherited by foreignkeys. And the problem is that user can use all companies for creation a vacancy instead of created by this user companies(User can create several companies). I tried to change creation form and view by filtering, but it didn't work out for me. I am new at django and i dint find anything to resolve my problem.
Model of company:
class Company(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(('Title of Shop'), blank=True, max_length=255)
info = models.TextField(('Information about Shop'), null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.title)
Model of vacancy:
class Vacancies(models.Model):
title = models.CharField(('Title of Vacancy'), blank=True, max_length=255)
city = models.ForeignKey(City, on_delete=models.CASCADE, default='363')
description = models.TextField(('Information about Vacancy'), null=True, blank=True)
employer = models.ForeignKey(Company, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-updated', '-created']
def __str__(self):
return str(self.title)
Create vacancy view:
#login_required(login_url='login')
def createVacancy(request):
form = VacanciesForm()
cities = City.objects.all()
if request.method == 'POST':
form = VacanciesForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form, 'cities': cities}
return render(request, 'vacancy_form.html', context)
Vacancy form:
class VacanciesForm(ModelForm):
class Meta:
model = Vacancies
fields = '__all__'
What do I need to change to get the correct display of companies in the vacancy
Try this:
#login_required(login_url='login')
def create_vacancy(request):
user = request.user
cities = City.objects.all()
if request.method == 'POST':
form = VacanciesForm(data=request.POST, instance=user)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form, 'cities': cities}
return render(request, 'vacancy_form.html', context)
Also you can use in view:
def create_vacancy(request, logined_user_id):
vacancies = Vacancies.objects.filter(owner=logined_user_id)
...
And you can try some logic here:
class VacanciesForm(ModelForm):
vacancies = [some_logic]
class Meta:
model = Vacancies
fields = '__all__'
Finally, you can read docs:
modelforms
This work:
views
def createVacancy(request):
cities = City.objects.all()
form = VacanciesForm(data=request.POST, request=request)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form, 'cities': cities,}
return render(request, 'vacancy_form.html', context)
forms
class VacanciesForm(ModelForm, forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(VacanciesForm, self).__init__(*args, **kwargs)
self.fields['employer'].queryset = EmployerCard.objects.filter(owner=self.request.user)
class Meta:
model = Vacancies
fields = '__all__'
i am trying to create a logic where users can review and rate a course, the logic in my views.py looks fine but i keep gettting this errror NOT NULL constraint failed: course_courserating.user_id i removed some null=True from my models but it still keeps showing the error.
views.py
if request.method == "POST":
form = CourseRatingForm(request.POST)
if form.is_valid():
rating_form = form.save(commit=False)
user = request.user
course = course
rating_form.save()
messages.success(request, f'You review was sent successfully!')
return redirect("course:course-detail", course.slug)
else:
form = CourseRatingForm
models.py
class Course(models.Model):
course_title = models.CharField(max_length=10000)
slug = models.SlugField(unique=True)
class CourseRating(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
rating = models.CharField(max_length=1000, choices=USER_COURSE_RATING)
review = models.TextField()
date = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
def __str__(self):
return f"{self.course.course_title} - {self.rating}"
You need to assign it to the CourseRating object, so:
if request.method == 'POST':
form = CourseRatingForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.instance.course = course
form.save()
messages.success(request, f'You review was sent successfully!')
return redirect('course:course-detail', course.slug)
else:
form = CourseRatingForm()
I have a model in models.py; like this:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='static/images/account/avatar', default='/static/images/default-avatar.png')
bio = models.CharField(max_length=300, blank=True, null=True)
def __str__(self):
return '#' + self.user.username
in views.py i want to check if a filed (i mean avatar) from Profile model has changed or not
in views.py:
def editProfile(request):
user = request.user.profile
form = AuthorForm(instance=user)
if request.method == 'POST':
if ...:
os.remove(request.user.profile.avatar.path)
form = AuthorForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.save()
return redirect('dashboard')
context = {'form': form}
return render(request, 'account/edit.html', context)
In fact, I want the default image (or any other photo) not to be deleted if the user does not change the avatar field.
The fields that change are listed in the .changed_data attribute [Django-doc]. You thus can check if the avatar has changed with:
if 'avatar' in form.changed_data:
os.remove(request.user.profile.avatar.path)
I am getting an error when I try to update a record in Django using a form. I get an error that a record with that number already exists. Below is my model and view. This is really driving me nuts. I though that Django would just update the record instead of trying to write a new record.
class Report(models.Model):
report_number = models.CharField(max_length=4, unique=True)
detected = models.CharField(max_length=40)
computer_name = models.CharField(max_length=40)
username = models.CharField(max_length=15)
cab_date_time = models.CharField(max_length=40)
collector = models.CharField(max_length=40)
addresses = models.TextField()
fault = models.CharField(max_length=40)
known_malware = models.TextField(default='No')
collected_files = models.TextField(default='None')
registry_keys = models.TextField()
service_number = models.CharField(max_length=15, blank=True)
notes = models.TextField(blank=True)
sample_requested = models.CharField(max_length=4, blank=True)
action = models.CharField(max_length=35, blank=True)
And View
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
form = ReportForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
return render(request, 'reports/report.html', {'form': form})
Here is the Form defination
from django.forms import ModelForm
from reports.models import Report
class ReportForm(ModelForm):
class Meta:
model = Report
exclude = ('moderator',)
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
if request.method == 'POST':
form = ReportForm(request.POST, instance=instance)
if form.is_valid():
form.save(force_update=True)
return HttpResponseRedirect('/')
else:
form = ReportForm(instance=instance)
return render(request, 'reports/report.html', {'form': form})