NOT NULL constraint failed: issue_tracker_label.project_id - python

I am trying to create a 'Label'. Basically, you click on 'label' button, and it will show title and content under. I am using POST method. But when I click on 'submit', it gave me this error:
IntegrityError at /project/1/issue/2/label/
NOT NULL constraint failed: issue_tracker_label.project_id
Btw, I am using crispy form and I did do makemigrations and migrate after I modified my model.py. Not sure why I still get this error.
view.py
#csrf_exempt
def label_create(request, project_id,issue_id):
issue = get_object_or_404(Issue, id=issue_id)
project = Project.objects.get(id=project_id)
if request.method == 'POST':
form = LabelForm(request.POST)
if form.is_valid():
label = form.save(commit=False)
label.issue = issue
label.save()
return redirect('project:issue_tracker:issue_detail', project_id=project.id, issue_id=issue.id)
else:
form = LabelForm()
template = 'issue_tracker/issue/label.html'
context = {'form': form, 'project': project}
return render(request, template, context)
model.py
class Label(models.Model):
issue = models.ForeignKey(Issue, related_name='issue_label', on_delete=models.CASCADE)
project = models.ForeignKey(Project, related_name='project_label', on_delete=models.CASCADE)
title=models.CharField(max_length=20,default='Debug')
color=models.CharField(max_length=20,default='red')
def __str__(self):
return self.title
form.py
class LabelForm(forms.ModelForm):
class Meta:
model = Label
fields = ('title','color',)

Try adding the project in your object save:
views.py
#csrf_exempt
def label_create(request, project_id,issue_id):
issue = get_object_or_404(Issue, id=issue_id)
project = Project.objects.get(id=project_id)
if request.method == 'POST':
form = LabelForm(request.POST)
if form.is_valid():
label = form.save(commit=False)
label.issue = issue
label.project = project
label.save()
return redirect('project:issue_tracker:issue_detail', project_id=project.id, issue_id=issue.id)
else:
form = LabelForm()
template = 'issue_tracker/issue/label.html'
context = {'form': form, 'project': project}
return render(request, template, context)
Notice the label.project = project

Related

Form is not being saved in Django admin page

I have faced a problem in my Django project where my form is not being saved as a new listing in my model(listing) and is not even showing on Django's admin page.
my models.py :
class listing(models.Model):
title = models.CharField(max_length=64)
describtion = models.CharField(max_length=300)
bid = models.FloatField()
category = models.ForeignKey(categories, default=1, verbose_name="Category",
on_delete=models.SET_DEFAULT)
user = models.ForeignKey(User,default='', verbose_name="User", on_delete=models.SET_DEFAULT)
image = models.CharField(max_length=400)
def __str__(self):
return f"{self.title} "
create a new listing form :
class create(ModelForm):
class Meta:
model = listing
fields = [ 'title', 'describtion','bid','category','image']
views.py :
def CreateListing(request):
user = request.user
if request.method == "POST":
form = create(request.POST, instance=user)
if form.is_valid():
new_listing = form.save()
new_listing.user = request.user
new_listing.save()
return render(request, "auctions/listing.html")
else:
return render(request, "auctions/Create.html",{
"form": create
})
Ps: I have no problem with my urls.py
You need to set the user before you can save this to the database:
def CreateListing(request):
user = request.user
if request.method == "POST":
form = create(request.POST, instance=user)
if form.is_valid():
form.instance.user = user
form.save()
return redirect('%name-of-some-view')
else:
form = create(instance=user)
return render(request, "auctions/Create.html",{
'form': form
})
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

rendered form isnt saving any input into database, why isnt it working?

