How to frequently update some particular field in database? - python

This is my model to store bus details. Here I have kept a field named bookedSeat to store which seat is booked ( input a-z or A-Z ).Every-time user book a seat a single character (inputted from user) should be added to bookedSeat field in database.
class busDetails(models.Model):
busID = models.AutoField(primary_key=True)
arrival = models.CharField(max_length=50)
destination = models.CharField(max_length=50)
rent = models.IntegerField()
distance = models.IntegerField()
bookedSeat = models.CharField(max_length=100)
def __str__(self):
return self.arrival+' --> '+self.destination
I am getting stuck at how to frequently update(add into existing) that particular database field(bookedSeat)? (without adding any new row)
How do you solve this problem?
Thank You :)

Create an updateview for that Model and specify the fields that you would like to update. You can use a custom form, But trust me these generic views will save you a lot of time .
views.py :
from django.views.generic.edit import UpdateView
class updimagesUpdateView(UpdateView):
model = updimages
fields = ['approval']
template_name_suffix = '_update_form'
Of all the attributes, you can mention the ones you need to be updated.
As shown in the last line above (template_name_suffix) , use the same naming suffix pattern for the template... [modelname_update_form.html] and display the form...
modelname_update_form.html :
{% extends "base.html" %}
{% load static %}
{% load bootstrap_tags %}
{% block title %} Update {% endblock %}
{% block body%}
<div class="jumbotron">
Are you sure you want to approve the Image ?
</div>
<br>
<form method="POST">
{% csrf_token %}
{{ form|as_bootstrap }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
make sure you get the corresponding element you want to update from the template :
<h3>update</h3>
clicking the above triggers the url. Add the urls ,
urls.py:
path('update/<int:pk>', views.updimagesUpdateView.as_view() , name = "update"),
PS: You can also update values from views using queries to select the desired object and then editing them like this ,
in views.py :
example = model.objects.filter(id=images.id).update(content=txt)
check out the documentation for more info :
https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/

Related

Show Groupnames in a dropdown list

I am working on a studentresult website in Python and Django. Now I want to ask to the database to give me the names of the groups that are in the database. Using the standard db.sqlite3 database from django. In the Dropdown menu I get three white bars because I have three groups now. When I the Class DisplayGroups to id = Models.IntegerField(id, flat=True) change return.self.group_name to return self.id then the dropdownlist shows me the ID that the group has. But how can I show the name of the group. Tried a lot:
Changed to group in the model
Changed to groupname in the model
Changed a few of the commands in the views.py
Made a new database item Groepen and changed query to that.
views.py
from django.shortcuts import render, redirect
from .models import DisplayGroups, DisplayUsername
from django.contrib.auth.models import User, Group
def index(request):
response = redirect('/login')
return response
def home(response):
return render(response, "home/home.html")
def bekijk(request):
DisplayGroup = Group.objects.all()
print(DisplayGroup)
DisplayNames = User.objects.all()
print(DisplayNames)
return render(request, "home/bekijk.html", {"DisplayGroups": DisplayGroup,"DisplayUsername":DisplayNames})
models.py
from django.db import models
# Create your models here.
class DisplayGroups(models.Model):
group_name = models.CharField(max_length=200)
def __str__(self):
return self.group_name
class DisplayUsername(models.Model):
username = models.CharField(max_length=100)
def __str__(self):
return self.username
The html page
{% extends 'home/base.html' %}
{% block title %}Cijfers studenten{% endblock %}
{% block javascript %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var $productvar=$("#groupdd1");
$itemvar=$("#userdd1");
$options=$itemvar.find('option');
$productvar.on('change', function()
{
$itemvar.html($options.filter('[value="'+this.value+'"]'))
}).trigger('change');
});
</script>
{% endblock %}
{% block content %}
<h1>Studentresultaten</h1>
<select id="groupdd1">
<option disabled="true" selected>-- Select Fruit --</option>
{% for result in DisplayGroups %}
<option>{{result.group_name}}</option>
{% endfor %}
</select>
<select id="userdd1">
<option disabled="true" selected>-- Select Fruit --</option>
{% for result in DisplayUsername %}
<option>{{result.username}}</option>
{% endfor %}
</select>
{% endblock %}
The piece of jquery is for later, because I want to make a dependant dropdown menu. Hope you guys can help me. Thanks in advance!
#WilliamVanOnsem is right the model from where you are filtering is Group which do not have group_name as a field. Here's what you can do.
In views.py
DisplayGroup = DisplayGroups.objects.all()
DisplayNames = DisplayName.objects.all()
Now in HTML template you can access group_name and result.username. The User model has username field so result.username did not show an empty text

