Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + nginx + uwsgi how to configure subdomain
I have Django project with one app and it is available on app.amzkpis.com I've created new app in the same project and I need it be available on amzkpis.com How to correctly configure nginx for that? My nginx and uwsgi configs look like this now: server { server_name app.amzkpis.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/amz/AMAZON_SITE/; } location / { include uwsgi_params; uwsgi_pass unix:/var/www/amz/AMAZON_SITE.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/app.amzkpis.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/app.amzkpis.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { server_name amzkpis.com; listen 80; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/amz/AMAZON_SITE/; } location / { ??? } # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/amzkpis.com-0001/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/amzkpis.com-0001/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = app.amzkpis.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name app.amzkpis.com; return 404; # managed by Certbot } server { if ($host = amzkpis.com) { return … -
Django on AWS Ubuntu can’t see manage.py
from django.shortcuts import render import json, sys, os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(BASE_DIR, 'imecaff_logic')) try: os.chdir(os.path.join(BASE_DIR, 'imecaff_logic')) except OSError: print("Can't change the Current Working Directory") from imecaff_logic import main as logic_main I installed Django on AWS Ubuntu. everything works. But when i’m trying to connect it with my parser I got MISTAKE. Then I import main.py file from another folder(from imecaff_logic import main as logic_main). (env_imecaff) ubuntu@ip-172-31-33-221:~/imecaff/imecaff_local$ python manage.py runserver 0.0.0.0:8000 manage /home/ubuntu/imecaff/imecaff_local manage /home/ubuntu/imecaff/imecaff_local Performing system checks... views1 /home/ubuntu/imecaff/imecaff_local/imecaff_logic Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.main(self.inner_run, None, options) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/utils/autoreload.py", line 323, in main python_reloader(wrapped_main_func, args, kwargs) File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/utils/autoreload.py", line 302, in python_reloader reloader_thread() File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/utils/autoreload.py", line 274, in reloader_thread change = fn() File "/home/ubuntu/imecaff/env_imecaff/lib/python3.5/site-packages/django/utils/autoreload.py", line 204, in code_changed stat = os.stat(filename) FileNotFoundError: [Errno 2] No such file or directory: ‘manage.py' On local on my Mac and PC the same code works … -
Static Files would not load in Django (Pycharm)
I am currently making a Web App using the Django framework and have just started recently. I looked through the Django Documentation and also looked through many tutorials and other answers on StackOverflow but none of them seem to work. When I first placed the link on the HTML page I included the {% static 'my_app/css/cssFile'%}and also included {% load staticfiles %}. I have also tried including this into my settings file: STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static'])) but none of these work. Every time I try to run the server, the console keeps saying that the server could not find the resource and that it exited out as a 404. This is my settings file: """ Django settings for WebApp project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import posixpath # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6-_^kvfdcg&@+_gdf1ub*ood*$fm4vs1m-aw_uw#(2tliu9(d0' # SECURITY WARNING: don't run with debug turned on in … -
How to fix error 500 from query None
I want to list related categories saved on a db field called "related" my code: def category(request, slug): related = Article.objects.filter(slug__icontains=slug).values('related').first() return render(request,'category.html',{'related':related} y try with: option 1: In case of return a None on related i assign only the category Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)) option 2: if related is None: related = Article.objects.filter(category__icontains=slug).values('category').first() else: relateds = related.get('related').split(',') error: 'NoneType' object has no attribute 'get' on my db i check with query: SELECT * FROM `article` WHERE slug like '%internet%' And i get 0 records, so the error is coherent But i dont see how to assign in that case SELECT * FROM `article` WHERE category like '%internet%' where i have 22 results model: class Article(models.Model): category = models.CharField(max_length=2000, blank=True, null=True) related = models.CharField(max_length=2000, blank=True, null=True) text = models.CharField(max_length=2000, blank=True, null=True) slug= models.SlugField(max_length=255, unique=True) class Meta: managed = False db_table = 'article' def __str__(self): return u'%s %s %s %s' % (self.categoria,self.related, self.text, self.slug) -
Set authenticated user as value in Foreign key field before create an object using ModelSerializer with DRF
I'm trying to implement a simple endpoint to create an object using the ModelSerializer of Django rest framework. My model has a Foreign key to the User model, and I need set this value in the endpoint post functionality. Working with forms in Django, you can add commit=false to the save method in the post, set the attribute (instance.user = self.request.user) and after that create the instance using the save() method. But, I can't find a clear and clean way to do it using Djago Rest Framework serlializaer. This is my model. class Ticket(models.Model): images_quantity = models.PositiveSmallIntegerField() status = models.PositiveSmallIntegerField( choices=TICKET_STATUS_CHOICES, default=PENDING_TICKET, ) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) created_at = models.DateTimeField( auto_now_add=True, ) So, as you can see, there is a foreign key to the User model. In my post endpoint, this value must be filled with the authenticated user. Take a look to the serializer: class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket fields = ('images_quantity',) User only must to send images_quantity field value. So I need to create a new instance of the Ticket model, and set the authenticated user id as the value in the created_byfield. This is my view: class TicketFormView(APIView): def post(self, request, format=None): serializer … -
Django 2.1 and Python 3.7: KeyError: 'django' when running Apache2 mod_wsgi and other issues
I'm coming to you after so many hours trying to figure out why my django setup does not work anymore. I swear to whatever God you want I did not sleep last night because of it. I wanted to switch from Python 3.5 to Python 3.7 because I started to use f-strings, and as this feature was available from Python 3.6, I was like why not using directly Python 3.7. Also, I wanted my 2 domains (mywebsite.fr and mywebsite.com) to point to the same django project. No issue with only mywebsite.fr until now. I will try to explain as precisely as I can to you what I have done to obtain this hideous code below: My install is on Ubuntu 16.04, I did some mess with Python versions natively installed on my Ubuntu setup. I finally succeeded in installing properly (I think) Python 3.7, I really struggled configuring/making/installing the appropriate mod_wsgi, I use venv for my django setup (called m2gvenvprod below), I am using mod_wgsi and its daemon mode associated, With everything I read, I am sure my conf in apache2 for each of those website/domains are correct (in sites-available), And here I am, with the apache2 error.log below, after … -
How to get an input from a base template in Django?
I would like to have a little text area in which people can write something and immediately post it to the database. So, I need a way to manage an input from a base template. I know how to do this with normal templates, but I can't figure out how to do it with the base template without writing the same process in every child template of my project. I have already heard of template processors, but my problem is that I don't want to pass a variable to the base template, but to take it from the base template. Thank you very much in advance. -
How to compare Django template language variables with javascript variables?
I've got something like this in my Django template: <script> var selected_direction = $("#id_direction").val(); {% for bus_stop in bus_stops %} {% if bus_stop.direction == selected_direction %} // Do something // {% endif %} {% endfor %} </script> I can do everything with bus_stops until it reaches the {% if %} statement. How can i compare javascript variable with django variable? -
How to order Django Tables2 column by model property that depends on outside model query
Say I have two models, one with a property: class Name(models.Model): name = models.CharField() class Name_ID(models.Model): name_id = models.IntegerField() @property def object_name(self): try: return Name.objects.get(id=self.name_id) except Name.DoesNotExist: return '' Then I try making a table using django-tables2 for the Name_ID model only: class NameIDTable(tables.Table): object_name = tables.Column() class Meta: model = Name row_attrs = {'data-id': lambda record: record.pk} exclude = ('name_id',) attrs = {'class': 'table table-striped', 'style': 'display: block; overflow: auto;'} The table successfully shows the object_name column with all of the values from the property. However, when I try clicking on the column header for it so I can order them by name, I get an error because 'object_name' is not an actual field in the Name_ID model. Many of the solutions I found don't work because they assume that you're using fields from the model itself, not queries from outside models. How do you make the table orderable by the object_name property? -
Return Zip file with HttpResponse using StringIO, Django, Python
I'm trying to return a zip file with HttpResponse, using StringIO() because i'm not storing in DB or Harddrive. My issue is that my response is returning 200 when i request the file, but the OS never ask me if i want to save the file, or the file is never saved. i think that the browser is reciving the file because i have seen on the Network Activity (inspect panel) and it says than a 6.4 MB file type zip is returned. I'm taking a .step file (text file) from a DB's url, extracting the content, zipping and returning, that's all. this my code: def function(request, url_file = None): #retrieving info name_file = url_file.split('/')[-1] file_content = urllib2.urlopen(url_file).read() stream_content = StringIO(file_content) upload_name = name_file.split('.')[0] # Create a new stream and write to it write_stream = StringIO() zip_file = ZipFile(write_stream, "w") try: zip_file.writestr(name_file, stream_content.getvalue().encode('utf-8')) except: zip_file.writestr(name_file, stream_content.getvalue().encode('utf-8', 'ignore')) zip_file.close() response = HttpResponse(write_stream.getvalue(), mimetype="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename=%s.zip' % upload_name response['Content-Language'] = 'en' response['Content-Length'] = write_stream.tell() return response -
Django finding element by reverse relation vs filter function
I am currently working on django project, I am using reverse relationship for finding the element but at same time I can also use filter function. for example models are: class Group(models.Model): #some attributes class Profile(models.Model): group = models.ForeignKey(Group,related_name = profile) #more attributes if I have instance of Group (group) then I could use: group.profile.all() but also: Profile.objects.filter(group=group) What's the difference and which one is more efficient ?? I tried to find on google but unable to get a good solution. What if I am using reverse relationship three to four times to find element? -
Add new variable to DRF Response
I have a working function, I need to add a new variable to it, the value of which will depend on which part of the code is executed. working_code.py class YoutubeAuthView(APIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): ..... some code ..... try: ...some code... try: p = Platform.objects.get( content_type=ContentType.objects.get_for_model(y), object_id=y.id, user=request.user ) except: p = Platform(user=request.user, platform=y, description=description) except Youtube.DoesNotExist: p = Platform(user=request.user, platform=y, description=description) return Response( PlatformSerializer(p, context={'request': request}).data ) Now I add variable NEW class MyAuthView(APIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): ..... some code ..... try: ...some code... try: p = Platform.objects.get( content_type=ContentType.objects.get_for_model(y), object_id=y.id, user=request.user ) except: p = Platform(user=request.user, platform=y, description=description) NEW = False except Youtube.DoesNotExist: p = Platform(user=request.user, platform=y, description=description) NEW = True return Response(?????) How to add right in return Response variable NEW? Something like PlatformSerializer(p, context={'request': request, 'new':new}).data -
Date/Time formatting in Django Template
I have a field that's part of a larger set of data that's being returned from an api and passed to my template as a dictionary. The field is an iso 8601 formatted date. I would like to reformat this to a different, more readable, format. I've tried using the built-in filters, both date and from the humanize filter, naturaltime but neither work. I'm pretty sure this is because the field that's being passed as part of the dictionary is coming through as a string rather than a datetime object. So, is there any way I can change this field to be a datetime object, either in the dictionary or in the template? I thought about creating a custom template filter, would that work or is there a better more elegant way of reformatting this field? -
File Not Found Error Django
Hello im new to django and im trying to make a web app. I have a running back end but the problem is its only running on cli and I have to turn it into a web app. def testing(request): ksize = 6 somsize= 10 csvname="input.csv" testcap = "testing.pcap" pl.csv5("chap/a",testcap) tmparr=[] for filename in os.listdir("chap"): if filename.endswith(".csv"): tmparr.append(filename) continue else: continue tmparr.sort() visual_list = natsort.natsorted(tmparr) csv = sl.opencsv(csvname) norm = sl.normalize(csv) weights = sl.som(norm,somsize) label = sl.kmeans(ksize,weights) #for x in range (2,21): # label = sl.kmeans(x,weights) # print("K is", x, "Score is ", label[1]) lblarr = np.reshape(label,(somsize,somsize)) #sl.dispcolor(lblarr) classess = sl.cluster_coloring(weights,norm,csv) classpercluster = sl.determine_cluster(classess,lblarr,ksize) classpercent = sl.toperc(classpercluster) print (classpercent) #print(classpercluster) for x in visual_list: temp = ("chap/"+x) tests = sl.opencsv(temp) print(tests) hits = sl.som_hits(weights, tests) name = ("img/" + x + ".png") sl.disp(lblarr,name,hits) return render(request,'visualization/detail.html') The system cannot find the path specified: 'chap', I'm not sure if I should put the chap folder inside the templates folder or in the app folder. Thank you in advance! -
Converting a DateTimeField to user timezone without setting USE_TZ
I have a model that has a click_time that is a DateTimeField and my timezone in my settings.py file is set to 'UTC'. I want to display to that admin user the click time in their timezone that is set in their userprofile. Is there a simple way to do this without making the global change to my settings.py file. I think it may have some unintended consequences on the rest of the project. -
Use Taggit-Selectize in Django to autocomplete the tags in User Form outside the Admin
I am using this https://github.com/chhantyal/taggit-selectize which uses django-taggit and selectize.js to add autocompletion of tags in my blog app. I have followed the instructions in the readme file and it works fine in admin. But when I am trying to use it in User form , it is not working. I have used this https://github.com/chhantyal/taggit-selectize/issues/17 to customize my form and have tried using the js and css file almost everywhere in my HTML template as suggested in the above post. But I am not able to get it. <script type="text/javascript" src="/static/taggit_selectize/js/selectize.js"></script> <link href="/static/taggit_selectize/css/selectize.django.css" type="text/css" media="all" rel="stylesheet"/> PS. I am also using Martor Django Editor which uses semantic.js (Mentioning it because it had conflict with few of my JS and bootstrap stuff.) -
Regex - replace non-unicode characters but only in certain patterns
I'm working with Django, trying to autogenerate templates for a whole bunch of links, some of which have non-unicode characters (e.g. é, ç, etc). While putting those characters in filenames seems to work when I'm browsing on my own computer, django does not like it and refuses to render them. I figured a quick solution to this would be to just regex-replace these characters with underscores or something, but only in the urls where Django would otherwise have problems. The string I'm trying to parse - the autogenerated template - looks something like this: desc = """...blah blah blah <a href="{% url 'myproject:do_thing' arg_name='ñôt-unìcodé' %}">Link Text Ñôt Unìcodé</a> blah blah blah ...""" So I want to use regex to change ñôt-unìcodé to __t-un_cod_, while leaving Ñôt Unìcodé untouched. Here's what I've tried: re.findall(r"'arg_name='(([^'])+?)'", desc) I intend for this to give me a parseable list of all the individual characters, which could then be replaced on an individual basis via re.sub: ['ñ', 'ô', 't', '-', 'u', 'n', 'ì', 'c', 'o', 'd', 'é', ...] But instead I end up with the entire string and just the last letter: [('ñôt-unìcodé', 'é'), ...] What am I misunderstanding here? (I've found both parts of this … -
Django Get request returns empty array if I do not duplicate the API endpoint
I have been struggling for the past 2 months with very strange behavior that I can not pin down. One of my django app urls file looks like this: urlpatterns = { path('containers/', GetProductContainers.as_view()), path('delete/<deleteTime>', DeleteProcessedStockTime.as_view()), path('containers/', GetProductContainers.as_view()), path('input/', InsertMultiProcessedStock.as_view()), path('<str:stockT>/', ProcessedStockTimeView.as_view(), name="stockstime"), path('', ProductListDetailsView.as_view(), name="details"), } As you can see, this path path('containers/', GetProductContainers.as_view()), is twice in my urlpatterns. The reason for this is that as soon as I remove one, it returns an empty array. It does not matter which one I remove! If both are there, I get the 319 records that I expect. I can remove ANY one of the two, and it will return an empty array, but as soon as I have 2 it works again. Can anyone think of an explanation for this or how I can even begin to debug it? -
Django and Apache: Start addional thread for MQTT Client
server with an additional mqtt-client. I am using Django and Apache in production. To start my mqqt client, I edited the wsgi.py this is working perfectly, if I am using the development server (python3 manage.py runserver). But its not working in production. Can any help or has an idea how to get this working in production with apache? wsgi.py: import os import threading import logging logger = logging.getLogger('mqtt') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "iot.settings") from iot.settings import MQTT_CONNECTION, MQTT_BROKER if MQTT_CONNECTION: logger.debug('Connecting to Broker...') try: from utils_mqtt_client.mqtt_client import run_client run_client() except Exception as e: logger.debug('Could not conntect to MQTT Broker:\n\t {}'.format(e)) else: logger.debug('Starting without MQTT connection') application = get_wsgi_application() mqqt-client: import json import threading import logging import paho.mqtt.client as mqtt from device.models import Device from value.models import Value from iot.settings import MQTT_BROKER logger = logging.getLogger('mqtt') topics = ['config'] CLIENT = mqtt.Client('webserver') # [...] def run_client(): devices = Device.objects.all() CLIENT.on_connect = on_connect CLIENT.on_message = on_message for device in devices: subscribe(CLIENT, device) CLIENT.connect(MQTT_BROKER) CLIENT.loop_start() -
Send thousands of emails with crontab in django and aws
I have a process where about 1500 mails are sent once a week. The process I have it in a django command that I plan to put in a crontab. The process has a loop in which it is verified if you want to receive emails and the language in which you will receive, like this one: for user in users: # Check if user accept emails if user['send_mail']: # Get language to email lang = "" if user['lang'] == "es": lang = "es" elif user['lang'] == "fr": lang = "fr" else: lang = "en" email = user['email'] # Send email send_mail() It is not much 1500 mails, but I want to leave it scalable, since the amount of mails depends on the number of registered users for the platform. I do not know if it is now scalable or it is better to use redis queue or celery. I am using Amazon Simple Emails Service (SES). -
I am trying to publish a saleor store on AWS and using Apache
I have ran published default django project and it was working fine, I was able to access it with domain name then I just replaced the details for saleor and now I am getting Forbidden error. Here is my conf file: <VirtualHost *:80> ServerAdmin admin@example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/ecom/saleor/saleor/static <Directory /home/ubuntu/ecom/saleor/saleor/static> Require all granted </Directory> <Directory /home/ubuntu/ecom/saleor/saleor/wsgi> <Files __init__.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject2 python-home=/home/ubuntu/ecom/ecom python-path=/home/ubuntu/ecom WSGIProcessGroup myproject2 WSGIScriptAlias / /home/ubuntu/ecom/saleor/saleor/wsgi/__init__.py </VirtualHost> Here /home/ubuntu/ecom is my project main dir and it contains ecom (virtual env) and saleor folders. I have added glintwear.com my domain in settings.py file of saleor project -
Hosting a Django project
I've been working on this Django project and now I am at the stage where I have to think about finding a host for it. I've spoken to a customer service agent from a hosting company and she advised me to get a dedicated server (which is very expensive). Now, I need to know if it's a must that I rent out a dedicated server for my Django project or will Cloud Hosting suffice. What are the variables I should be considering while making this decision. -
Displaying foreign key related tables in Django Admin
I am trying to create properties list and link it to objects. Table : Properties class Properties(models.Model): Property = models.CharField(primary_key=True, max_length=4...... PropetyDesc = models.CharField(max_length= ....... Table : Wood class Wood(models.Model): Name = models.CharField(max_length= ..... Property = models.ForeignKey(Properties, on_delete=models...... At the outset I am trying to use Django Admin's capabilities to see how the DB design stack up. In a nutshell my admin page would look like a GUI for creating a purchase order where the header section will have the order details and in the item line we will have materials: In the instant case, I am trying to put the object (Wood) on the header and in the "TabularInline" being created will have option to choose the properties. class PropertiesInline(admin.TabularInline): model = Properties def get_extra(self, request, obj=None, **kwargs): extra = 1 return extra class WoodAdmin(admin.ModelAdmin): list_display = ('Name', 'Property') fields = ['Name', 'Property'] inlines = [PropertiesInline] admin.site.register(Wood, WoodAdmin) However, I end up getting the following error: ERRORS: <class 'mapp.admin.PropertiesInline'>: (admin.E202) 'mapp.Properties' has no ForeignKey to 'mapp.Wood'. On the other hand, if I were to reverse the scenario like this: class WoodInline(admin.TabularInline): model = Wood def get_extra(self, request, obj=None, **kwargs): extra = 1 return extra class PropertiesAdmin(admin.ModelAdmin): list_display = ('Property', … -
django - automated integer value
I have defined 2 models: Course and Task where are defined in the following way: class Course(models.Model): creator = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=100) archived = models.BooleanField() class Task(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) taskNo = models.IntegerField() title = models.CharField(max_length=100) description = models.TextField(max_length=2000) Here, each Task that is created will belong to a Course. Notice the taskNo in Task model. What I want to achieve is that taskNo should be in sequential order for that particular Course. Look at the below example: There are two Courses A and B. At present both courses have 0 posts. Now, If I add a task to A, then its taskNo should be 1. If I add a task to A, then its taskNo should be 2. If I add a task to B, then its taskNo should be 1. I couldn't find anything online that could help me, so it would be good if you guide me the right way. -
django view and templates are not integrated to urls.py
the url that I am trying to access is blog/2018/08 and blog/2018/08/14. the other urls such as blog/, blog/2018, blog/today, archive/ works well but urls containing month and day are not working. this is my code: blog/urls.py from django.urls import path from blog.views import * app_name = 'blog' urlpatterns = [ path('', PostLV.as_view(), name='index'), path('post/', PostLV.as_view(), name='post_list'), path('post/<slug:slug>/', PostDV.as_view(), name='post_detail'), path('archieve/', PostAV.as_view(), name='post_archive'), path('<int:year>/', PostYAV.as_view(), name='post_year_archive'), path('<int:year>/<int:month>/', PostMAV.as_view(), name='post_month_archive'), path('<int:year>/<int:month>/<int:day>/', PostDAV.as_view(), name='post_day_archive'), path('today/', PostTAV.as_view(), name='post_today_archive'), ] blog/views.py from django.views.generic import ListView, DetailView from django.views.generic.dates import ArchiveIndexView, YearArchiveView, MonthArchiveView, DayArchiveView, TodayArchiveView from blog.models import Post # Create your views here. class PostLV(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDV(DetailView): model = Post class PostAV(ArchiveIndexView): model = Post date_field = 'modify_date' template_name = 'blog/post_archive.html' class PostYAV(YearArchiveView): model = Post date_field = 'modify_date' make_object_list = True template_name = 'blog/post_archive_year.html' class PostMAV(MonthArchiveView): model = Post date_field = 'modify_date' template_name = 'blog/post_archive_month.html' class PostDAV(DayArchiveView): model = Post date_field = 'modify_date' template_name = 'blog/post_archive_day.html' class PostTAV(TodayArchiveView): model = Post date_field = 'modify_date' template_name = 'blog/post_archive_today.html' all the templates I got is mentioned in views.py! thank you so much