I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ?
def addContact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form = Contact(
# full_name = request.POST ('fullname'),
# relationship = request.POST ('relationship'),
# email = request.POST ('email'),
# phone_number = request.POST ('phone-number'),
# address = request.POST ('address'),
# )
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
def contactProfile(request,pk):
contact = Contact.objects.get(id=pk)
return render(request, 'contact/contact-profile.html', {'contact': contact})
In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database.
forms.py:
from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
models.py:
from django.db import models
# Create your models here.
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number =models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
It seems that your form is not valid and it redirects always to contact.
You should to use redirect only if the form is valid. Otherwise you will never see which errors your form contains.
Try the following code:
def addContact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
else:
form = ContactForm()
context = {'form': form}
return render(request, 'contact/new.html', context)

TypeError at /project/create 'Account' object is not iterable

I am facing a problem. I can not assign user with project using many to many field
here is the details
here is my model.py
from django.conf import settings
from django.db import models
from workingSkills.models import Domain,Environment,ToolsAndTechnology
class Project(models.Model):
profile_of = models.ManyToManyField(settings.AUTH_USER_MODEL, null=False)
project_title = models.CharField(max_length=100)
domain = models.ManyToManyField(Domain)
environment = models.ManyToManyField(Environment)
tools_and_technology = models.ManyToManyField(ToolsAndTechnology)
here is views.py
#login_required(login_url= 'login')
def createProject(request):
form = createProjectForm()
print(request.user)
if request.method == 'POST':
form = createProjectForm(data=request.POST)
if form.is_valid():
user = Account.objects.filter(request.user)
instance = form.save(commit=False)
#instance.save()
instance.profile_of.set(user)
instance.save()
return HttpResponseRedirect('createprofile')
form = createProjectForm
context = {'form': form}
return render(request, 'project/create_project.html', context)
here is error image
change this like this you have to specify for which column you want to filter
from:
Account.objects.filter(request.user)
to:
Account.objects.filter(user=request.user)
You have made a typo mistake in that query set
Change of queryset 'set' To 'add' in the line

How do I save m2m field session from a form to another?

I'm doing a multi step form where everything is saved at the end. In my models I have a m2m checkbox field and I'm using django Sessions to grab the forms datas to show it on the final step.
The issue is that the m2m field (checkboxes) is not saved when I submit the final form.
Here is my views file :
views.py
def step1(request):
initial={'name': request.session.get('name', None), 'checkbox': request.session.get('checkbox', (False,))} #cookies
form = FormOneForm(request.POST or None, initial=initial)
if request.method == 'POST':
if form.is_valid():
request.session['name'] = form.cleaned_data['name']
request.session['checkbox'] = form.cleaned_data.get('checkbox')
return HttpResponseRedirect(reverse('step2'))
return render(request, 'step1.html', {'form': form})
def step2(request):
form = FormTwoForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
formtwo = form.save(commit=False)
formone2 = FormOne.objects.create(checkbox=request.session.get('checkbox')) #error is here
formone = FormOne.objects.create(name=request.session['name'])
formtwo.owner = formone
formtwo.save()
formone2.save_m2m()
return HttpResponseRedirect(reverse('step3'))
return render(request, 'step2.html', {'form': form})
models.py
class Font(models.Model):
font_name = models.CharField(max_length=100)
font_family = models.CharField(max_length=100)
font_link = models.CharField(max_length=100)
...
class FormOne(models.Model):
name = models.CharField(max_length=40)
checkbox = models.ManyToManyField(Font, blank=True)
...
class FormTwo(models.Model):
owner = models.ForeignKey(FormOne)
name = models.CharField(max_length=40)
...
this code gives me this error :
'checkbox' is an invalid keyword argument for this function
How can I achieve what I am trying to realise ?
Try to save object first:
formone2 = FormOne.objects.create(name=request.session['name'])
formone2.checkbox.add(request.session.get('checkbox')
The problem is that you need to save object before use Many-to-many relations. See docs:
You can’t associate it with a Publication until it’s been saved

Django Delete Objects

I'm receiving this error "TemplateDoesNotExist at /bookmarks/list/1/delete_link/" when attempting to delete an object in Django.
In forms.py I have:
class DeleteForm(forms.ModelForm):
class Meta:
model = Link
fields = []
In views.py:
def delete_link(request, link_id):
link_to_delete = get_object_or_404(Link, id=link_id)
context_dict = {'link_id': link_id}
if request.method == 'POST':
form = DeleteForm(request.POST, instance=link_to_delete)
if form.is_valid():
link_to_delete.delete()
return HttpResponseRedirect('bookmarks/list')
else:
form = DeleteForm(instance = link_to_delete)
template_vars = {'form': form}
return render_to_response(request, 'bookmarks/delete_link.html', template_vars)
urls.py:
url(r'^list/(?P<link_id>\w+)/delete_link/$', views.delete_link, name='delete_link'),
embedded in list.html (template for displaying a list of links, I want delete options next to each):
<a href='/bookmarks/list/{{ link.pk }}/delete_link/'> Delete</a>
Here:
return render_to_response(request, 'bookmarks/delete_link.html', template_vars)
Django can't find your template. do you have it in your TEMPLATES_DIRS?

Categories

Resources