Get model attributes without making them required for modelform_factory?

I've got a modelform_factory which works perfect for what I need.
I call it like this:
dep_formset = modelformset_factory(
Dependent,
fields=('has_medical', 'med_group_id'),
max_num = dep_count
)
As you might guess, Dependent has additional fields that I want to use simply for display purposes (first_name and last_name respectively) I want to show the first_name and last_name of the dependent person - but have it be simply for display, not edit.
If I add 'first_name' and 'last_name' to the fields in the above, I can then access them in my template - but the form fails against .is_valid() because I'm displaying them simply as text and not as an input, so they're not being POST'ed
Is there some clever way to get access to the first_name and last_name of the dependent objects without adding them to fields for the formset_factory?
The template looks like this (partial snippet so you can see what I'm trying to do with the first_name, last_name):
{% for form in dep_formset %}
{{ form.id }}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<div class="g">
<h4>{{ form.first_name.value }} {{form.last_name.value}}</h4>
</div>
<div class="g dependent-option">
<div class="g-1-4 dependent-option-check">
{% if form.has_medical %}
Based on provided information it looks like the formset is tied to an instance which you can access in template:
{{ form.instance.first_name }}

How show related object in Django admin from the model with a foreign key point of view?

I got two Django models linked by a Foreign key:
class Author(models.Model):
...
class Book(models.Model):
author = models.ForeignKey(Author)
Please consider admin example below (I want to do the opposite):
from django.contrib import admin
from my_app.models import Author, Book
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
admin.site.register(Author, AuthorAdmin)
With this example, we can see in the admin all authors, and for each author, their books.
Now, I would like to to it the other way around. Have en entry per Book in the administration and display the Author informations (it can be readonly) on the Book details. I tried with the solution below, but obviously it didn't work:
from django.contrib import admin
from my_app.models import Author, Book
class AuthorInline(admin.TabularInline):
model = Author
class BookAdmin(admin.ModelAdmin):
inlines = [
AuthorInline,
]
admin.site.register(Book, BookAdmin)
Django raised an error :
<class 'my_app.admin.AuthorInline'>: (admin.E202) 'my_app.Author' has no ForeignKey to 'my_app.Book'.
Do you know how to do that ?
More context :
Django 1.11
I want to display Book and Author as full readonly, so the foreign key of the Book will not be changed (at least not from the admin)
Here my solution, maybe not the best, but it works! :)
The idea is to change the template and therefor be able to display it the way I wanted.
admin.py :
class BookAdmin(admin.ModelAdmin):
...
change_form_template = 'admin/book_details.html'
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
extra_context['book'] = Book.objects.get(id=object_id)
extra_context['author'] = extra_context['book'].author
return super().change_view(request, object_id, form_url, extra_context=extra_context)
admin.site.register(Book, BookAdmin)
For the template I just copy/past the template change_form.html from the admin.
admin/book_details.html:
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}" />{% endblock %}
{% block coltype %}colM{% endblock %}
{% block breadcrumbs %}
<div class="breadcrumbs">
{% trans 'Home' %}
› {{ opts.app_config.verbose_name }}
› {% if has_change_permission %}{{ opts.verbose_name_plural|capfirst }}{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %}
› {% if add %}{% blocktrans with name=opts.verbose_name %}Add {{ name }}{% endblocktrans %}{% else %}{{ original|truncatewords:"18" }}{% endif %}
</div>
{% endblock %}
{% block content %}
# Display here want you want !
{% endblock %}
I took a look at Django admin's template to be able to display my Book and Author the same way as if they were displayed by the default template. So my user won't be disrupted by this view.
If you found a better way, please let me know! :)
There's ModelAdmin.readonly_fields that can take callables on both the ModelAdmin itself or the Model and show them on the add/change form. (docs)
If you wanted to show an author's name on the book change form in the admin, you would do it like this:
class BookAdmin(admin.ModelAdmin):
readonly_fields = ['get_author_name']
[...]
def get_author_name(self, book):
return book.author.name
All the readonly fields will be displayed beneath the form's regular fields.
You can also customize the way fields are displayed by modifying ModelForm.get_fields().
If you do it like this, you save yourself the trouble of overwriting the templates.
You can't do this. Inlines only make sense in one direction.
The way to do this is to define the display of the author field so that it gives you sufficient information automatically; for example, by defining the __str__ method.
As the error says:
class 'my_app.admin.AuthorInline'>: (admin.E202) 'my_app.Author' has no ForeignKey to 'my_app.Book'.
You need to add the foreign key in Author table that references Book table.
The first one worked because you would have a foreign key in Book that references Author.

Django: Check that row exists in list

