NOT NULL constraint failed: complaint_complaint.resident_id - python

I am writing an app in which people can submit their complaints related to some issues.
After the form is submitted, it is supposed to redirect to the page where the details of the complaint are mentioned like area of the complaint, title, description etc.
But after the form is submitted, it throws IntegrityError.
I read about it and went through some of the solutions:
Someone suggested that I delete some past migrations and run them again. I cleared the migrations, ran them again and made some posts through the admin but it is throwing the same error.
Some posts suggest that null=True, blank=True should be added but I do not understand where they should be added in my case. I also don't want to add null=True, blank=True because I don't want any field to be left blank.
Below is my models.py:
from django.db import models
from django.urls import reverse
# Create your models here.
class Complaint(models.Model):
""" Details of the complaint """
resident = models.ForeignKey('auth.User', on_delete=models.CASCADE)
AREA = [('PL', 'Plumbing'), ('EL', 'Electricity'), ('CP', 'Carpenter'), ('CO', 'Construction'), ('DS', 'Disputes'), ('OT', 'Other'),]
matter = models.CharField(max_length=2, choices=AREA)
title = models.CharField(max_length=200)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('comp_detail', args=[str(self.id)])
Below is my urls.py which I created in my 'complaint':
Note - I used class-based views in my views.py
from django.urls import path
from .views import CompListView, CompDetailView, CompCreateView
urlpatterns = [
path('comp/new/', CompCreateView.as_view(), name='comp_new'),
path('comp/<int:pk>/', CompDetailView.as_view(), name='comp_detail'),
path('', CompListView.as_view(), name='home'),
]
Some help will be appreciated.

Related

Page not found (404) in Django Output

Urls.py:
urlpatterns = [
path("", views.index, name="blogHome"),
path("blogpost/<int:id>/", views.blogpost, name="blogHome")
]
Views.py:
django.shortcuts import render
from .models import Blogpost
# Create your views here.
def index(request):
return render(request, 'blog/index.html')
def blogpost(request, id):
post.Blogpost.objects.filter(post_id = id)[0]
print(post)
return render(request, 'blog/blogpost.html')
Models.py:
from django.db import models
class Blogpost(models.Model):
post_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
head0 = models.CharField(max_length=500, default="")
chead0 = models.CharField(max_length=10000, default="")
head1 = models.CharField(max_length=500, default="")
chead1 = models.CharField(max_length=10000, default="")
head2 = models.CharField(max_length=500, default="")
chead2 = models.CharField(max_length=10000, default="")
pub_date = models.DateField()
thumbnail = models.ImageField(upload_to='blog/images', default="")
def __str__(self):
return self.title
Error
Error in cmd
Not Found: /blog/blogpost
[21/Jun/2022 12:29:33] "GET /blog/blogpost HTTP/1.1" 404 2678
The current error means Django doesn't find anything with the route blog/blogpost, it is because you have also defined an id to be pass in route, so kindly try http....blog/blogpost/1/ any id you can give.
Also, id is generally used to get a single object, and you are doing filtering on it. I think you should use get_object_or_404 if you want to retrieve single object.
As #lvanStarostin stated in the above comment that URL patterns should also have unique names. You should change one of the names.
Note: Models are classes of python so they must be written in PascalCase, so you may change your model name to BlogPost from Blogpost.

Page not found (404) Request Method: GET ....... the current path, blog/blogpost, didn't match any of these

