Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add attributes to a Django form widget's media fields?
I can render media files for a django form, through a custom widget, like this: class TinyMCEWidget(Textarea): def __init__(self, attrs=None): if attrs is None: attrs = {} attrs.update({ 'class':'listing-template', }) super().__init__(attrs) class Media: js = ('https://cdn.tiny.cloud/1/my_api_key/tinymce/5/tinymce.min.js/',) But I need to add referrerpolicy="origin" to the script. Is there a way this can be done without a javascript hack? How can I add attributes to a widget's media fields through the widget or form class? This question shows how I can add an arbitrary amount of attributes to a form widget, but does not show how to add attributes to a widget's media fields, therefor my question is not a duplicate. -
ModuleNotFoundError... No Module named Google
I'm trying to link my Google App to cloud storage so I can upload and store images. It worked just fine locally. Now I'm getting this error: (showrooom is the name of my app, and create is the page containing the upload form) ModuleNotFoundError at /showroom/create/ No module named 'google' Following the documentation and previous answers, I used PIP to install google-cloud, google-cloud-vision, and google-cloud-storage. Running pip now shows that google-cloud is installed in my Virtual Environment. Requirement already satisfied: google-cloud in c:\users\user\envs\torque\lib\site-packages (0.34.0)``` But checking in Python (still within the directory and virtualenv), it returns none: >>> import google >>> print(google.__file__) None Can anyone point me in the right direction? There are a lot of interesting errors, so I'll post the full traceback (torque is the name of my app). Request Method: POST Request URL: https://torque-256805.appspot.com/showroom/create/ Django Version: 2.2.5 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'showroom', 'django.contrib.humanize', 'django.contrib.sites', 'crispy_forms', 'allauth', 'allauth.account'] Installed 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'] Traceback: File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/env/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return … -
Is it possible in Django to insert data in var/dynamic table name via Models META?
Thank you for reading i am new to Django and For my application it's a requirement to create a table for each client to store his data. Each client table has the same data so i made a Model for it. But the table name is variable: I tried to do this via the Meta: db_table: Other_function The table is not created and i get error. In the url the customername is available, als in the view as variable. I tried to do this via the Meta: db_table: get_create_table The table is not created and i get error. because the function needs the var instance get_create_table(instance) if (instance.organisation in connection.introspection.table_names()): return instance.organisation else: with connection.cursor() as c: c.execute("CREATE TABLE %s (organisation varchar(255)," "organisation_code varchar(255)," % instance.organisation)``` and in the model: ``` class Import(models.Model): class Meta: db_table = get_table_name() organisation = models.CharField(max_length=255) ``` i get of course and error for instance because it doesnt exists from the view. In the view i have: ``` model = Import() model.organisation = organisation model.save() ``` i also changed the model to: ``` class Import(models.Model): class Meta: db_table = get_table_name organisation = models.CharField(max_length=255) ``` but it doesnt create the table and gives errors. i would … -
Adding reviews to shopping cart buid with react and django
I've built a react shopping cart using reactjs and backend build with django is it possible to add customers review's on my web app and i have a Google authentication set up -
How to extend Django groups for dynamic user types?
I have a SaaS project which many companies will use and within the companies there will be employees which will be applied to one of two groups: Supervisor or Non-Supervisor. This will probably look as such: class EmployeeGroup(Group): .... Each company will be able to create their own EmployeeType which falls into one of the EmployeeGroups. e.g. an EmployeeType may be Food and Beverage Supervisor which is an EmployeeGroup: Supervisor: class EmployeeType(models.Model): .... employee_type = models.CharField( max_length=32, default='Server' ) employee_group = models.ForeignKey( EmployeeGroup, null=True ) company = models.ForeignKey( Company, on_delete=models.CASCADE, null=True ) And obviously each User will have an EmployeeType: class User(AbstractUser): .... employee_type = models.ManyToManyField( EmployeeType, null=True, ) In this situation, can several companies share EmployeeGroups without sharing EmployeeTypes? My concern is that if an EmployeeType: Server is created at Company A then Company B will not be able to create an EmployeeType: Server as well. Or that if they do then information will get crossed. It wuold help to have an understanding of how the database works but I do not. Any links to external resources specific to this situation would be greatly appreciated! -
redirect() not directing to proper view
I have the following urls.py: from django.contrib import admin from django.urls import path from users import views as usersViews urlpatterns = [ path('admin/', admin.site.urls), path('', usersViews.index, name = 'index'), path('register/', usersViews.register, name = 'regsister'), ] and the following views.py: from django.shortcuts import render, redirect from .forms import RegistrationForm from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('signed up') def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) # get data from form if form.is_valid(): form.save() # save form? to db? username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') return redirect("index") else: form = RegistrationForm() # pass blank form to template return render(request, 'users/registration.html', {'registrationForm':form}) Upon submission of the form I am being redirected to "/register/index.html" and not "/" (index page). Can anyone help with this? -
Error updating model data using .objects.filter().update() in Django using Djongo "djongo.sql2mongo.SQLDecodeError"
Hello there I'm using Django and MongoDB for building a REST API project. I'm using Djongo for connecting Django with MongoDB I've created my models as follow: Models from djongo import models class OPCNetworkNode(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) address = models.CharField(max_length=100, default="localhost", blank=False, null=False) port = models.CharField(max_length=10, default="58725") class OPCTagBrowserSesson(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) opc_node = models.ForeignKey(OPCNetworkNode, on_delete=models.CASCADE,related_name='node_opc_sesson', unique=True) clientId = models.CharField(max_length=100, blank=False, null=False) token = models.CharField(max_length=100, blank=False, null=False) timestamp = models.DateTimeField(default=timezone.now()) and I've created a function based view as follow: View @api_view(['POST']) def getOPCRoot(request): opc_uri = request.data.get('opc_uri') sessonInstance = OPCTagBrowserSesson.objects.filter(opc_node__address__exact=opc_uri) sessonInstance.update(clientId = "88888888888888") return Response(data={"check cmd"}) But when I request a POST request to the url with the 'opc_uri' parameter to perform an update on the model data it gives me the following error. Error: djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "asset_herarchi_opctagbrowsersesson" SET "clientId" = %(0)s WHERE "asset_herarchi_opctagbrowsersesson"."id" IN (SELECT U0."id" FROM "asset_herarchi_opctagbrowsersesson" U0 INNER JOIN "asset_herarchi_opcnetworknode" U1 ON (U0."opc_node_id" = U1."id") WHERE U1."address" = %(1)s) Params: ('88888888888888', 'localhost') Pymongo error: {'index': 0, 'code': 40081, 'errmsg': '$in requires an array as a second argument, found: missing'} Version: 1.2.35 -
Heroku doesn't upload static files to S3 bucket in production: Possibly permission error
I configured my django app so that it uploads static and media files to S3. I configured everything that my static folder should be public. My media folder has one private and one public folder. Now, locally everything runs perfectly fine. My static files are public, my private media folder is private, my public media folder is public. In production a weird behaviour happens. The only static files being uploaded to my bucket is the folder admin and rest_framework. My custom static files (css etc) are not uploaded. I set my env variables in heroku. And this is my config: #GENERAL AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = 'public-read' #AWS S3 Static AWS_STATIC_LOCATION = 'static' STATIC_URL = 'http://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) STATICFILES_DIR = [os.path.join(BASE_DIR, 'heatbeat_website/static')] STATICFILES_STORAGE = 'config.settings.storage_backends.StaticStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) #AWS S3 Private Media Upload AWS_PUBLIC_MEDIA_LOCATION = 'media/public' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' PRIVATE_FILE_STORAGE = 'config.storage_backends.MediaStorage' # MEDIA # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR('media')) # https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' My storages are: class StaticStorage(S3Boto3Storage): location = settings.AWS_STATIC_LOCATION default_acl = 'public-read' class PublicMediaStorage(S3Boto3Storage): location = settings.AWS_PUBLIC_MEDIA_LOCATION default_acl = 'public-read' file_overwrite = False class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = … -
How does "return render(request, 'path/path')" works in Django?
Please explain how "return render(request, 'path/path')" this works step by step in any particular views.py file in django. MYcode: (views.py) from django.shortcuts import render from basic_app.forms import UserForm,UserProfileInfoForm from . import forms def index(request): return render(request,'basic_app/index.html') def register(request): registered=False if request.method=="POST": profile_form=UserProfileInfoForm(data=request.POST) user_form=UserForm(data=request.POST) if profile_form.is_valid() and user_form.is_valid(): user=user_form.save() user.set_password(user.password) user.save() profile=profile_form.save(commit=False) profile.user=user if 'profile_pic' in request.FILES: profile.profile_pic=request.FILES['profile_pic'] profile.save() registered=True else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'basic_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) Code: (registration.html) {% extends "basic_app/basic.html" %} {% load staticfiles %} {% block body_block %} <div class="jumbotron"> {% if registered %} <h1>Thank you for registering!</h1> {% else %} <h1>Register Here!</h1> <form enctype="multipart/form-data" method="post"> {{user_form.as_p}} {{profile_form.as_p}} {% csrf_token %} <input type="submit" name="" value="Register"> </form> {% endif %} </div> {% endblock %} ALSO EXPLAIN: How the dictionary defined in "return" statement in views.py works step by step. -
inhereting models in forms in django
while I am linking my models to my forms by using forms.ModelForm and running the server the error appearing is "ModelForm has no model class specified" class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class meta: Model= User fields=('username' , 'email' , 'password') -
How to refresh cache from DB in django rest service?
The main intent of this question is to know how to refresh cache from db (which is populated by some other team not in our control) in django rest service which will then be used in serving requests received on rest end point. Currently I am using the following approach but my concern is since python (cpython with GIL) is not multithreaded then can we have following type of code in rest service where one thread is populating cache every 30 mins and main thread is serving requests on rest end point.Here is sample code only for illustration. # mainproject.__init__.py globaldict = {} # cache class MyThread(Thread): def __init__(self, event): Thread.__init__(self) self.stopped = event def run(self): while not self.stopped.wait(1800): refershcachefromdb() # function that takes around 5-6 mins for refreshing cache (global datastructure) from db refershcachefromdb() # this is explicitly called to initially populate cache thread = MyThread(stop_flag) thread.start() # started thread that will refresh cache every 30 mins # views.py import mainproject @api_view(['GET']) def get_data(request): str_param = request.GET.get('paramid') if str_param: try: paramids = [int(x) for x in str_param.split(",")] except ValueError: return JsonResponse({'Error': 'This rest end point only accept comma seperated integers'}, status=422) # using global cache to get records output_dct_lst … -
Text area not reading HTML
I have Django´s Blog APP installed, all working fine, but I need to add posts (via admin) with HTML in the post content field, now, the text area can only read plain text (it doesn´t render HTML). This is the field: (models.py) content = models.TextField() This is the HTML for this field: <h6 class="card-text" ><small>{{post.content|slice:":500" |linebreaks |safe}}</small></h6> Question is: are there special configs for Django/Python in order for the field to render HTML? -
Page not Found (404) in django
Am using django I got this error Page not Found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in VibezT.urls, Django tried these URL patterns, in this order music/ admin/ The empty path didn't match any of these. VibezT\urls.py from django.contrib import admin from django.urls import include, path urlpatterns =[ path('music/', include('music.urls')), path('admin/', admin.site.urls), ] For music URLs I have this code music\urls.py from django.urls import path from . import views urlpattern = [ path(r'^$',/ views.index, name='index') ] For views i have this code from django.http import HttpResponse def index(request): return HttpResponse("Hello World") -
Template tag doesn't respect passed context variable
I'm having an issue with my custom template tag not respecting passed context variable. So, I have a template named task_list.html, which includes paginator.html that references my custom template tag ({% url_replace %}): task_list.html: ... {% include 'paginator.html' with page_obj=tasks_tomorrow page='page_tomorrow' %} ... paginator.html: ... <a class="page-link" href="?{% url_replace page=page_obj.paginator.num_pages %}" ... However, the URL constructed is http://127.0.0.1:8000/todo/?page=2, instead of http://127.0.0.1:8000/todo/?page_tomorrow=2. This is my template tag: from django.utils.http import urlencode from django import template register = template.Library() @register.simple_tag(takes_context=True) def url_replace(context, **kwargs): query = context['request'].GET.dict() query.update(kwargs) return urlencode(query) What is the issue here? -
How to get a value from a select for a variable in javascript
I am trying to get a value from a variable. console.log ($ ('# id_prova'). val ()) works perfectly when inspecting element, console.log (proofIdQuestao), which is part of app.js, does not work. I want to make one dropdown dependent on another. The questions depend on idProva. app.js let urlQuestoes = $('#myForm').data('urlquestoes'); var provaIdQuestao = $('#id_prova').val() console.log($('#id_prova').val()) console.log(provaIdQuestao); console.log(urlQuestoes); $('#questaoSelect').change(function() { let urlQuestoes = $('#myForm').data('urlquestoes'); let questaoIdQuestao = $(this).val(); console.log(questaoIdQuestao); $.ajax({ url: urlQuestoes, data: { questao: provaIdQuestao }, success: function(response) { $('#provaSelect').html(response); } }) }); }); base.html <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" type="text/javascript"></script> </script></head> index.html <form action='/pesquisa' id="myForm" method="GET" data-urlquestoes="{% url 'questoes_choices_ajax' %}" data-urlcategorias="{% url 'categorias_choices_ajax' %}"> {% csrf_token %} <div class="card acik-renk-form"> <div class="card-body"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="provaSelect">Provas</label> {% render_field form.prova title="Provas" class="form-control" %} </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="questaoSelect">Questões</label> <select class="form-control" name='questao' id="questaoSelect"> <option value="">---------</option> </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="categoriaSelect">Categoria</label> <select class="form-control" name='categoria' id="categoria"> <option value="">---------</option> {% for categoria in categorias %} <option value={{categoria.idCategoria}}>{{categoria.nomeCategoria}}</option> {% endfor %} </select> </div> </div> </div> <div class="row"> <div class="col-md-10"> <div class="form-group"> <input placeholder="Termo" type="text" name="q" class="form-control"> </div> </div> <div class="col-md-2"> <button type="submit" class="btn btn-block btn-md btn-primary pl-6 pr-6">Pesquisar questões</button> </div> </div> </div> </div> </form> -
Queryset and serializer is giving the error 'int' object is not iterable
I have two models. A model which contains the students and teamnames and the other model (Tester) contains the rate (1 until 10) the gave for the fields QA1 and QA2. Every team has its own page, where they can find the average rates for QA1 and QA2 per team. For this, i need a queryset that is filtering the team and calculates the averages for each team. The code was working until I tried to create the filters. This is the documentation I used: https://www.django-rest-framework.org/api-guide/generic-views/#listapiview https://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-url I already tried to delete or add arguments, I also tried to change get_queryset. So far without succes. Im getting the same error or different errors. I really don't know how to solve this. serializers.py class TesterSerializer(serializers.ModelSerializer): slug_teamname = serializers.SlugRelatedField( slug_field='slug_teamname', read_only=True, many=True) queryset = serializers.SerializerMethodField() lookup_field = 'slug_teamname' extra_kwargs = {'url': {'lookup_field': 'slug_teamname'}} class Meta: model = Tester fields = ('slug_teamname','queryset') views.py class TesternieuwListView(generics.ListAPIView): serializer_class = TesterSerializer template_name = 'tester/tester_list.html' # filter_backends = (DjangoFilterBackend) lookup_field = 'slug_teamname' lookup_url_kwarg = 'slug_teamname' def get_queryset(self): slug_teamname = self.kwargs['slug_teamname'] return Tester.objects.filter(slug_teamname__slug_teamname=slug_teamname).values('slug_teamname').annotate( QA1__avg=Avg('QA1'), QA2__avg=Avg('QA2'), A snippet of my models.py created_by = models.ForeignKey(User, on_delete=models.CASCADE) slug_teamname = models.ForeignKey(Team, on_delete=models.CASCADE) QA1 = models.DecimalField(max_digits=4, decimal_places=0) QA2 = models.DecimalField(max_digits=4, decimal_places=0) My … -
Need Nginx proxy to forward Authorization to django backend, How?
I will be very precise on this, as i have tried every solution on the web. I am in desperate need of help. I am attatching my default.conf file for my nginx. I am able to use the django apis successfully without nginx. Please help me. Anyone ? It says 401: unauthorized, meaning i am not able to pass the authorization token to django backend through nginx. I am sure someone would have gone through this process because it is a common use case. HELP location ~ /backend/(?<section>.+) { proxy_pass http://10.128.0.5:8001/$section; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header Authorization "9ca0c2c79b1acab6c1b2a699a391f08f7aa68bdf"; } -
Jinja custom extension: parse arguments in any order they are written
I've built a custom Jinja extension that, when used inside a template, looks something like this: {% field "text" name="color" value="Yellow" class="bold" %} And once it's been interpreted by Jinja, the resulting HTML is: <div class='bold'>Yellow</div> It works fine, except for the fact that the parameters must be written in exact order (name, then value, and finally class). I would like to make it handle the parameters in a more flexible way, ie. that that can be specified in any order. This is how I've implemented it: def parse(self, parser): lineno = parser.stream.__next__().lineno context = jinja2.nodes.ContextReference() tag = parser.parse_expression().value if tag not in self.environment.supported_tags: raise TemplateSyntaxError(f'Unexpected template tag {tag}. ' f'Expected one of {self.environment.supported_tags}.', lineno, tag) value = css_class = '' if parser.stream.current.test('name:name'): parser.stream.skip(2) parser.parse_expression() # parse the field name parser.stream.skip_if('comma') if parser.stream.current.test('name:value'): parser.stream.skip(2) value = parser.parse_expression() parser.stream.skip_if('comma') if parser.stream.current.test('name:class'): parser.stream.skip(2) css_class = parser.parse_expression() parser.stream.skip_if('comma') args = [value, css_class, context] call = self.call_method('_create_field', args) return jinja2.nodes.Output([call], lineno=lineno) I understand why it's behaving the way it is, but I don't know how to parde the parameters in any given order. Any idea how to make it accept the parameters in any order? -
tcp serwer with django
For easy understanding, I simplify description of my app. App has two main features: 1. show data from database in a beautiful way :) 2. save data provide by POST or GET request (json) I want to speed up the application and relieve network, to do that I want to make able to send data to the app by tcp. Have you any suggestions on how to do it? I want to have as much as its possible common code. In ma app I have a method "parse_and_save_to_db(json)", which is used by the view and I want to use it in tcp server. -
Update Static JSON file from Django page
I'm building an app at work for part number creation/management with Django. I current use a json file to inform/enforce some of the part number rules on the part number creation page. I'd like to be able to update this json file from the web page so that when we need to edit or add to the current part number schemes the person doing so doesn't need a technical background. To do this I want to send a json object to the view and use it to update/replace the original json file. I've tried to access it using the static url static('/javascript/json_file_name.json') I've also tried to access it using its file path. both have not been successful. This is a tool used inside a private network hosted on a raspberry pi and won't be public. Thanks in advance! -
How to subscribe a celery task to an existing RabbitMQ exchange?
I'm currently writing a chat messenger using GRPC/RabbitMQ for group chats. I have an API in Django/DRF that handles authentication/message logs/text and email alerts etc. To do this I would like to create a celery task that subscribes to each group message exchange but I'm unclear if there is there a way to bind a celery task to the message exchanges. Is it realistic/possible to create celery tasks that subscribe to the chat exchanges I create? If not how would you solve/handle these duties? -
Selenium - Python/Django - Count records for a model
I newbie in Django/Python and moreover in functional testing I use selenium I try to test "add" in a model so I try to calculate record number (number = MyModel.objects.count()) before and after adding to compare but my count return 0 even if there is 8 records in my database it is not possible to count from a class test? -
How to handle multiple dynamic user types in Django?
I have a problem I have been stuck on for days now and can't seem to find the solution. In my models I have Companies. Each company has 2 Group's for authentication and authorization: Supervisor and Non-Supervisor. Of these 2 Group's there will be several dynamic sub-groups for each company, which I call Employee Type. These EmployeeType's will be able to be created by the Company Admin within the Admin panel then assigned to one of the Groups. class Company(models.Model): .... group = models.ManyToManyField( Group, related_name='companies_group' ) class EmployeeType(models.Model): .... employee_type = models.CharField( max_length=32, default='Server' ) group = models.ForeignKey( Group, on_delete=models.CASCADE, null=True ) class User(AbstractUser): .... company = models.ForeignKey( Company, on_delete=models.CASCADE, null=True ) group = models.ForeignKey( Group, on_delete=models.CASCADE, null=True ) employee_type = models.ForeignKey( EmployeeType, on_delete=models.CASCADE, null=True, ) I have several questions: Should the UserProfile be handling the user's Group and Employee Type? Should the CompanyProfile be handling the companies' Groups? Is this the correct way to model the dynamic user type creation? Each company will have different EmployeeTypes. Do I need to add EmployeeTypes to Company? Apologies if it seems very simple but I am confused when the EmployeeTypes become dynamic. I end up having circular logic when I try … -
how to extend templates in djangi
I created blog page. while clicking on a post title it will opemsin single page. but i created new html page , views and added path in urls Events page html code: this is page it will displays all posts below images are added {% extends 'polls/base_1.html' %} {% block content %} <p>Events page </p> <div> <h2><a href="{% url 'event_detail' pk=event.pk %}">{{ event.event_title }}</a></h2> <p>published: {{ event.event_release_date }}</p> <p>{{ event.event_description|linebreaksbr }}</p> {% for author in event.event_author.all %} <p>{{ author }}</p> {% endfor %} </div> {% endblock %} events detail page code: this is page page where open while clicking on post {% extends 'polls/base_1.html' %} {% block content %} <div class="post"> <div class="date"> <p>published: {{event.event_release_date }}</p> </div> <h2>{{ event.event_title }}</h2> <p>{{ event.event_description|linebreaksbr }}</p> </div> {% for author in event.event_author.all %} <p>{{ author }}</p> {% endfor %} {% endblock %} -
Django: Set pk from own model as default value in own column
What do I have to do, to assign the pk as a default value? This doesn't work: from django.db import models class TeamMember(models.Model): id = models.AutoField(primary_key=True) order_listing = models.IntegerField(default=id)