I want to check that user_id exists in the profile_images table from my Django template.
My Model
class profiles(models.Model):
profile_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User)
-----
class Profile_images(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User)
image = models.ImageField(upload_to='uploads/',default = 'uploads/no-img.jpg')
My View
def view_profiles(request):
if request.user.is_authenticated():
view_all_profiles = profiles.objects.all()
profile_image = Profile_images.objects.all()
return render_to_response('profiles/all.html', {'profiles':view_all_profiles,'profile_image':profile_image}, context_instance=RequestContext(request),)
else:
return HttpResponseRedirect('/accounts/login/')
My Template
{% for profile in profiles %}
<li>
{% for image in profile_image %}
{% ifequal image.user_id profile.user_id %}
<img src="{{MEDIA_URL}}{{image.image}}" alt="image" />
{% endifequal %}
<!-- i want to check here if not user_id exist in profile_images table -->
{% if profile.user_id not in profile_image %}
<img src="{% static 'images/no-image.jpg' %}" alt="image" />
{% endif %}
{% endfor %}
</li>
{% endfor %}
{% if profile.user_id not in profile_image %} is not working. I'm new to Django & python and I'm stuck here. Please suggest better ways if my code is not correct.
in your view you could get all user_ids with a profile image, something like:
user_ids_with_profile_images = Profile_images.objects.all().values_list('user_id', flat=True)
Then in your template you could check if profile.user_id not in user_ids_with_profile_images.
It might actually be a little cleaner to loop through all the users with profiles in your system and get their profile images through the foreign key, instead of looping through all the profiles and trying to get the users...
This is really a design problem, you've got a separate model specifically for a profile image when that could just be a field on the profile model itself.
class Profile(models.Model): # convention is to use a non-plural name for models
# No need to explicitly set the primary key, this will be added automatically
# profile_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User)
image = models.ImageField(upload_to='uploads/',default = 'uploads/no-img.jpg')
-----
Now it would just be a case of using {{ profile.image }} with no need for any additional looking up.

D3.js Directed Graph Django Integration

I have a simple Django application that queries a database and displays the fields of the objects returned. I was wondering what would be the best way to go about integrating this directed graph visualisation into my project; I've never worked with d3 until now.
Allow me to explain my application. At the moment, it's simply a form that allows users to query contents of the database regarding information on books, by entering the unique ID of a book. This works fine, the contents are displayed through the use of a template.
What I wish to do is used one of the fields of the queried objects to push data into the graph example above, and simply display this graph in a new window when a text-link is pressed.
Here's my application structure:
Code
myapp.models.py:
from django.db import models
class Book(models.Model):
uid = models.IntegerField(primary_key=True)
title = models.CharField(max_length=30)
related_books = models.CharField(max_length=2048)
class Meta:
db_table = u'books'
The field related_books contains the data I wish to graph. The data is stored in the format rel_book1 rel_book2 rel_book3 ... where each book is related to the queried Book object, there are n related books for each object, but there is at least always two.
myproject.templates.search.html:
<form action="" method="get">
<label for="id_q">Search:</label>
<input id="id_q" name="q" type="text">
<input type="submit" value="Submit">
{% if found_entries %}
<ul>
{% for i in found_entries %}
{{ i.uid }} {{ i.title }} {{ value|linebreaks }}
{% endfor %}
</ul>
{% endif %}
</form>
So this is where I'd like to display the graph; in a new window when a text-link is pressed.
myapp.views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from myapp.search import get_query
from myapp.models import Book
def search(request):
query_string = ''
found_entries = None
if ('q' in request.GET) and request.GET['q']:
query_string = request.GET['q']
found_entries = Book.objects.filter(uid=query_string)
return render_to_response('search.html',
{ 'query_string': query_string, 'found_entries': found_entries },
context_instance=RequestContext(request))
So just to reiterate, a user enter a unique ID for a given book and contents of the database related to that book are displayed. At the moment the ID and title are displayed, I'd also like to display a link to the directed graph example.
So my question is, how would I go about extracting the information out of the field related_books when the Book model is queried, so that I can push this data into the graph example to generate graphs for each Book object generated?
Thanks for bearing with me!
It seems to me you already have enough information. Your view returns book objects that match the filter, and related_books is a member of the Book class.
You'd simply need to generate a link on the fly by iterating over the related_books attribute of each book, e.g.
{% for book in found_entries %}
# print out whatever results here
<a href="graphing_page.html?contents=
{% for content in book.related_books %}content{% endfor %}
">Graph this</a>
{% endfor %}
I'm not sure what parameters the d3 library takes, but a list of connected components seems reasonable.

Categories