Trying to apply CRUD functionality to python project - python

So I'm building a real estate website for school. And one of the requirements is to have CRUD functionality on the front end for admins. But before i knew that i created in the backend admin page, all the fields that need to be filled before a listing can be published.
But now i need to display all of the fields i created on the backend admin page to show on the front end. I've tried writing the code to display it but its not really working. Im only seeing the submit button.
Im new to coding and stack overflow, so please do let me know if you need anything els from me or if ive done something wrong.
these are the fields that should be filled and show up in the front end for realtors to publish, edit and remove a listing:
models.py
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zipcode = models.CharField(max_length=20)
description = models.TextField(blank=True)
price = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
garage = models.IntegerField(default=0)
sqft = models.IntegerField()
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')
photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
is_published = models.BooleanField(default=True)
list_date = models.DateTimeField(default=datetime.now, blank=True)
This is the code that Ive tried writing to display the code above on the front end so it can be edited.
forms.py
from django.forms import ModelForm
from listings.models import Listing
class listingForm():
class Meta:
model = Listing
fields = '__all__'
create_listing.html
{% extends 'base.html' %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" name="submit">
</form>
{% endblock %}
views.py
def createListing(request):
form = listingForm()
context = {'form': form}
return render(request, 'accounts/create_listing.html')

You didn't pass in the context to the render function, the code should look like this:
def createListing(request):
form = listingForm()
context = {'form': form}
return render(request,'accounts/create_listing.html', context)
Also a suggestion for your code is optimising the photos for your Listing model, here is a good material to watch: https://youtu.be/-0nYBqY9i5w

Related

Django- How do I get the content of a model thats related to another?

So i'm creating a to-do app. How do I view the tasks linked to the board? Like I understand that the board needs to be the foreign key to task.
Here is my code so far:
Models.py
class Board(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Board")
name = models.CharField(max_length=200)
class Task(models.Model):
board = models.ForeignKey(Board, on_delete=models.CASCADE)
admin = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.CharField(max_length=300)
complete = models.BooleanField(default=False)
assigned_to = models.CharField(max_length=30)
views.py
def board_post_detail(request, board_id):
obj = get_object_or_404(Board, id=board_id)
context = {"object": obj}
return render(request, 'boards/board_post_detail.html', context)
board_post_detail.html
{% block content %}
<h1>{{ object.name}}</h1>
<p>Created by {{object.admin.username }}</p>
{% endblock %}
If you want to find what tasks correspond to a specific instance of the Board class, then you should just make a query filtering by the instance:
obj = get_object_or_404(Board, id=board_id)
Task.objects.filter(board=obj)

When I submit this form, neither data is saved onto database nor giving any error in my django project

models.py
here is my model
class Load_post(models.Model):
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False , blank=False , unique=True)
receiver_name = models.CharField(max_length=150)
sending_item = models.CharField(max_length=150)
weight = models.CharField(max_length=150)
metric_unit = models.CharField(max_length=30, default='SOME STRING')
quantity = models.PositiveIntegerField(default=1)
requested_shiiping_price = models.PositiveIntegerField()
pick_up_time = models.DateField()
drop_time = models.DateField()
paid_by = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now=True)
published_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def publish(self):
self.published_date = timezone.now()
self.save()
def get_absolute_url(self):
return reverse('local')
class Meta:
ordering = ["-created_at"]
unique_together = ["sender_name", "receiver_name"]
please check the phone number
forms.py
this is form.py
class Loader_post_form(forms.ModelForm):
phone_number = PhoneNumberField()
metric_unit = forms.ChoiceField(choices=UNIT, required=True)
class Meta:
model = Load_post
fields = ("pick_up_station", "destination_station",
"sender_name", "phone_number", "receiver_name",
"sending_item","image_of_load","weight","metric_unit",
"quantity","requested_shiiping_price","pick_up_time",
"drop_time","paid_by")
views.py
This is my views.py
absolute URL used in models already
class Loader_post_view(CreateView, LoginRequiredMixin):
login_url = 'Driver/login/'
form_class = forms.Loader_post_form
model = Loader_Signup
template_name = "Driver/post.html"
def form_valid(self,form):
form.instance.user = self.request.user
form.save()
return super(Loader_post_view,self).form_valid(form)
post.html
this is html page (template)
{% extends "Driver/base.html" %}
{% block content %}
<h1>create a post</h1>
{% csrf_token %}
{{form}}
<button type="submit">submit</button>
{% endblock content %}
this is html code
how to add it to the database
and I cannot see any error in my forms
thank you
am working on driver and client-side project
From what I see you html template cannot submit the form because you ae missing the <form> tags - if you do not have them hidden in your base.html.
Your html template should be something like this:
{% extends "Driver/base.html" %}
{% block content %}
<h1>create a post</h1>
<form method="POST">
{% csrf_token %}
{{form}}
<button type="submit">submit</button>
</form>
{% endblock content %}
The {{ form }} renders the form with all the inputs but does not create the tags needed for html forms.
In addition there are some other errors in the code you posted.
In your view the model you defined is called Loader_Signup, however the model you posted is Load_post. Either you posted the wrong model or you declared the wrong model in your view.
In your form one field is called image_of_load, however, this field is not part of you model.
In your model you have got a field called phone_number, you are defining a field with the same name in your form. The field in your form has got no connection to your model so take it out.
Unfortunately you are not providing any details about your PhoneNumberField so this cannot be checked.