Hi i am trying to make blog website but while i fetch model with blogpost function in views.py its shows error that 404 page not found like ||Using the URLconf defined in mac.urls, Django tried these URL patterns, in this order: admin/ shop/ blog/ [name='BlogHome'] blog The current path, blog/blogpost, didn't match any of these. ||
-until i don't create model it works fine but after creating model and trying to fetch articles through post_id it throws error as page not found!
-what am i missing?
-Here is the codes i am using.
code of blog/urls.py ->
from django.urls import path
from . import views
urlpatterns = [
path(" ", views.index, name="ShopHome"),
path("blogpost/<int:id>/", views.blogpost, name="blogpost")]
code of blog/Views.py ->
from django.shortcuts import render
from .models import Blog
# Create your views here.
from django.http import HttpResponse
def index(request):
return render(request, 'blog/index.html')
def blogpost(request,id):
post= Blog.objects.filter (post_id=id)[0]
print(post)
return render(request, 'blog/blogpost.html',{'post':post})
code of blog/adminpy ->
from django.contrib import admin
from .models import Blog
admin.site.register(Blog)
code of blog/models.py ->
from django.db import models
# Create your models here.
class Blog(models.Model):
post_id = models.AutoField(primary_key= True)
title = models.CharField(max_length=50)
title0 = models.CharField(max_length=500,default='')
title1= models.CharField(max_length=500,default='')
title2= models.CharField(max_length=500,default='')
Content_title= models.CharField(max_length=500,default='')
Content_title0= models.CharField(max_length=500,default='')
Content_title1= models.CharField(max_length=500,default='')
Content_title2= models.CharField(max_length=500,default='')
pub_date = models.DateField()
image = models.ImageField(upload_to='shop/images', default="")
def __str__(self):
return self.title
You are passing an /<int:id>/ (btw always include the last trailing slash in your urls /) but your path says /blog/blogpost with a str parameter where it should be an int representing the id of an existing Blogpost instance.

Django class based view: passing additional information to the next view

I'm very new to Django and a bit overwhelmed by the documentation. I think my problem is pretty simple but everything i've found just confused me more.
I am building a little news app with a model NewsItem:
from django.db import models
from django.utils import timezone
# Create your models here.
class NewsItem(models.Model):
title = models.CharField(max_length=50)
newsText = models.TextField()
dateEntered = models.DateTimeField('date entered')
datePublished = models.DateTimeField('date published', blank=True, null=True)
user = models.CharField(max_length=30) #temporary field. will be changed to user foreign key
def __str__(self):
return self.title
def publish(self):
if (self.datePublished == None):
self.datePublished = timezone.now()
def published(self):
return self.datePublished != None
two views (technically 3) index and detail
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic
from .models import NewsItem
# Create your views here.
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latestNewsList'
def get_queryset(self):
return NewsItem.objects.order_by('-datePublished')[:5]
#todo
class DetailView(generic.DetailView):
model = NewsItem
template_name = 'news/detail.html'
def publish(request, itemId):
newsItem = get_object_or_404(NewsItem, pk=itemId)
newsItem.publish()
newsItem.save()
return HttpResponseRedirect(reverse('news:detail', args=(newsItem.id,)))
and an urlconf like this
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:itemId>/publish', views.publish, name='publish'),
]
In the detail view i have a link Publish which just triggers the function views.publish. This view is supposed to redirect back to the detail view.
What i'm trying to do now is to display a little message (like article successfully published) in detail view when it was redirected by the publish view. But i have no idea what would be a good aproach
I could just render the details template in the publish view, but then it would still say news/publish in the URL instead of news/detail
Thanks in advance for your help
Have a look at the messages framework. You could add a success message before redirecting, which will be displayed on the next page.
from django.shortcuts import redirect
from django.contrib import messages
def publish(request, itemId):
newsItem = get_object_or_404(NewsItem, pk=itemId)
newsItem.publish()
newsItem.save()
messages.success(request, "The post has been published")
return redirect('news:detail', newsItem.id)
Note that I've simplified the return statement to use redirect(...) instead of HttpResponseRedirect(reverse(...)).

how to display information entered by a user into a django model in the User profile

