Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run midee doctr on specific area of image?
I am using below code to extract text from image with mindee/doctr package. from doctr.models import ocr_predictor from doctr.io import DocumentFile import json model = ocr_predictor( reco_arch='crnn_vgg16_bn', pretrained=True,export_as_straight_boxes=True) image = DocumentFile.from_images("docs/temp.jpg") result = model(image) result_json = result.export() json_object = json.dumps(result_json, indent=4) with open("temp.json", "w") as outfile: outfile.write(json_object) result.show(image) By using the mindee/doctr I got whole text form image in temp.json file. output after ocr I want to get text of specific area from the image. I don't have good approach to achieve that can someone help me to get out of it ? -
Django project deployment with Jenkins on AWS EC2 Instance
I have a Django project. Now I want to publish my project on AWS EC2 instance with Ubuntu AMI. To publish it, I want to use Jenkins as CI/CD pipeline. I really dont know what are the steps to deploy using Jenkins in AWS. I used normal project to publish it but suing Jenkins to deploy the project is problematic for me. But it is quite helpful than docker build as far I checked -
Django model update multiple instances with custom Manager function
I have a model class (for example A) inside the Django model framework. For this model I have created his Manager class with some functions. class T_Manager(BaseModelManager): def add_function(value): .... class T(BaseModel): objects = T_Manager() .... class A(BaseModel): t = GenericRelation('T', related_name='t') .... Now I have a list of A class objects and I would like to call add_function on all of them efficiently. I would like to use something like list_a.update(F('add_function', value)) or something like this. Is there a way to call this function inside the update function or what is recommended way to do this? -
Django models update multiple instance with foreign key objects in one transaction
In Django project I have three models: class First(BaseModel): ..... class A(BaseModel): b = models.OneToOneField('B', null=True, blank=True, related_name='B%(class)s', on_delete=models.PROTECT) first = models.ForeignKey('First', related_name='a_list', on_delete=deletion.PROTECT) class B(BaseModel): some_value = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True) Inside one function, I would like to update the list of objects A with one transaction (so that I don't hit DB with multiple queries and updates). I tried something like this: first = First.objects.get(pk=id) list_a = first.a_list.filter(...).select_related('b') list_a.update(b__some_value=10) The problem is that I get the error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/models/options.py", line 608, in get_field return self.fields_map[field_name] KeyError: 'b__some_value' During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 2423, in ... resp = mview.post(self.get_url(), data=data, format='json') .... File "/usr/local/lib/python3.7/site-packages/django/db/models/options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: A has no field named 'b__some_value' Does anyone know why I get this error or how to achieve the same results? -
How do I run ASGI alongside WSGI on Heroku with NGINX, Django, uWSGI, and Daphne?
Something is wrong with nginx start up and connecting to websockets but I'm having trouble figuring out how to solve it. Looking at the heroku logs, the Daphne process end up getting an error "CRITICAL Listen failure: Couldn't listen on unix:/tmp/nginx.socket:48560: [Errno -2] Name or service not known." And the web process just keeps printing "buildpack=nginx at=app-initialization" every second. Here is my code: Procfile: release: python manage.py migrate web: bin/start-nginx-debug uwsgi uwsgi.ini daphne: daphne my_project.asgi:application --port $PORT --bind unix:/tmp/nginx.socket -v2 worker: celery -A my_project worker -l info nginx.conf.erb: daemon off; # Heroku dynos have at least 4 cores. worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>; events { use epoll; accept_mutex on; worker_connections <%= ENV['NGINX_WORKER_CONNECTIONS'] || 1024 %>; } http { gzip on; gzip_comp_level 2; gzip_min_length 512; gzip_proxied any; # Heroku router sends Via header server_tokens off; log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id'; access_log <%= ENV['NGINX_ACCESS_LOG_PATH'] || 'logs/nginx/access.log' %> l2met; error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %>; include mime.types; default_type application/octet-stream; sendfile on; # Must read the body in 5 seconds. client_body_timeout 5; # upstream for uWSGI upstream uwsgi_app { server unix:///tmp/nginx.socket; #unix:/app/my_project/uwsgi_app.sock; # } # upstream for Daphne upstream daphne { server unix:///tmp/nginx.socket; #unix:/app/my_project/daphne.sock; } server { listen <%= ENV["PORT"] %>; server_name _; keepalive_timeout … -
chatbot using python, django, openai, speech recognition
I have implemented virtual assistance using speech recognition,openai,pyttsx3.it's working on console, I want to create a web app using django. console result -
Upload KML data from Google Earth to django Models
I have a model class Area(models.Model): name = models.CharField(max_length = 255) point = postgis.PointField(null = True, blank = True) area = postgis.MultiPolygonField(null = True, blank = True) I have a kml file which consist of different areas and I want to upload it into this model so later I can add the foreign key of the area in other table How to do that? -
Django - solving a possible n + 1 problem
One of my views is hitting the db a lot with a particular query. Scout-apm identifies it as a possible n+1 query. I'm not sure that is the problem, but it is a problem nonetheless. My original code was: models.py class Grade(models.Model): score = models.CharField(max_length=4, blank=True) testing = models.ForeignKey(Testing, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) classroom = models.ForeignKey(Purpose, on_delete=models.CASCADE) time_created = models.DateField( auto_now=False, auto_now_add=False, default=timezone.now) Class Testing(models.Model): name = models.CharField(max_length=20, blank=True) omit = models.BooleanField(default=False) Class Classroom(models.Model): name = models.CharField(max_length=20, blank=True) views.py def allgrades(request, student_id): classrooms = Classroom.objects.all() for c in classrooms: q = Grade.objects.filter( student=student_id, classroom=c.id, testing__omit="False").order_by('-time_created') if q.exists(): if len(q) < 3: qn = q.first() else: .... The offending queries come from the if q.exists(): and qn = q.first(). I don't know if this falls in the category of n + 1, but the number of queries decreases from around 1300 to around 400 if I get rid of the if q.exists(): and qn = q.first() I need the functionality of these statements. Since I'm doing something with q, I need to check that it exists. And as the code shows, I may want to only include the newest object. Is there a less expensive way to deal with this? -
How do I create multiple lines in my string for my Blog site?
from django.conf import settings from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Title: {self.title}\nBlog: {self.text}" I introduced the f-string format and attempted to utilize the "\n" method but the output is still on same line when I run my server. -
I am getting "Incorrect type. Expected pk value, received str." using fk in drf
This is my model. class Counter(models.Model): userid = models.ForeignKey(Identification,related_name="userName",verbose_name=_("User ID"), on_delete=models.CASCADE, null=True) counter = models.IntegerField(_("Counter"), blank=True, null=True) date_and_time = models.DateTimeField(_("Date and Time"), default=timezone.now) def __str__(self): return str(self.counter) This is my serializer. class Message_Counter_Serializer(serializers.ModelSerializer): userid = serializers.SlugRelatedField( slug_field='userName', queryset=Identification.objects.all() ) class Meta: model = Counter fields = '__all__' This is my View class Counter_Viewsets(errorhandler, viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasResourceScope] serializer_class = Message_Counter_Serializer def get_queryset(self): return Counter.objects.all().filter(userid__user_name=self.request.user) ** This is my Post Request:** { "counter": "2", "userid": "yasmin" } -
Can not get validation during json deserialization with django rest framework
I am working on a django application that fetch data from an API. The json I get looks like this : { "id":"game_id", "players":{ "white":{ "user":{ "name":"player1", "id":"player1" }, "rating":11, "stars":58 }, "black":{ "user":{ "name":"player2", "id":"player2" }, "rating":10, "stars":52 } } } I am trying to deserialize it to insert data in a "game" database : class User(models.Model): id = models.CharField(primary_key=True, max_length=100) name = models.CharField(max_length=100) class Game(models.Model): id = models.CharField(primary_key=True, max_length=15) white = models.ForeignKey(User, related_name="white_id", on_delete=models.CASCADE) white_rating = models.IntegerField() white_stars = models.IntegerField() with the following serializers : class PlayersSerializer(serializers.BaseSerializer): def to_internal_value(self, data): white = data.get("players").get("white") white_id = white.get("user").get("id") white_rating = white.get("rating") white_stars = white.get("stars") return {"white": white_id, "white_rating": white_rating, "white_stars": white_stars} class GameSerializer(serializers.ModelSerializer): white = PlayersSerializer() white_rating = PlayersSerializer() white_stars = PlayersSerializer() class Meta: model = Game fields = ["id", "white", "white_rating", "white_stars"] When in the view file I check GameSerialization.is_valid(data), I get the following error: {'white': [ErrorDetail(string='This field is required.', code='required')], 'white_rating': [ErrorDetail(string='This field is required.', code='required')], 'white_stars': [ErrorDetail(string='This field is required.', code='required')]} -
Django ModelSerializer is receiving an empty set for the context
When I am passing the context via DRF the serializer is getting an empty set it seems. When I look at what self.context prints, it is "{}". End goal with all of this is to be able to 1. filter nested serializers based on context data and 2. pass context data in nested serializers. Here is my view: @api_view(['POST']) @permission_classes([IsAdminUser]) def unitUpdate(request, pk): request.data._mutable = True request.data['tenant'] = request.user.tenant unit = Unit.objects.filter(unit_id = pk,tenant=request.user.tenant) context = {'request': request} serializer = UnitSerializerCreate(instance=unit, data=request.data,context=context) if serializer.is_valid(): serializer.save() return Response(serializer.data) Here is my Serializer class UnitSerializer(serializers.ModelSerializer): rooms = serializers.SerializerMethodField('get_rooms') #filter(tenant=self.context['request'].user.tentant) def get_rooms(self, obj): print(self.context) room_instances = Room.objects.filter(tenant=self.context['request'].user.tenant) return RoomSerializer(room_instances, many=True) return None class Meta: model = Unit fields = ['unit_id','unit_name','description','rooms','tenant'] Have tried many different ways of passing context and even passing in statically defined dictionaries but they always come out as empty sets -
django utf-8 urls works on local but not working on production
i have a django project that on local the urls are ok and opens normally but on live server the utf-8 urls get 404 error here is my urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import re_path from .views import law_list, law_detail, post_detail, category_detail app_name = 'book' urlpatterns = [ re_path(r'^$', law_list, name='law_list'), re_path(r'^(?P<law_id>\d+)/$', law_detail, name='law_detail'), re_path(r'^(?P<law_id>\d+)/(?P<law_slug>[-\w]*)/$', law_detail, name='law_detail_slug'), re_path(r'^categories/(?P<category_id>\d+)/$', category_detail, name='category_detail'), re_path(r'^categories/(?P<category_id>\d+)/(?P<category_slug>[-\w]*)/$', category_detail, name='category_detail_slug'), re_path(r'^posts/(?P<post_id>\d+)/$', post_detail, name='post_detail'), re_path(r'^posts/(?P<post_id>\d+)/(?P<post_slug>[-\w]*)/$', post_detail, name='post_detail_slug'), ] # Add the following lines to serve static files if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) thanks i tried to add allow_unicode = true to settings.py but it didnt work! -
For Django project (using VS Code), dynamic images not loading. Possible issue with baseURL
I've started a Django project based off of a tutorial. I didn't use the "Travello" files for the tutorial...set up something simple for myself. There's data defined on Views.py for title, description, images for courses. It should populate containers in a row on homepage. Everything is getting populated but the images are not coming up with this code: ```<img src="{{ baseURL }}/{{ course.image }}" alt="Course Pic" class="img-fluid"/>``` But in the same code I tested using static image and that image shows. I tried different images including same one as in dynamic code. All work in static version. But weirdly for static code the "alt" tag is what I have for dynamic. Here's the full loop: ``` {% for course in courses %} <div class="col-md-3 bg-aqua"> <div class="p-1"> <img src="{{ baseURL }}/{{ course.image }}" alt="Course Pic" class="img-fluid"/> {% if forloop.counter == 2 %} <img src="{% static 'home/img/Dalle1.jpg' %}" alt="Testing" class="img-fluid" /> {% endif %} </div> <div class="fs-3"> <span> {{ course.name }} </span> </div> <div> <span> {{ course.description }} </span><br/> <span> Start Course-1 $ {{ course.price }} </span><br/> </div> </div> {% endfor %} ``` The if/endif is what I added to test the static link and the image populates in 2nd column … -
Django. Can't get absolute url
I need a link to supplier_data for logged in supplier. Can't get it with any method. I get empty element. Model: class Supplier(models.Model): id = models.IntegerField(primary_key=True) company_name = models.OneToOneField(User, max_length=120, on_delete=models.CASCADE) currency = models.CharField('Currency', max_length=4) legal_form = models.CharField('Legal form', max_length=100, choices=legal_form_options, default='Sole proprietorship') accounting_standards = models.CharField('Accounting standards', max_length=100) owner_structure = models.CharField('Owner structure', max_length=100) industry_sector = models.CharField('Industry sector', max_length=100, choices=industry_sector_options, default='Advertising') date_of_establishment = models.DateField('Date of establishment', default=date.today) start_up = models.CharField('Start-up', choices=start_up_options, default='No', max_length=4) email_address = models.EmailField('Email address') web = models.URLField('Website address') def get_absolute_url(self): return reverse('supplier_data', args=[self.id]) View: def all_suppliers(request): supplier_list = Supplier.objects.all() return render(request, 'all_suppliers.html',{'supplier_list': supplier_list}) def supplier_data(request, id): supplier_list = get_object_or_404(Supplier, pk=id) return render(request, 'all_suppliers.html',{'supplier_list': supplier_list}) Url: path('supplier_data/<int:id>', views.supplier_data, name="supplier_data"), Html: {% for supplier in supplier_list %} <a id=link href="{% url 'supplier_data' supplier.id %}">Supplier data</a> {%endfor%} I spent about one week trying with get_absolute_url method and without it... many things... Thanks for taking a look at this. -
Graphs are not sorting according to Dash table
I'm creating a Dash table where data will be shown according to the date selected by a date picker. There will be several bar figures below the table which will be updated according to the table. I've followed the official documentation of sorting, and filtering examples of Dash table. But for some reason, the figures are not updating properly when the table is updated (e.g. sorting, filtering, etc.). Here's the code: from dash import dash_table, dcc, html from datetime import date from dash.dependencies import Input, Output from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc import pandas as pd df = pd.read_csv('owid-covid-data.csv') df = df[['location', 'new_cases', 'new_cases_per_million', 'total_cases', 'total_cases_per_million', 'continent', 'date']].copy() df['id'] = df['location'] df.set_index('id', inplace=True, drop=False) app = DjangoDash('Cases', external_stylesheets=[dbc.themes.LUX]) selected_date = '2021-01-01' initial_date = df[df['date'] == selected_date] app.layout = html.Div(className='w-75 mb-3', children= [ dbc.Card( [ dbc.CardBody( dcc.DatePickerSingle( id='date-picker', min_date_allowed=date(2020, 1, 1), max_date_allowed=date(2023, 3, 1), initial_visible_month=date(2021, 1, 1), month_format='MMM D, YYYY', display_format='MMM D, YYYY', date=date(2021, 1, 1), ), ), dbc.CardBody( [ dash_table.DataTable( id='casetable-row-ids', columns=[ {'name': i, 'id': i, 'deletable': True} for i in initial_date.columns if i != 'id' ], data=initial_date.to_dict('records'), editable=False, filter_action="native", sort_action="native", sort_mode='multi', row_selectable='multi', selected_rows=[], page_action='native', page_current= 0, page_size= 10, style_as_list_view=True, style_cell={'padding': '5px'}, style_header={ 'backgroundColor': 'black', 'color': 'white', 'fontWeight': … -
django queryset use .values for the foreign key field
I have a model which the creator field is a forign key from user table : class CompanyTemplateMessage(models.Model): name = models.CharField(max_length=100, blank=True, null=True) subject = models.CharField(max_length=256) company = models.ForeignKey('Company', on_delete=models.CASCADE, related_name='company_template') text = models.TextField() created_at = models.DateTimeField(auto_now=True, blank=True, null=True) creator = models.ForeignKey( 'user.User', null=True, blank=True, on_delete=models.SET_NULL, related_name='user_template_message', ) User: class User(AbstractBaseUser, PermissionsMixin): is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=255, unique=True) phone = PhoneNumberField(unique=True, null=True, blank=True) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) join_date = models.DateTimeField(auto_now_add=True) companies = models.ManyToManyField( 'company.Company', related_name='members', blank=True, ) USERNAME_FIELD = 'email' def __str__(self): return self.email i use this queryset and value() parameter to determine which field is chosen to show def get_queryset(self): company_code = self.kwargs.get('company_code') company_template_objs = CompanyTemplateMessage.objects.filter(company__code=company_code).values( 'name', 'created_at', 'creator') return company_template_objs when i dont use values() it works properly and shows the creator field but when i choose creator in the fields , it shows this error : 'int' object has no attribute 'pk' and when i use something else like : 'creator__email' or 'creator__id' the creator field returns null value while it is filled by a user what should i use for this field to show the user value ? -
Django with Postgresql on MacOS. FATAL error: "Database does not exist"
Trying to get Django to work with Postgres instead of sqlite. Created the database (ytptest1). It exists. It has no tables, thus cannot migrate. kak=# \c ytptest1 You are now connected to database "ytptest1" as user "kak". In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # 'NAME': BASE_DIR / 'ytptest1', # 'NAME': str(BASE_DIR / 'ytptest1'), 'NAME': str('/Users/kak/Library/Application Support/Postgres/var-15/ytptest1'), # 'NAME': '/Users/kak/Library/Application Support/Postgres/var-15/ytptest1', 'USER': 'kak', 'HOST': 'localhost', 'PORT': '5432', } } % python manage.py runserver . . . File "/Users/kak/Library/Python/3.10/lib/python/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "/Users/kak/Library/Application Support/Postgres/var-15/ytptest1" does not exist I've tried more things can I can list. I finally figured out that the Django DB's are stored in /Users/kak/Library/Application Support/Postgres/var-15 Very new to this universe. ( I Thanks -
How to take input as audio using django template?
<input type="text" x-webkit-speech name="prompt" value="{{prompt}} enter image description here I'm not able to get audio as an input as shown in image. <input type="text" x-webkit-speech name="prompt" value="{{prompt}} i have tried this but its not working. -
Install mod-wsgi in a poetry virtual environment
I have a django app. I've created a poetry virtual environment to manage dependencies. This app runs on python 3.10. My pyproject.toml looks like this: [tool.poetry] name = "django_manager" version = "0.1.0" description = "A Game manager" authors = [""] [tool.poetry.dependencies] python = "^3.10" Django = "^4.1.7" beautifulsoup4 = "^4.12.0" requests = "^2.28.2" pillow = "^9.4.0" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" Now I'm trying to move the app to a CentOS VM, I copied the whole project folder to /var/www/html/GameManager and inside it run poetry install then poetry shell Now if I do python -V I get Python 3.10.4 so that side works OK. If I try to serve the app with apache: /etc/httpd/conf.d/gamemanager.com.conf <VirtualHost *:80> ServerName gamemanager.com ServerAlias *.gamemanager.com Redirect permanent / https://gamemanager.com/ </VirtualHost> <VirtualHost *:443> ServerName gamemanager.com ServerAlias *.gamemanager.com <Directory /var/www/html/GameManager> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess gamemanager.com display-name=gamemanager user=user group=user_group processes=2 threads=15 WSGIScriptAlias / /var/www/html/GameManager/app/wsgi.py WSGIProcessGroup gamemanager.com TimeOut 3600 LogLevel info ErrorLog "/var/log/httpd/gamemanager.com-error.log" CustomLog "/var/log/httpd/gamemanager.com-access.log" common </VirtualHost> I see in gamemanager.com-error.log an expception executing wsgi.py, probably because that it's trying to use /home/user/.local/lib/python3.6/site-packages/django/conf/__init__.py So right now I'm trying to fix that by installing mod-wsgi inside the venv with python3.10 and pip3.10. But … -
How to fill GraphQL ENUM from Django QuerySet?
In my graphql api for Revenue field use Currency enum from constant. from graphene import Enum CurrencyEnum = Enum('Currency', CURRENCY_CHOICES) class RevenueMetrics: revenue = graphene.Float(description='Revenue', currency=CurrencyEnum(required=True)) ... But now CURRENCY_CHOICES constant has moved to DB (Currency table). There are good reasons for this (not related to graphql). I can't figure out how to create CurrencyEnum class with dynamic filling from QuerySet of Currency table. Have an up-to-date set of Currencies.(I suppose that there is another question in the restructuring of the scheme). graphene==2.1.8 graphene-django==2.13.0 I tried like this: def dcm(): return Enum('Currency', tuple((c, c) for c in Currency.objects.values_list('code', flat=True))) revenue = graphene.Float(description='Revenue', currency=dcm()(required=True)) But it still requires a schema regeneration. -
How to get all {% include ... %} and {% extend ... %} tags before/after render Django template?
Using Django, I have html template "name.html" with content like: {% extends "some.html" %} {% for page in pages %} {% include page.html_template_path %} {% endfor %} This will include template wich path is stored in page.html_template_path. Important part is: every html template may extend/include another html templates inside itself. How to recursivly get all templates (path to every template) loaded via {% extend ... %} and {% include %} tags ? RegEx is not solution (path to template may be inside variable/context/{% for %} tag etc I found https://github.com/edoburu/django-template-analyzer/blob/master/template_analyzer/djangoanalyzer.py but it cant properly treat nested {% for %} tags etc -
How can I take the second row from the end from the table of the Django model?
I'm trying to get the second and third rows from the end of the model table. I know how to get the last row. But I need - (last - 1) and (last - 2) rows alternately. How can you get them? qs_select = Model.objects.all() last_row = qs_select.last() -
Catching IntegrityError vs filtering before object creation?
I have a development task. And at some point of this task, I need to create DB objects with a function which takes multiple json objects returning from third-party client request. I am for looping through json objects and calling _create_db_object method to create them one-by-one. Sample model: class MyObject(models.Model): some_unique_field = models.CharField() ... ... The function I use to create objects in DB: def _create_db_object(dict_: dict[str, str]) -> None: try: return MyObject.objects.create(...) except IntegrityError as e: continue My question is: "Would it be better if I used something like this instead of try except?" def _create_db_object(dict_: dict[str, str]) -> None: if MyObject.objects.filter(some_unique_field=dict_["unique_field"]): continue return MyObject.objects.create(...) Which function would be better and why? -
How to assign tags to a post using a form?
I have the following code below, when adding a Post, everything is saved and assigned except for tags that seem to have not even been written. How can I assign them? Thanks in advance for the hints models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') object = models.Manager() published = PublishedManager() tags = TaggableManager() def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) class Meta: ordering = ('-publish',) def __str__(self): return self.title forms.py class PostAdd(forms.ModelForm): class Meta: model=Post fields=('title', 'body', 'tags','status') views.py def AddPost(request): post_form=PostAdd(request.POST) if post_form.is_valid(): form=post_form.save(commit=False) form.slug=slugify(form.title) form.author=request.user form.save() context={ 'post_form':post_form, } return render(request, 'administration/addpost.html', context) I tried to do something with the documentation but it threw errors.