One field (ManyToMany) in a Django ModelForm is not saving to database

My app is project management tool where users can add, edit, and view Projects. Projects have titles, summaries, and authors (users). Users have ManyToMany relationships with Projects.
Adding new Projects was working fine until I added an edit project view. I can still create a new Project or edit an existing one, and the new title and summary get saved to the database, but the selected authors do not get saved. Note that I can still go into the shell and add authors to a project manually.
Here are the Project and User models:
class MyUser(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
bank_id = models.CharField("researcher's four-letter bank id", null=True, max_length=4, unique=True)
#division = models.CharField(max_length=30, blank = True)
department = models.CharField(max_length=3, choices=DEPARTMENTS)
job_title = models.CharField("job title", max_length=30, choices=JOB_TITLES)
citations = models.IntegerField(null=True, blank=True)
institution = models.CharField(max_length=30, choices=DEPARTMENTS, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
#history = HistoricalRecords()
REQUIRED_FIELDS = ['email']
USERNAME_FIELD = 'username'
class Project(models.Model):
title = models.TextField('Title')
summary = models.TextField('Summary', default=DEFAULT_TEXT)
authors = models.ManyToManyField(MyUser)
internal_status = models.CharField('Internal Status', max_length = 20, choices = INTERNAL_STATUS,
default='wip')
external_status = models.CharField('External Status', max_length = 20, choices = EXTERNAL_STATUS,
blank=True)
mtp_goal = models.CharField(max_length = 50, choices = MTP_GOALS,
blank=True)
topics = ArrayField(models.CharField('Topics', max_length=30), size=4, null=True)
created_on = models.DateTimeField(auto_now_add=True, null=True)
updated_on = models.DateTimeField(auto_now=True, null=True)
history = HistoricalRecords()
views.py
def add_new(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.created_on = timezone.now()
project.save()
return redirect('project_profile', pk=project.pk)
else:
form = ProjectForm()
return render(request, 'add_new.html', {'form': form})
def edit_project(request, pk):
project = get_object_or_404(Project, pk=pk)
if request.method == 'POST':
form = ProjectForm(request.POST, instance=project)
if form.is_valid():
project = form.save(commit=False)
project.updated_on = timezone.now()
project.save()
return redirect('project_profile', pk=project.pk)
else:
form = ProjectForm(instance=project)
return render(request, 'edit_project.html', {'form': form})
forms.py:
from django import forms
from .models import Project, MyUser
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ('title', 'authors', 'summary')
And finally, the add_project.html page (please excuse the horrific html):
<html>
<head>
<title>ResearchTracker</title>
</head>
<body>
<div>
<nav>
About us
Login
Admin
</nav>
</div>
<h1>New project</h1><br>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
Go home
</body>
</html>
Since you use commit=False in save, you need to explicitly call save_m2m to save the many to many fields.
From the documentation:
Calling save_m2m() is only required if you use save(commit=False).
When you use a simple save() on a form, all data – including
many-to-many data – is saved without the need for any additional
method calls. For example:
You would do
project.save()
project.save_m2m()

Django reduce queries

I have two models, Post and Vote. Users can upvote and downvote posts.
models.py:
class Post(models.Model):
poster = models.ForeignKey('auth.User')
question = models.ForeignKey('self', null=True, blank=True)
post_title = models.CharField(max_length=300)
post_content = models.TextField(null=True, blank=True)
is_published = models.BooleanField(default=True)
is_locked = models.BooleanField(default=False)
is_question = models.BooleanField(default=True)
is_deleted = models.BooleanField(default=False)
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
date_modified = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.post_title
class Vote(models.Model):
user = models.ForeignKey('auth.User')
post = models.ForeignKey('Post')
vote_type = models.SmallIntegerField()#-1, 0, 1
date_voted = models.DateTimeField(
default=timezone.now)
def __str__(self):
return self.user
I use the following code in my view to return the posts to templates:
views.py:
def index(request):
posts = Post.objects.filter(created_date__lte=timezone.now(
), is_question=1, is_published=1).order_by('-created_date')
#removed the paging stuff here for simplification
return render(request, 'homepage/index.html', {'posts': posts})
This just returns the posts, but I also want to check if the current user has voted or not (and possibly the sum of the vote_type column for each post which is the total number of votes for the post).
Currently I use template tags for each post to check if the current user has voted or not. This creates a lot of queries. (Currently 50 queries with 40 duplicates).
My index.html sample code:
{% for post in posts %}
{% if post|userVotedThisPost:request.user.id == 1 %}
<img id="upvote-img" class="icons" src="{% static 'img/upvote-marked.svg' %}" alt="Upvote">
{% else %}
<img id="upvote-img" class="icons" src="{% static 'img/upvote.svg' %}" alt="Upvote">
{% endif %}
{% endfor %}
Is there any way to query everything in the views.py and then in the template I could check like this: (if post.user_voted), so that the database is not hit each time in the for loop?
You can use prefetch_related to fetch the related votes for that user.
from django.db.models import Prefetch
Post.objects.filter(
created_date__lte=timezone.now(),
is_question=1,
is_published=1
).order_by(
'-created_date',
).prefetch_related(
Prefetch('vote_set', queryset=Vote.objects.filter(user=request.user), to_attr='user_votes')
)
Then in your template, change the check to:
{% if post.user_votes %}

Django 1.6: model fields not showing

I'm trying to get a list of all the doctor listings from the Doctor model in one of the templates. But the template is not showing anything. It's not like there is no data in the models, I can see it's populated through the admin panel.
here is the template doclistings.py
{% for doc in doctor.all %}
<p>{{doc.name}}</p>
<p>{{doc.specialization}}</p>
<p>{{doc.clinic}}</p>
{% endfor %}
Here is the views.py
def allDocs(request):
return render(request, 'meddy1/doclistings.html')
Here is the models.py
class Doctor(models.Model):
name = models.CharField(max_length=30)
specialization = models.ForeignKey(Specialization)
scope = models.CharField(max_length=100, blank = True)
clinic = models.ForeignKey(Clinic)
seekers = models.ManyToManyField(DoctorSeeker, through='Review')
language = models.ManyToManyField(Language)
education1 = models.CharField(max_length=100)
education2 = models.CharField(max_length=100, null = True)
gender_choices = ( ('M', 'Male'), ('F','Female'),)
gender = models.CharField(max_length=5, choices = gender_choices, null=True)
profile_pic = models.ImageField(upload_to='meddy1/images/', blank=True)
statement = models.TextField(null=True)
affiliation = models.CharField(max_length=100, null = True)
Here is urls.py
url(r'^doclistings/$', views.allDocs, name='allDocs'),
You need to pass the list to template from the view. In your code, the variable doctor is not defined in the template, so it doesn't show anything.
Change your view to pass doctlist as
def allDocs(request):
return render(request, 'meddy1/doclistings.html', {'doclist': Doctor.objects.all()})
Update template to use doclist to show each item.
{% for doc in doclist %}
<p>{{doc.name}}</p>
<p>{{doc.specialization}}</p>
<p>{{doc.clinic}}</p>
{% endfor %}

Categories