I'm kind of new to django, I'm working on a project currently. It is a website where people can look for houses to rent. Users will be able to create accounts, search for houses to rent and create listings about the houses they want to rent out.
I created a model to save all the information about houses that users want to rent out. I need to filter this information and display each user's listing on their profile. I have searched online but no solution yet.
Really need help.
models.py
from django.db import models
from django.contrib.auth.models import User
class Myhouses(models.Model):
Available = 'A'
Not_Available = 'NA'
Availability = (
(Available, 'Available'),
(Not_Available, 'Not_Available'),
)
name_of_accomodation = models.CharField(max_length=200)
type_of_room = models.CharField(max_length=200)
house_rent = models.IntegerField()
availability = models.CharField(max_length=2, choices=Availability, default=Available,)
location = models.CharField(max_length=200)
nearest_institution = models.CharField(max_length=200)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='profile_image')
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='author')
def __str__(self):
return self.name_of_accomodation
view.py
class ListingByUser(LoginRequiredMixin, generic.ListView):
model = Myhouses
template_name ='houses/ListingByUser.html'
paginate_by = 10
def get_queryset(self):
return Myhouses.objects.filter(author=self.request.user)
urls.py
from django.conf.urls import url, include
from . import views
from django.contrib.auth.models import User
urlpatterns = [
url(r'^addlisting/$', views.addlisting, name='addlisting'),
url(r'^mylisting/', views.ListingByUser.as_view(), name='ListingByUser')
]
Template
<ul>
{% for houses in myhouses_list %}
<li>{{ houses.name_of_accomodation }}</li>
{%endfor %}
</ul>
Taking a quick view of your code, there is something that stuck me on your ListingByUser view: you override the get method only to set some attributes that are normaly defined as class attributes. That also could be preventing your view to actually get your models out of the database (via calling the get_queryset method) and rendering a proper response.
Edit
I found there's also a problem linking your template to the response the ListingByUser view is rendering. As far as I know, Django views doesn't look into the variable template_name for getting the response's template. But it does call a method get_template_names which returns a list of template names given as strings.
Try to modify it in this way:
views.py
class ListingByUser(LoginRequiredMixin, generic.ListView):
model = Myhouses
template_name ='myhouses/listing_by_user.html'
paginate_by = 10
def get_queryset(self):
return Myhouses.objects.filter(author=self.request.user)
def get_template_names(self):
return [self.template_name]

To show data in Django admin page which user send

Question: How to show data in Django admin page which user send by forms\fields from webpage?!
P.S. I am just beginner in Django so I think my question has easy solution but right now I dont know how to make it. Don`t judge me harshly please. I will be happy for any example or article about it. =)
forms.py
class TicketForms(forms.Form):
name = forms.CharField(max_length=120, required=True)
email = forms.EmailField(required=False)
department = forms.CharField(max_length=120, required=True)
room = forms.CharField(max_length=100, required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
models.py
from django.db import models
class Ticket(models.Model):
name = models.TextField(null=True, blank=True)
email = models.TextField(null=True, blank=True)
department = models.TextField(null=True, blank=True)
room = models.TextField(null=True, blank=True) # TextField cause room can be 408A as example
comment = models.TextField(null=True, blank=True)
def __str__(self): # __unicode__ on Python 2.7
return self.name
admin.py
from django.contrib import admin
from .models import Ticket
# Register your models here.
class Admin(admin.ModelAdmin):
class Meta:
model = Ticket
admin.site.register(Ticket, Admin)
Since you have empty admin page, this means you did not registered your models yet in the admin interface. Simply go to app each in the same directory as models.py you should find admin.py and if not just create it and add the following:
1.
admin.py
from django.contrib import admin
from ticket.models import Ticket
admin.site.register(Ticket)
2.then add your app to settings.py:
INSTALLED_APPS = (
...
'tickets',
)
3.apply migrations
python manage.py makemigrations
python manage.py migrate
Now that you model is ready in views.py:
def home(request):
form = TicketForms(request.POST)
# validate your form
if form.is_valid():
Ticket.objects.create(**form.cleaned_data)
# return success url
else:
context = {'form': form}
render(request, 'ticket.html', context)
Check you admin again and you will find the saved data displayed.
And since you are new to Django I will recommend you to go through this official django tutoriel with 7 parts.

Categories

Resources