Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
which database is should I use for my website? [closed]
I am planning to make a website in Python-Django. People can come to my website and can take a quiz. There will be user table which I think 5000-6000 entries will be there. Another table for questions which will have approx 40,000 to 50,000 questions. (There will be many more table but wont have more than 2000 entries) User can come to my website, select number of question(say 50) and can start a quiz. Now this 50 question will be randomly selected from my database. So, my questions are 1) which database should I use for this kind of function? 2) Is it good to use random function to get 50 questions from 50,000 question?(I am free for any other suggestion) I am going to get all the data and perform random function and will get those 50 question(any other suggestion will be appreciated) 3) If in future the size of database increases and want to shift to another database, how convenient will it be? thank you in advance -
Django how to save multiple dynamic form
Unable to save dynamic form entry to the DB. It only takes the last entry and saved into the DB. Here is the code: VIEW def dynamicRow (request, *args, **kwargs): form = dynamicRow_Form(request.POST or None) template_name = 'cvp/rowdata.html' ### Below will generate the FORM based on SEQ number. if request.method == 'POST': if form.is_valid(): print("NO of ROW: {}".format(request.POST['totalnum'])) no_of_rows = int(request.POST.get('totalnum')) list_of_rows = [dynamicRow_Form() for i in range(no_of_rows)] args = {'forms': list_of_rows} for i in range(len(args['forms'])): i = dynamicRow_Form(request.POST) print("FORM ROWS: {}".format(i.is_valid())) if i.is_valid(): print("HOSTNAME: {}".format(i.cleaned_data['hostname'])) i.save() messages.success(request, 'Successfully stored data into database.') continue else: messages.error(request, form.errors) else: form = dynamicRow_Form() return render(request, template_name, {'form': form }) If No_of_row is 1 it saves fine, if No_of_row more then one, only takes last entry and saves the data into DB. Is the logic is correct? not sure what were is incorrect. -
How to provide choices to django rest framework DecimalField serializer?
Django==2.2.6 djangorestframework==3.10.3 Models.py VAT_CHOICES = [(Decimal('0.00'), '0%'), (Decimal('6.00'), '6%'), (Decimal('12.00'), '12%'), (Decimal('25.00'), '25%')] class Service(models.Model): vat = models.DecimalField(verbose_name=_('vat'), decimal_places=2, max_digits=10, choices=VAT_CHOICES) serializers.py class ServiceSerializer(serializers.ModelSerializer): vat = serializers.DecimalField(decimal_places=2, max_digits=10, coerce_to_string=True) If I do this then the value of vat in response is in srting as expected but the choices validation does not implied then. Now I can create a service with vat="5.00" which should not be possible because there is a choice list in the model. How can I have the string representation of the decimal field vat but keep the choices validation? -
Show a login page to a user who is not logged in without LoginRequiredMixin / django
this is my code class PostDetail(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CommentForm() return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if request.user.is_authenticated: if form.is_valid(): comment = form.save(commit=False) comment.comment_owner = request.user comment.post = Post.objects.get(pk=kwargs['pk']) comment.save() return redirect('blog:detail', pk=kwargs['pk']) else: return redirect('blog:detail', pk=kwargs['pk']) else: ??? i added comment form in detailview When a user who is not logged in attempts to add a comment, I want to display a login page. i didn't add LoginRequiredMixin because anyone should be able to see the post. any advice? -
how can get title name instead of id in url http://localhost:8000/home/6/
how can i add title name into URL instead of id HTTP://localhost:8000/home/6/ my URL is path('', views.homepage, name='home'), path('<int:services_id>/', views.details, name='details'), path('<int:prgmm_id>/program/', views.program, name='program') -
How to add custom views or overide views for Django Admin index?
urls.py -> ''''from django.contrib import admin from django.urls import path from Administrator import views admin.site.index_template = 'admin/dashboard.html' admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), ] ''' I have added custom admin_index template in urls.py.My doubt is shown in the picture.please,see it. My Admin index custom template.Kindly ,See it -
Django views local variable 'varname' referenced before assignment and admin panel
I have a simple view where I am capturing a post parameter and regex matching with an array. I use a local variable for that in the view. When I open any model of myapp in the admin panel then it goes through checking all app files and gives me an error on using this local error as not referenced, which obviously gets value only when requests are made and regex is matched. Why does it do that? Admin panel shouldn't complain about a local variable not referenced. How to fix this? Views location = ['name1','name2','name3'] @csrf_protect def locationnames(request): if request.method == "POST": r = re.compile(request.POST['place']) found = list(filter(r.match, location)) else: pass print (found) return JsonResponse(found, safe=False) #To Investigate for Security Error on accessing any module on the app from the admin interface - UnboundLocalError at /admin/myapp/names_location/ local variable 'found' referenced before assignment Request Method: GET Request URL: http://10.0.0.99:8000/admin/myapp/names_location/ Django Version: 3.0.1 Exception Type: UnboundLocalError Exception Value: local variable 'found' referenced before assignment Exception Location: /data/project/myapp/views.py in geonames, line 33 Python Executable: /usr/bin/python Python Version: 3.7.5 Python Path: ['/data/project', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/root/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sun, 29 Dec 2019 23:37:30 -0800 -
Can you do math on variables inside double curly braces in a html script?
this is a html file i currently have: <!DOCTYPE html> <html> {{unit.unit_class}} <div id="stats"></div> <script> var str ="", i; for(i = 1; i<=99; i++) { str = str + "<p>level " + i + ": hp {{unit.hp_current}}</p>"; } document.getElementById("stats").innerHTML = str; </script> </html> that bit in the for loop {{unit.hp_current}} is a decimal number. It's value is currently set to 0.00, which it does display on my page. I was wondering if I was able to do arithmetic on this variable inside the double curly braces. I tried doing something like {{unit.hp_current + 3}} or {{unit.hp_current}} + 3 in order for the program to display 3.00 instead of 0.00, but it doesn't seem to work. Is this something I need to make a function for instead in my views.py? -
Object of type <> is not JSON serializable
I am running a website using Django . Here is views.py: def signup(request): registered=False failed_ref=False wrong_ref=False if request.method=='POST': if 'city' in request.POST: user_form = UserForm(data=request.POST) profile_form = ProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user else: print(user_form.errors,profile_form.errors) else: profile_form=ProfileForm() return JsonResponse({'profile_form':profile_form,'registered':registered, 'failed_ref':failed_ref,'wrong_ref':wrong_ref},safe=False) When i try to get, Json Response, i am getting Object of type ProfileForm is not JSON Serializable My ProfileForm(): class ProfileForm(forms.ModelForm): class Meta: model=Profile widgets = { 'address_line_1': forms.TextInput(attrs={'placeholder': 'Door No,Building'}), 'address_line_2': forms.TextInput(attrs={'placeholder': 'Area,Locality'}), } fields=('first_name','last_name','mobile_no','email','address_line_1','address_line_2','postal_code','city','country','image','referral_contact','promo_coupon','ic') How to get JSON Response for this? -
How to remove duplicate in database
The problem is that all fields gets duplicated, i want to achieve just a single field for all product in order. I tried using .distinct(), it is not working. You can see photos; class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey('Payment', on_delete=models.SET_NULL, blank=True, null=True, related_name='payment_opt') def __str__(self): return self.user.username def orders(request): order = Order.objects.filter(user=request.user.id, ordered=True).distinct() context = { 'order': order, } return render(request, 'orders.html', context) {% for order in order %} <p class="text-muted my-2" style="font-size:14px"> Address: {{ order.billing_address.street_address|capfirst }}</p> <p class="text-muted my-2" style="font-size:14px"> Apartment Address: {{ order.billing_address.apartment_address|capfirst }}</p> <p class="text-muted my-2" style="font-size:14px"> City: {{ order.billing_address.city|capfirst }} </p> <p class="text-muted my-2" style="font-size:14px"> State: {{ order.billing_address.state|capfirst }} </p> <p class="text-muted" style="font-size:14px"> Country: {{ order.billing_address.country.name|capfirst }}</p> {% endfor %} -
Prefetching returning empty values for some object
Assume these two models. class Folder(model): name = models.CharField(max_length=8) files = models.ManyToManyField('File') class File: path = models.CharField(max_length=255) First I was fetching the folders and while looping over them fetching the files with distinct path folders = Folder.objects.all() for folder in folders: files_with_distinct_path = folder.files.distinct('path').order_by('path') but this suffers from N+1 problem, So I tried prefetching the files while fetching all the folders. from django.db.models import Prefetch folders = Folder.objects.prefetch_related( Prefetch( 'files', queryset=File.objects.distinct('path').order_by('path'), to_attr='distinct_files' ) ) but it turns out now there objects with empty distinct_files which is not the correct result, these objects have files but after prefetching the result is empty only for few objects. -
Uncaught TypeError: Cannot read property 'pop' of undefined at change HTMLSelectElement.onchange
i am trying to create a function that allows me to change my chart.js data based on what i have selected on a drop down menu. There has not been much tutorials on chart.js x django rest framework and i manage to piece together these based off parts and pieces from articles online. The idea is to call a function within the AJAX function such that i am able to change the data array that goes into the model itself , however i've been facing some difficulty in doing so. This is my ajax function: <script type="text/javascript"> endpoint = 'api/chart/data' $.ajax({ type: "GET", url: endpoint, success: function(data){ sales_time = data.sales_time_axis sales_rev = data.sales_rev conversion_label = data.conversion_label conversion_data= data.conversion_data profit_data_per_project= data.profit_data_per_project createChart() change(sales_rev) }, error: function(error_data){ console.log('error') console.log(error_data) } }) Here is the change function definition : function change(data){ var val = "Hi"; console.log(val) data.pop() console.log(data) } here is my HTML: <div class="card-body" id="card_body"> <select class="text_select" id="chart-select" onchange="change()" name="select"> <option value="All">All Time</option> <option value="3" id = 'hello'>Last 3 Months</option> <option value="6">Last 6 Months</option> <option value="12">Last Year</option> <option value="24">Last 2 Years</option> </select> <canvas id="myChart"></canvas> </div> but i am receiving this error in my console: (index):176 Uncaught TypeError: Cannot read property 'pop' of … -
Django multiple annotate resulit
python 3.6 django 2.2 I'm writing a statistics app with django. I need to show the number of user connections by month and by country. The result I want is below. this_month : US(315), CA(115), JP(95), KR(52), ...... last_month : US(525), CA(233), AU(156), JP(112), ...... last_2_month : US(456), AU(243), CN(145), BR(156), ...... ... ... last_12_month : US(525), CA(233), AU(156), JP(112), ...... my model.py is from inspectdb class UserLogs(models.Model): uid = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, db_column='uid') uuid = models.CharField(max_length=100, blank=True, null=True) acct_type = models.IntegerField(blank=True, null=True) auth_type = models.IntegerField(blank=True, null=True) log_type = models.CharField(max_length=20, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) created_at_unix = models.CharField(max_length=100, blank=True, null=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) nation_cname = models.CharField(max_length=10, blank=True, null=True) # nation_cname example(US, CA, TH, VN, KR, AU, CN,.....) # nation_cname has been added to an existing database, so None, null, 'blank' exists. I'm trying to write like this..(views.py) this_month = UserLogs.objects.filter(created_at__gte=this_month).values('nation_cname').annotate(the_count=Count('nation_cname')).order_by('-the_count') last_month = UserLogs.objects.filter(created_at__gte=last_month, created_at__lt=this_month).values('nation_cname').annotate(the_count=Count('nation_cname')).order_by('-the_count') last_2_month = UserLogs.objects.filter(created_at__gte=last_2_month, created_at__lt=last_month).values('nation_cname').annotate(the_count=Count('nation_cname')).order_by('-the_count') # more and more.. However, this causes duplicate queries. How can I solve it with one query? -
How can i make jquery, css external and internal styling work in my template?
I have been working on a django project for some time now, but i'm having some problems with making external and internal css work, only inline css works, i have 2 questions How can i make external css or internal css work and jquery? I tried running the collectstatic command, i added STATIC_URL, STATIC_DIR etc, i also added the css and jquery file path to my html How can i beautify my registration/login forms? i already tried django_crispy_forms but i still didn't get the desired result. Thanks in advance for helping me out. settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") MEDIA_DIR = os.path.join(BASE_DIR, "media") STATIC_ROOT = os.path.join(BASE_DIR, 'static') AUTH_USER_MODEL = "website.User" """STATICFILES_DIR = [ STATIC_DIR, ]""" # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #My Apps #'avatar', 'django_countries', 'website', 'djmoney', 'crispy_forms', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'main.urls' TEMPLATES = [ { 'BACKEND': … -
TypeError: get() missing 1 required positional argument: 'id'
TypeError: get() missing 1 required positional argument: 'id' In url.py, I am unable to mention the id object. The regex I have provided in ur_pattern, the browser unable to find the 'id'. url.py: from django.contrib import admin from django.urls import path from withoutrest import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^api/(?P<id>\d+)$', views.EmployeeDetails.as_view()), ] view.py: from django.shortcuts import render from django.views.generic import View from withoutrest.models import employee from django.http import HttpResponse import json from django.core.serializers import serialize from withoutrest.mixins import serializeMixin # Create your views here. class EmployeeDetails(serializeMixin,View): def get(self, request, id, *args, **kwargs): emp = employee.objects.get(id=id) json_data = self.serialize([emp,]) return HttpResponse(json_data, content_type='application/json') mixins.py: from django.core.serializers import serialize import json class serializeMixin(object): def serialize(self, emp): json_data= serialize('json', emp) pdict= json.loads(json_data) list=[] for obj in pdict: emp_data=obj['fields'] list.append(emp_data) json_data=json.dumps(list) return json_data test.py: import requests BASE_URL = 'http://127.0.0.1:8000/' ENDPOINT = 'api/' def get_resource(id): resp = requests.get(BASE_URL + ENDPOINT + id + '/') print(resp.status_code) print(resp.json()) get_resource(id) -
Getting the application error in deploying app in heroku?
I am trying to deploy my django application in heroku and it is getting an application error even I had included the procfile in the project procfile: web: gunicorn realstate.wsgi when i run the heroku logs --tail command the error is given as below -
How to POST data from external json to own database in Django REST Framework
I want to get the info about specyfic movie from omdb api by enter the title and then save it to my database. I need to use Django REST Framwerork. Now I can't make a propper POST method. Could you look at my code, especially at my create method in views? class MoviesView(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer def list(self, request, *args, **kwargs): movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): if request.data.get("title"): title = request.data["title"] else: return Response(data={"Error": "Enter title"}, status=status.HTTP_400_BAD_REQUEST) url = f'http://www.omdbapi.com/?t={title}&apikey={settings.API_KEY}' response = requests.get(url) if response.status_code == requests.codes.ok and response.json()['Response'] == 'True': if not Movie.objects.filter(Title=response.json()['Title']).exists(): serializer = MovieSerializer(data=response.json()) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(data={"Error": "Lorem ipusm!"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: movie_from_database = Movie.objects.get(Title=response.json()['Title']) movie_from_database_serialized = MovieSerializer(movie_from_database) return Response(movie_from_database_serialized.data) else: return Response(data={"Error": "Lorem ipusm!"}, status=status.HTTP_204_NO_CONTENT) My model and serializer: class Movie(models.Model): Title = models.CharField(max_length=100) Year = models.CharField(max_length=100) Released = models.CharField(max_length=100) Runtime = models.CharField(max_length=100) Genre = models.CharField(max_length=100) Director = models.CharField(max_length=100) def __str__(self): return self.Title class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' My app urls: router = routers.DefaultRouter() router.register('movies', views.MoviesView) urlpatterns = [ url('', include(router.urls)) ] Could you help me? -
Display content based on selected checkbox value
I am trying to retrieve the information based on the selected checkbox value. Right now, i have managed to display the content accordingly based on the selected checkbox. However, it only works for one selected checkbox. If i select more than 1 checkbox, it will return the last selected checkbox. I understand I have to use request.POST.getlist('name') to pass multiple checkbox value. When I did this, it displays nothing. I would like to show the name of students who have attended the class on the selected week. Below is my sample code: Views.py def filterWeek(request): qs = MarkAtt.objects.all() week_checked = request.GET.get('week_check') if week_checked: # week_mchecked = request.POST.getlist('week_check') #not working, display nothing #qs = qs.filter(week_in=week_mchecked) qs = qs.filter(week=week_checked) context={ 'queryset' : qs } return render(request, "filter.html", context) Templates: <form method="GET" action="."> <input type="checkbox" id="week_check" name="week_check" value="1"/> Week 1 <input type="checkbox" id="week_check" name="week_check" value="2"/> Week 2 <input type="checkbox" id="week_check" name="week_check" value="3"/> Week 3 </form> Hope anyone of u could help me out. Appreciate it so much. -
How to solve NoReverseMatch
I have project's urls.py file whiche located at forecast/urls inside it i am trying to setup url routing for my app's urls from django.contrib import admin from django.urls import path,include from django.contrib.auth import login urlpatterns = [ path('auth/',include ('authorization.urls')), ] In authorization/urls.py from django.urls import path from . import views urlpatterns = [ path('login/', views.login_name), ] After running server i want to open http://127.0.0.1:8000/auth/login and i got NoReverseMatch at/ auth/login/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Based on my urls setup i expect that path function from project's urls.py will give to included authorization/urls.py path auth/ than second path from authorization/urls.py will add to it pattern login than constructed auth/login/ will give to my view function if i am right why i got NoReverse error. Can anyone guide me what i am doing wrong -
Django Template Inheritance not fully working
base.html Blogpage.html Results: The base template is added but i can't insert contents between {% block content%} {% endblock %}. Please help. Thanks in advance . :) -
psql -h localhost hangs on macOS
I'm trying to set up a very basic Django + PostgreSQL running locally on my Mac laptop, following the instructions from here: https://towardsdatascience.com/data-engineering-with-python-django-and-postgresql-99409492769 I installed postgresql using brew, and I can access the psql CLI by typing that command alone. But after I change the Django settings to point to localhost:5432, running python manage.py migrate just hangs. And so does psql -h localhost so I assume there's some issue with the way I have the database server configured. Any ideas of what's going wrong? -
How can I include my argument in {% include %} tag django?
{% if type == "Cryptography" %} {% include 'Cryptography/_____.html' %} {% elif type == "Password Cracking" %} {% include 'PasswordCracking/_____.html' %} {% endif %} In a template, I want to include some HTML pages with 1.html 2.html 3.html which are inside C and PC directories. I have tried like this where the page is my argument variable. {% if type == "Cryptography" %} {% include 'cryptography/'{{page}}'html' %} {% elif type == "Password Cracking" %} {% include 'PasswordCracking/'{{page}}'.html' %} {% endif %} View for this def lessons(request, foo, page): return render(request, 'lessons.html', {'type': foo, 'page': page}) Note: type and page are my arguments -
How to render form.errors without html
i want to render form.errors individually without the html tag but it doesn't seem to work views.py .... context = { 'login_error': form.errors, 'login_form': LoginForm(), } return render(request, 'shop/login.html', context) .... login.html .... <label class="mt-1"> {{ login_form.username.label }} </label> {{ login_form.username }} {{ login_error.username }} <label class="mt-1"> {{ login_form.password.label }} </label> {{ login_form.password }} {{ login_error.password }} .... the answer i got is by unpacking it in a loop and then add an |escape .... {% for error in login_error %} {{ error|escape }} {% endfor %} <label class="mt-1"> {{ login_form.username.label }} </label> {{ login_form.username }} <label class="mt-1"> {{ login_form.password.label }} </label> {{ login_form.password }} .... so, the question is, why does this {{ login_error.username|escape }} {{ login_error.password|escape }} doesn't work which is the same thing (?) as {% for error in login_error %} {{ error|escape }} {% endfor %} -
How to calculate foreign keys field in Django Admin then show in list
I want to use Django to make a company management system. So I chose Django Admin as the foundation. I want the results of the calculation to be displayed in the Django Admin list. Here is my code and error message: models.py class Product(models.Model): ID = models.CharField(max_length=5, unique=True) NAME = models.CharField(max_length=30) QTY = models.IntegerField(default=0) class Order(models.Model): ID = models.CharField(max_length=5, unique=True) Product = models.ForeignKey(Product, on_delete=models.CASCADE) day_sale_30 = models.IntegerField(default=0) admin.py @admin.register(Product) class Product(admin.ModelAdmin): pass @admin.register(Order) class list_Order(admin.ModelAdmin): list_display=("NO", "Product", "day_sale_30", "daily_sales", "stock_divided_by_daily_sales") def daily_sales(self, obj): return obj.day_sale_30/30 def stock_divided_by_daily_sales(self, obj): return obj.Product__STOCK/(obj.day_sale_30/30) I got error as follows:: AttributeError at /admin/myapp/order/ 'Order' object has no attribute 'Product__STOCK' Request Method: GET Request URL: http://127.0.0.1:8000/admin/myapp/order/ Django Version: 3.0.1 Exception Type: AttributeError Exception Value: 'Order' object has no attribute 'Product__STOCK' Thanks for helping!!! -
Calculating difference between two time fields and storing it in Django model
I have a model that contains time fields for a single user. My model has several users and my aim is to get the difference between these two times and store the difference within the same model but I am not so sure how to do it. models.py: class Gettime(models.Model): id= models.ForeignKey(User, on_delete = models.CASCADE) start_time = models.DateTimeField() stop_time = models.DateTimeField() hours = models.IntegerField() #or is there a better data type to store the time difference? views.py: def diff(request): data = User.objects.filter(pk__gt=1) time_table = [] for user in data: start = Gettime.objects.filter(id = user).only('start_time') stop = Gettime.objects.filter(id = user).only('stop_time') diff = start - stop #However, this doesn't work. How can I get the time difference between the start_time and stop_time fields and store it within my model?