Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot upload media files in Django production to external folder
I have an issue on my Django production server. When I try to upload images, they always go to the app/media/ folder. However I want them to be uploaded to '/mnt/data'. In the admin panel, when I upload the image, it is always uploading in the 'app/media/' folder. I tried adjusting the Nginx config file and the settings.py, but I guess I am lost. Here is my Nginx configuration: location /static/ { root /home/rchebli/hopping/; } location /media/ { root /mnt/data/; } and the Settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Media files MEDIA_URL = '/media/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media') ) and in my model this is how I create the image: pictures = models.ImageField( upload_to='postings/', verbose_name=_('Posting_picture'), blank=True, null=True, validators=[validate_image], ) I guess following this configuration, the uploaded picture is supposed to be in mnt/data/media/postings. The media folder on the mnt/data/ is chmod 777, I did it when I lost hope in writing/reading the folder. -
React - How to secure content meant for admin user only?
I'm in a process of converting Django based templates into a client side React app. In Django I could control the rendering of a column like so: <table> <tr> <th>Column 1</th> <th>Column 2</th> {% if user.is_stuff %} <th>Column only for admins</th> {% endif %} </tr> </table> In React, I can use javascript if / ternary operator, but the content will still be visible in the output bundle. What are the options in the case of client side apps? The only way I see is to create a completely different component for admin users, and then to render the component conditionally using some server logic (so it won't be served as a static file). This will be a serious headache though. -
How to fix collapsing navbar that doesn't collapse in Bootstrap
My collapsible navbar is not working on this basic site, and I am not sure why. I have tried to reorder the CDN scripts, copied and pasted directly from Boostrap's docs, and have double checked the code a few times. I'm sure it's a stupid mistake, but can anyone help me and point out what is happening here? The toggle button appears, but doesn't do anything when clicked. This is being used with a Django project. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>{% block title %}The title I'm using{% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <form class="form-inline ml-auto"> <a href="{% url 'logout' %}" class="btn btn-outline-secondary"> Log out</a> <a href="{% url 'password_change' %}" class="btn btn-primary ml-2"> Change password</a> <a href = "{% url 'update' user.pk %}" class = "btn btn-primary ml-2">Update user profile</a> <a href = "{% url 'home' %}" class = "btn btn-primary ml-2">{{ user.username }}</a> </form> {% else … -
Django : Get Annotated values
class A(models.Model): a = models.CharField(max_length=30) class B(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) a_ref = models.ForeignKey(A, on_delete=models.CASCADE, null=True, related_name='sd') b_name = models.CharField(max_length=30, null=False) b_value = models.CharField(max_length=30, null=False) Now I want to apply filters to A and in the queryset add the value of a_ref when the b_name="first" filter_dict = {key:value} fallback_filter = Q() searched_data = A.objects.filter(fallback_filter) searched_data = annotate(b_searched_value=FilteredRelation('sd', condition=Q(sd__b_name="first"))) for data in searched_data: print(data) Now in this data I do not get any reference of b_searched_value. I want to directly get the value of b_value in data itself and not make another DB call using the 'a_ref'. -
Are there any other ways than authentication to tell the users apart?
In my app, the user can select a Youtube video that will be downloaded to MEDIA_ROOT folder and then also made available for the user to download. Whenever the user chooses another video to download, the previous one is deleted from MEDIA_ROOT. So at any given moment there is only one video sitting in the MEDIA_ROOT folder for a particular user. Is there any way - apart from implementing user authentication and associating the downloaded files with a user through foreign key, which I feel is an overkill for only this task - of telling the users apart whenever such download request is being made, so that one user's request does not cause the deletion of the file downloaded by some other user (as all the files sit in the same MEDIA_ROOT folder)? -
Do not record from <b-form-select> to my database
how I hope you can help me, I am trying to save the values that are in a b-form-select, the funny thing is that it fills the select and as you can see I do alert, and there I realize that if it brings the value that I need , but when making the put puts a null value, inside my model I define it as charfield and it takes it from a Choice <b-form-select v-model="elmovimiento.tipo" @select="Tselected" :options="Toptions" required="required"></b-form-select> updateMovimiento: function() { alert("Este es Tipo: "+this.elmovimiento.tipo+" Este es Descripción: "+this.elmovimiento.descripcion); id = this.elmovimiento.id; varurl = "/control/movimiento/api/mov/"+id+'/'; this.$http.put(varurl, this.elmovimiento).then((response) => { alert("Este es Tipo: "+this.elmovimiento.tipo+" Este es Descripción: "+this.elmovimiento.descripcion+" Otro: "+this.elmovimiento.arete); this.elmovimiento = response.data; this.$root.$emit('bv::hide::modal', this.infoModal.id); }) .catch((err) => { this.loading = false; console.log(err); }) }, -
Call Django View from D3.js onclick event on Heatmap
Is there a way to invoke a Django view and pass it a parameter(s) from a D3.js onclick event handler associated with a heatmap? For my heatmap, I'm using the code found at the following: https://www.d3-graph-gallery.com/graph/heatmap_style.html Any help would be greatly appreciated. Thanks. -
Django CRUD : Reload object after CRUD update
I'm working on a dynamical object menu in my project (with django-simple-menu) and I have some questions in order to display this one after updated it. Especially reload the menu immediately after the update to display changes. I have a simple model: class MyModel(models.Model): """ A class to manage navbar menu of the application """ collection = models.ManyToManyField('app.Collection', related_name='collection_list', symmetrical=False) application = models.ForeignKey('app.WebApplication', verbose_name=_('application'), related_name='application', on_delete=models.CASCADE) title = models.CharField(max_length=30, verbose_name=_('title'), default=('Xth Edition (Current)')) order = models.PositiveSmallIntegerField(default=1, verbose_name=_('menu order'), blank=True, null=False) display = models.BooleanField(verbose_name=_('Display menu'), default=True) class Meta: verbose_name = _('menu setting') verbose_name_plural = _('menu settings') This model is handle by django-crud library. Then I have a menu.py file containing: class CustomMenu(Menu): def __init__(self): self.create_custom_menu() def create_custom_menu(self): qs_custom = MyModel.objects.filter(display=True).order_by('application', 'order') for menu in qs_custom: slug = slugify(menu.title) # children menu children = [] for col in menu.collection.all(): children.append( CustomMenuItem(col.title, reverse('#'))) self.add_item(slug, CustomMenuItem(menu.title, f'#{slug}', children=children)) self.add_item('toto', MenuItem(_('Toto'), '#')) self.add_item('tata', MenuItem(_('Tata'), '#')) Menu.add_item('home', MenuItem(_('Home'), '/home')) CustomMenu() Menu.add_item('content', MenuItem(_('Content'), '#content', children=content_children)) Menu.add_item('admin', MenuItem(_('Admin'), '#admin', children=settings_children)) The Menu class is available here. My issue: When I update my model (for example by checking boolean field to display the object), my object menu in navbar is not displayed immediately. I have to restart the server … -
How to send cookies in CreateView?
I am trying to implement signed cookie sending in CreateView, but I have encountered with the trouble. Following code works in UpdateView but in CreateView we dont have self.object in render_to_response method and basically we cant get a pk there or at least I dont know how to do it. Question is how to get pk or id of a freshly created object or maybe alternatively in which method I could move my code to get access to pk from there? Thanks. def render_to_response(self, context, **response_kwargs): response = CreateView.render_to_response(self, context, **response_kwargs) existing_allowed_comments = self.request.get_signed_cookie('allowed_comments', default=None) if not self.request.user.is_authenticated: if existing_allowed_comments and str(self.object.pk) not in \ existing_allowed_comments: response.set_signed_cookie('allowed_comments', ", ".join([existing_allowed_comments, str(self.object.pk)]) elif not existing_allowed_comments: response.set_signed_cookie('allowed_comments', self.object.pk return response method should add pk of created objects to signed cookies in case user is not authenticated. self.get_object() doesn't work as well – 404 -
Django App - Brand New Car Calculator - SQL or OOP structure?
I'm writing web app in Django 2 - brand new car calculator. I don't know which data structure to choose - relational or object oriented database. It is well known solution where you choose first model, then type (sedan, combi, etc.), color. The problem occure when you choose engine, transmission (automatic, manual) equipment, extra packages. As you know there is so many options and not all are possible to choose. For example, you can't choose 1.0 petrol engine with automatic transmission and four-wheel drive. My first choice was object-oriented programming with inheritance but I can't find how to limit options in subclasses. Any of you did run simmilar project? best regards -
How to have the functionality of FileField's "upload_to" parameter without actually uploading anything?
I have a model like this: class Sample(models.Model): audio = models.FileField() that I instantiate in the view like this: sample = Sample() sample.audio = 'audio/sample.mp4' However, I would like to avoid having to provide the audio/ part of the filepath in the view whenever I create an object of this class, and have it defined in the model instead. I could add upload_to parameter like this: class Sample(models.Model): audio = models.FileField(upload_to='audio') but it will only work when something is actually uploaded, which is not my case. My files will already sit in the 'audio' folder. How can I avoid providing such full path for a media file whenever I create an object from model? -
django error: django.urls.exceptions.NoReverseMatch
I am creating a stock management system for my company. I don't know why the error: NoReverseMatch keeps coming for item_edit and item_delete views or urls. Because of these errors, I am not able to comple my CRUD views and modify or delete a exisiting item. The Error: "django.urls.exceptions.NoReverseMatch: Reverse for 'stock_management.views.item_edit' not found. " I have already tried going through my code a lot of time. I have also tried calling reverse() function for item_edit and item_delete from the shell and I also have also tried to manually enter the URLs in the browser but still the same error keeps showing. My models: class Item(models.Model): GOLD_PURITY_CHOICES = ( ... ) COLOUR_CHOICES = ( ... ) DIAMOND_PURITY_CHOICES = ( ... ) RATING_CHOICES = ( ... ) code = models.CharField(max_length=25, db_index=True, unique=True) gold_purity = models.CharField( max_length=3, choices=GOLD_PURITY_CHOICES, default='14K') labour = models.PositiveIntegerField() certification_no = models.CharField(max_length=35, null=True, blank=True) diamond_colour = models.CharField( max_length=4, choices=COLOUR_CHOICES, default='F') diamond_purity = models.CharField( max_length=10, choices=DIAMOND_PURITY_CHOICES, default='IF') rating = models.CharField( max_length=3, default='A', choices=RATING_CHOICES) gross = models.DecimalField(max_digits=6, decimal_places=3) image = models.ImageField(blank=True, null=True, upload_to=user_directory_path) def __str__(self): ... class Color(models.Model): item = models.ForeignKey( Item, on_delete=models.CASCADE, related_name='colors', help_text='Item to which the colors belong.') shade = models.DecimalField(...) price = models.IntegerField(...) class Diamond(models.Model): item = models.ForeignKey( … -
django models - Avoid possible circular reference in database design
I have a database design and relationships problem and I am concerned with possible circular references. To give an example, Jack has on his stock Medicines A, B and C. Medicines A and B have an active_ingredient AI1 and medicine C has an active_ingredient AI2. Jack goes to the doctor, who prescribes him AI1. For the Prescription object, it is indifferent if he takes Medicine A or B. Here is an example code: class ActiveIngredient(models.Model): ... class Medicine(models.Model): quantity = models.IntegerField() active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE) class Person(models.Model): ... class PersonStock(models.Model): customer = models.ForeignKey("Person", on_delete=models.CASCADE) medicine = models.ForeignKey("Medicine", on_delete=models.CASCADE) expiration_date = models.DateField() class Prescription(models.Model): ... quantity = models.IntegerField() What is the best solution to model this relationship? Changing Prescription to this: class Prescription(models.Model): ... customer = models.ForeignKey("Person", on_delete=models.CASCADE) active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE) quantity = models.IntegerField() Seems wrong to me given that there is the PersonStock class already connecting Person and Medicine. -
Some static files get 404
The question about static files seems to asked a lot. I don't find any about some files working though. I just got around fixing with favicons. First I added one favicion.ico. All godd and all working nice and all. Then I wanted to add more favicons with different sizes, for reasons. So I add a bunch of favicons-nnXnn.png and link tags for each. But these doesn't seem to work. I get 404 on them. I have deployed in production server. Running gunicor and nginx. I see the files in my static folder, both the one that work and the newer ones. How can some work and others don't? -
WhatsApp does not show image thumbnail for website
I followed all steps mentioned in these top-voted answers: https://stackoverflow.com/a/43154489/8407719 https://stackoverflow.com/a/32154775/8407719 This is a sample code in my base.html template in my Django Application deployed on Heroku: <meta property="og:site_name" content="Website Name"> <meta property="og:title" content="Website Name"/> <meta property="og:url" content="https://my-app-name.herokuapp.com/"/> <meta property="og:image:secure_url" itemprop="image" content="https://i.ibb.co/ZXV6r3Z/logo-large.png"> <meta property="og:description" content="Website Description"> <meta property="og:type" content="website" /> <meta name="author" content="Author name"> From the browser Inspector I have confirmed that these tags are being loaded in the DOM but still no image thumbnail for my website URL appears in Whatsapp. Please help me solve the problem. -
How to Pass Multiple Parameters in One Query String
I want to stack my query parameters on top of each other like: somesite.com/?param1=value1&?param2=value2 etc But I've got different forms I want to use on the same website. I have a form for querying posts, but when I want to go to a second page of those filtered results through another form for pagination the url rewrites the query with ?page=x. First form: ... <form class="form-inline my-2 my-lg-0" action="/posts/"> <input class="form-control mr-sm-2" type="text" name="q" placeholder="Search" autofocus aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> ... Second form: ... {% if is_paginated %} <nav> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="#"><span>Previous</span></a></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="page-item active"><a class="page-link" href="#">{{ i }} <span class="sr-only">(current)</span></a></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">Next</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="#"><span>Next</span></a></li> {% endif %} </ul> </nav> {% endif %} ... -
Django migrations failing on 2.2.1
Upgraded to Django 2.2.1 and a python manage.py migrate now fails, whenever I introduce even the simpler change: Migrations for 'model_name': Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/path/to/virtualenv/lib/python3.7/site-packages/migrate_sql/management/commands/makemigrations.py", line 137, in handle self.write_migration_files(changes) File "/path/to/virtualenv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 196, in write_migration_files writer = MigrationWriter(migration, self.include_header) AttributeError: 'Command' object has no attribute 'include_header' With previous version 2.0.x everything was OK, is there something obvious to anyone else missing? -
IntegrityError (news_post.hashTag may not be NULL)
I am deploying my web site, which is written in Django==1.8 and Python==3.6. When I firstly created a model of the project I added a column named hashtag to the table Post, so after removing this column, my Post model class looks like below: class Post(models.Model): league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='$ club = ChainedForeignKey( Club, chained_field='league', chained_model_field='league', show_all=False, ) player = ChainedForeignKey( Player, chained_field='club', chained_model_field='club', show_all=False, ) title = models.CharField(max_length=255) body = models.TextField(max_length=4000) img = models.ImageField() created_at = models.DateTimeField(auto_now_add=True) created_by = UserForeignKey(auto_user_add=True, verbose_name='The user that is automatically assigned', related_name='posts') As you can see there is no column named hashtag. Whenever I want to add a post to my website, it says IntegrityError at /admin/news/post/add/ news_post.hashTag may not be NULL Request Method: POST Request URL: http://68.183.188.14:8000/admin/news/post/add/ Django Version: 1.8 Exception Type: IntegrityError Exception Value: news_post.hashTag may not be NULL Exception Location: /home/firdavsbek/futbik_version_7/djangoen/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 318 Python Executable: /home/firdavsbek/futbik_version_7/djangoen/bin/python Python Version: 3.6.8 Python Path: ['/home/firdavsbek/futbik_version_7', '/home/firdavsbek/futbik_version_7/djangoen/lib64/python36.zip', '/home/firdavsbek/futbik_version_7/djangoen/lib64/python3.6', '/home/firdavsbek/futbik_version_7/djangoen/lib64/python3.6/lib-dynload', '/usr/lib64/python3.6', '/usr/lib/python3.6', '/home/firdavsbek/futbik_version_7/djangoen/lib/python3.6/site-packages'] Server time: Вт, 28 Май 2019 20:35:54 +0500 but there is not a column as you have seen before... What I did is just python manage.py makemigrations news(this is my app name) and python manage.py migrate, that's it! I cannot … -
How to make a custom filter on FileField in Django admin
In Django admin, I upload a csv file to create model objects. This file uploading should get done hundreds times per day by people downloading csv files from another website with the same file name, which means it's very easy to make mistakes. The custom filter that I want is to check the first line where a store name exists with an object's name where I upload the csv file on. After uploading the file, if the file has an unmatched store name, Django admin doesn't let me submit the csv file. I'm confused where I can start for that. Can anyone give me an idea? models.py class Store(TimeStampedModel): ... name = models.CharField(unique=True, max_length=40) similar_stores_file = models.FileField(blank=True, null=True) admin.py def save_model(self, request, obj, form, change): csv_file = form.cleaned_data['similar_stores_file'] if csv_file and 'similar_stores_file' in form.changed_data: lines = file_data.split("\n") for line in lines: # Check the first line to match the name -
Django Channels: Consumer object has no attribute "channel_name"?
When assigning the consumer to a group following the Django-Channels docs I get an error of " 'LabConsumer' object has no attribute 'channel_name' ". Where should I get 'channel_name' from? I tried specifying a "self.channel_name = 'admin_channel'" manually and the error disappears, but sending a message to the group 'admin' does not work. consumers.py from channels.generic.websocket import JsonWebsocketConsumer from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from django.core.serializers.json import DjangoJSONEncoder import json class LabConsumer(JsonWebsocketConsumer): channel_layer_alias = "admin" def fetch_progress(self, data): self.send_json(self.get_progress()) commands = { 'fetch_progress': fetch_progress, } def connect(self): self.channel_layer = get_channel_layer() self.lab_number = self.scope['url_route']['kwargs']['code'] async_to_sync(self.channel_layer.group_add)('admin', self.channel_name) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)("admin", self.channel_name) def receive(self, text_data): data = json.loads(text_data) print('received ') self.commands[data['command']](self, data) def get_progress(self): obj = LabProgress.objects.filter(code_id=self.lab_number).values() obj = json.dumps(list(obj), sort_keys=True, indent=1, cls=DjangoJSONEncoder) return obj settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } Any help in correctly specifying groups in consumers or finding the 'channels_name' would be appreciated. -
Uncaught ReferenceError: M is not defined in materialize
I am trying to use Toast Messages in Materialize and django but I keep getting an error: Uncaught ReferenceError: M is not defined I have tried typing Materialize instead of M. I am using Materialise v1.0.0 M.toast({html: 'I am a toast!'}) -
Use variable inside __init__ to outside __init__
I want to use variable inside def__init__ to outside def__init__. This is my def__init__ in my class : class UserResponseSearchForm(forms.Form): def __init__(self, *args, **kwargs): qry = kwargs.pop('qry') super(UserResponseSearchForm,self).__init__(*args, **kwargs) I want to use variable qry in outside def__init__ like this : class UserResponseSearchForm(forms.Form): def __init__(self, *args, **kwargs): qry = kwargs.pop('qry') super(UserResponseSearchForm,self).__init__(*args, **kwargs) gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(gejala__icontains = qry).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) I use variable qry in gejala__icontains = qry like this filter(gejala__icontains = qry) And it return name 'qry' is not defined. What the problem with that? And how to use the qry variable? Hope anyone can help me. -
return same product with multiple id
Right now I'm returning a product by passing a code over url class Product(APIView): def get_product(self, code): try: prod = ProductModel.objects.get(code=code) return prod except Product.DoesNotExist: raise Http404 def get(self, request, code, format=None): product = self.get_product(code) serializer = ProductSerializer(product) return Response(serializer.data) url path('product/<code>/', views.Product.as_view()), this will return product if it's in the database, simple stuff but now I've added a JSON field in the ProductModel with multiple codes ["05017303032619", "05017303032626"] so how can I return a product with multiple code? -
Unable to perform any operations on a django-app-model deployed on heroku
Developed an API having one module(task) which works on local server. Since I deployed it on Heroku with same database and records, which i'm able to access through bash, but unable to perform any of the CRUD operation on database model(Task) through API endpoints. (task) refers to app/module directory (Task) refers to model models.py class Task(models.Model): title = models.CharField(max_length=64) check = models.BooleanField(default=False) date_to_do = models.DateField(default='2019-05-26', null=True, blank=True) timestamp = models.DateTimeField(auto_now=True, null=True, blank=True) views.py def post(self, request, *args, **kwargs): data = request.body valid_json = is_json(data) if not valid_json: json_data = json.dumps({'msg': 'Invalid JSON data'}) return HttpResponse(json_data, content_type='application/json', status=400) task = json.loads(data) form = TaskForm(task) if form.is_valid(): form.save(commit=True) json_data = json.dumps({'msg': 'Saved Successfully'}) return HttpResponse(json_data, content_type='application/json', status=200) if form.errors: json_data = json.dumps(form.errors) return HttpResponse(json_data, content_type='application/json', status=400) Error ProgrammingError at /admin/task/task/add/ relation "task_task" does not exist at LINE 1: INSERT INTO "task_task" ("title", "check", "date_to_do", "ti... ^ -
urlpatterns return the value of very first function
I just started to learn Python Django Webpage development. My plan was to show the current time and window service status in my page. I have two functions in my views.py and urlpatterns refers these two functions in urls.py Whenever i run the server, the very first url only showed in my page. views.py: from django.shortcuts import render from django.http import HttpResponse import psutil, datetime def winservice(request): servicename = psutil.win_service_get('BrokerAgent') service = servicename.as_dict() if service['status'] == 'running': return HttpResponse("<h2>Hey Citrix is Up and Running .. </h2>") def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.current_datetime, name ='current_datetime'), url(r'^winservice$',views.winservice,name ='winservice'), ] Expected Result: Page should contains Current time. Status of my service.