Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Script sql in docker-entrypoint-initdb.d not executed
I try to initialize my postgresql database using sql script in docker-entrypoint-initdb.d folder I have no error message but database is not initialized even if I suppress container and rebuilt what is wrong with my docker-compose.yml file? docker-compose.dev.yml version: '3.7' services: web: restart: always container_name: coverage-africa-web-dev build: context: ./app dockerfile: Dockerfile.dev restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/usr/src/app - ./docker-entrypoint-initdb.d/initdata.dev.sql:/docker-entrypoint-initdb.d/initdata.dev.sql ports: - 8000:8000 env_file: - ./.env.dev -
Data not save on database
In my website when someone register he give some values like 1st name,last name,email, password etc. Which save in auth_User database. I want to make a new model Profile which is child of User model. and its have some new fields. models.py class Profile(User): image = models.ImageField(null=True,blank=True, upload_to="profile/") bio = models.TextField(max_length=255,null=True) address = models.CharField(max_length=255,null=True,blank=True,) mobile_no = models.CharField(max_length=10,null=True,blank=True,) website_url = models.CharField(max_length=255,null=True,blank=True,) facebook_url = models.CharField(max_length=255,null=True,blank=True,) twitter_url = models.CharField(max_length=255,null=True,blank=True,) linkdin_url = models.CharField(max_length=255,null=True,blank=True,) forms.py class UserEditForm(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={"class":"form-control"}) ) first_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={"class":"form-control"})) class Meta: model = Profile fields = ('first_name','last_name','username','email','password','image','address','mobile_no','bio','website_url','facebook_url','twitter_url','linkdin_url') widgets = { "username" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "website_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "facebook_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "twitter_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), "linkdin_url" : forms.TextInput(attrs={"class":"form-control","placeholder":"write title of your posts"}), # # "title_tag" : forms.TextInput(attrs={"class":"form-control"}), # # "author" : forms.HiddenInput(), # # "image" : forms.Select(attrs={"class":"custom-file"}), # "catagory" : forms.Select(choices=choices,attrs={"class":"form-control"}), "bio" : forms.Textarea(attrs={"class":"form-control"}), } urls.py path('edit_profile/',UserEditView.as_view(),name="editProfile"), views.py class UserEditView(UpdateView): form_class = UserEditForm template_name = 'edit_profile.html' success_url = reverse_lazy('editProfile') def get_object(self): return self.request.user edit_profile.html {% extends 'base.html' %} {% block title %} Edit Profile... {% endblock title %} {% block content %} <style> label[for=id_password],.helptext,#id_password { display: none; } </style> {% if user.is_authenticated %} <h1>Edit … -
Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer
I am getting this error while sending my form through Ajax in Django Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer in line data= formdata Can you help me figure out the solution. uploadBtn.addEventListener('click', e=>{ e.preventDefault() progressBox.classList.toggle('not-visible', false) var formdata = new FormData() formdata.append('csrfmiddlewaretoken', csrftoken) formdata.append('fileA', FileA.files[0]) formdata.append('a_year', year.value) $.ajax({ type: 'POST', url: '', enctype: 'multipart/form-data', data = formdata, success: function(response){ console.log(response) }, error: function(response){ console.log(response) }, cache: false, contentType: false, processData:false, }) }) -
No Module Found Django while sending mail
When I tried sending mails from my django project, experienced this problem. I tried these commands: from django.core.mail import send_mail send_mail("sub", "body", "test@test.com", ["xyz@gmail.com"]) All the email settings are properly configured and it is running on other systems, but it is showing this error on my Ubuntu 20.04 django project Traceback (most recent call last): File "/usr/lib/python3.8/code.py", line 90, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/nishi/nishi/campaignmanager/venv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 51, in send_mail connection = connection or get_connection( File "/home/nishi/nishi/campaignmanager/venv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 34, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "/home/nishi/nishi/campaignmanager/venv/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in … -
How to migrate/makemigrations in one app with multiple databases
I'm working on a django project with: One single app Three huge identical mysql databases with historical data One mysql database where I store results from calculations of the historical data I'm struggling with how to makemigrations/migrate when I make changes to the models. With only one database I would simple do something like: $ manage.py makemigrations <app_name> $ manage.py migrate <app_name> 0001 But this creates tables for every model in every database. I've tried to mess around with: $ manage.py migrate <app_name> 0001 --database==<name_of_db> But is this all I should do? I have looked into routers but I don't really understand how to configure one for this case. In short: My goal is to be able to update a model and then only migrate the changes to the relevant databases. In some cases the updated model should migrate to the three identical databases, in other cases the updated model should only migrate to the one unique database. All help would be appreciated! -
Search data in array of json array using django filter
I am using Postgresql DB. I have a JSONField in my Model. Here is the json. object.outer_data = [ { 'end': '20-11-2020 02:01 PM', 'start': '20-10-2020 02:01 PM', 'inner_data': [ { 'type': 'primary', 'id': '2' }, { 'type': 'secondary', 'id': '8' } ] }, { 'end': '', 'start': '20-11-2020 02:01 PM', 'inner_data': [ { 'type': 'primary', 'id': '2' }, { 'type': 'secondary', 'id': '6'}] } ] And I want to find out if this data have a matching key 'dietitianid': '6'. Models.objects.filter(outer_data__dietitians__inner_data__contains=[{'dietitianid': '6'}]) But ofcourse this is wrong as I have to pass the index in which inner_data will be searched. I am looking for this query where I can sort of use a double contains. One for dietitians in outer_data and then for dietitianid in dietitians. Any suggestion would be helpful! Thank you. -
django.db.utils.OperationalError: while deploying to pythonanywhere
django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? -
django built-in authentication system not working with react
I am building a django-react app, using Django to render the templates, Django REST framework for the api endpoints, and React on top of django templates. I am using 'rest_framework.authentication.SessionAuthentication' and I have implemented the authentication routes but django's built-in authentication methods (login, logout, authenticate) only seem to work with the templates rendered by django and not with the React components. By this I mean if i have a view like def home_page(request, *args, **kwargs): print("local USER >>>", request.user) print("local SESSION >>>", request.session) return render(request, 'pages/homepage.html', {}, status=200) and I visit the route after logging in, it would print out both the user and the session object. But for the api views, @api_view(['GET', 'POST']) @permission_classes([IsAuthenticatedOrReadOnly]) def post_list_view(request, *args, **kwargs): print("api USER >>>", request.user) print("api SESSION >>>", request.session) ... I get AnnonymousUser and None even if I'm logged in. When i checked the browser cookies, i found both the csrftoken and sessionid cookies. But if I try a post request, I get 403 Forbidden error with "Authentication credentials were not provided." message. (I have also set withCredentials to true.) And in the request headers there was only the X-CSRFToken header (with the token) but sessionid cookie was missing. At this point, … -
How to check request.user against an unrelated model in Django
My question is a little difficult to explain but I'll try my best. Please ask if anything needs to be clarified. I have three models, Exercise, Area, and Workout: class Exercise(models.Model): name = models.CharField(max_length=100) class Area(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=100) exercise = models.ManyToManyField(Exercise, blank=True) class Workout(models.Model): weight = models.DecimalField(default=0.0) reps = models.PositiveIntegerField(default=0) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) The user will complete a form that adds objects to Area. They can then go into that object and complete a new form that adds objects to Exercise, which are also attached to the specific area through M2M. In order to display only the exercises that this particular user has created, I have an if statement in the exercise template: {% if area.user.user == request.user %}` {{ exercise.name }} {% endif %} I want the user to now be able to go into the Exercise object and complete a form that adds to Workout. I can achieve this but my question is how can I make sure only the logged in users workouts are displayed? area.user.user has no affect since Area is unrelated to this template and I cannot add a user to the Exercise model. -
Django Admin see and ORM query in admin view
In my django project i have two tables: class A(models.Model): n_code = models.CharField(max_length=2, verbose_name='NazA') n_desc = models.CharField(max_length=50, verbose_name='DescA') class B(models.Model): b_code = models.CharField(max_length=2, verbose_name='NazB') b_descr = models.CharField(max_length=50, verbose_name='DescB') b_surname = models.CharField(max_length=50, verbose_name='surB') b_notes = models.CharField(max_length=50, verbose_name='NotesB') i would , when in my django admin console loock at the A model list items view the fields related to an ORM query with A and B models linked by n_code and b_code fields How can i ask Django to display list of fields based on a query instead of just the field declared in my model? so many thanks in advance -
Do errors in BoundField.errors and BoundField.help_text need to be escaped in a template in Django?
Do errors in BoundField.errors and BoundField.help_text need to be escaped in a template in Django? My guess is yes because both the errors and the help_text are no place for HTML code. However, I am a bit confused after I saw the following two snippets of code in the documentation of Django. Snippet A: {% if form.subject.errors %} <ol> {% for error in form.subject.errors %} <li><strong>{{ error|escape }}</strong></li> {% endfor %} </ol> {% endif %} Snippet B: {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} (Snippet A can be found at near here, and Snippet B can be found near here) For Snippet A, I don't think the escape filter is needed because Django's default template engine escapes the string representation of any variable value by default. For Snippet B, I don't think the safe filter should be used because help_text is no place for any HTML code. Is my understanding incorrect, or are these two snippets of demo code in Django's documentation problematic the ways I indicated? -
List only unassigned values for many to many field in Django
I have two models as follows: class Fruit(models.Model): name = models.CharField(max_length=20) class Season(models.Model): name = models.CharField(max_length=20) fruits = models.ManyToManyField(Fruit, related_name='seasonal_fruit') I want to add the fruits to the Season if only they are not assigned to any other Season object. Also, I want to display the list of these distinct (i.e. not assigned to any other Season object) in the SeasonAdmin. How can I achieve this? -
Django Rest Framework - serializers.SlugRelatedField does not return field value
I have the following Car model in my Django Rest Framework project: from django.db import models from django.contrib.auth.models import User class Car(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) driver = models.ForeignKey(User, related_name='cars', on_delete = models.CASCADE) def __str__(self): return self.name class Meta: ordering = ['created'] As you can see, the Car model has a foreignkey relationship with the built-in User model. The field is called driver. Now, using the serializer class I also wanted to print out the username of the driver. Therefore, I used serializers.SlugRelatedField like this: class CarSerializer(serializers.ModelSerializer): username = serializers.SlugRelatedField(read_only=True, slug_field='username') class Meta: model = Car fields = ['id', 'name', 'username'] But in the JSON output I can not see the username value: [ { "id": 1, "name": "BMW" }, { "id": 2, "name": "Audi" } ] What is wrong here? -
How can I access the serializer in extra actions?
I have the following two classes and I want two merge EventInvitationCreateView into EventInvitationViewSet. However, I am struggling to bring perform_create into create_invitation as I still need to access serializer. Do you have any input on how to achieve that? class EventInvitationCreateView(CreateAPIView): serializer_class = InvitationSerializer permission_classes = [RetoolPermission] queryset = Invitation.objects.none() def perform_create(self, serializer): email = serializer.validated_data["email"] event = self.request.event invitation_exists = Invitation.objects.filter( email__iexact=email, event=event ).exists() if invitation_exists: raise ValidationError("Email already exists") serializer.save(event=event) class EventInvitationViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): permission_classes = [RetoolPermission] serializer_class = InvitationSerializer filter_backends = [filters.SearchFilter] search_fields = ["email"] queryset = Invitation.objects.none() def get_queryset(self) -> QuerySet: return self.request.event.invitations.all() @action(detail=True, methods=["post"]) def create_invitation(self, request, pk=None): [...perform_create] -
Celery worker stops when console is closed
I am trying to run Celery in development environment, on a cloud server. I am connecting to the machine using remote SSH, and starting Celery worker with the following comand: celery -A myapp worker -l info -f logs/celery.log Everything works fine at this point, but the worker stops a few seconds after the console window is closed (ssh connection closed). How do I keep the worker running, as having an opened SSH connection permanently is not an option? celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('uiforms') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py import requests from celery import shared_task import json def auth(): headers = {"someheaders"} data = { "somedata" } r = requests.post("url", data=data, headers=headers) return r.json()['access_token'] @shared_task def add_queue_item(acces_token=None, content=None): acces_token = auth() headers = { "Content-Type": "application/json", "Authorization": f"Bearer {acces_token}", } data = json.dumps(content) r = requests.post("url", data=data, headers=headers) cellery logs: [2020-11-20 08:55:13,548: INFO/MainProcess] celery@localhost ready. [2020-11-20 08:55:13,549: INFO/MainProcess] Received task: dlaforms.tasks.add_queue_item[517d8785-d08c-48a3-9475-b1c728daf66d] [2020-11-20 08:55:13,550: INFO/MainProcess] Received task: dlaforms.tasks.add_queue_item[3cdc3b8e-dbea-4f69-bb3a-d87668fb7804] [2020-11-20 08:55:14,181: INFO/ForkPoolWorker-1] Task dlaforms.tasks.add_queue_item[517d8785-d08c-48a3-9475-b1c728daf66d] succeeded in 0.5300460010184906s: None [2020-11-20 08:55:14,702: INFO/ForkPoolWorker-1] Task dlaforms.tasks.add_queue_item[3cdc3b8e-dbea-4f69-bb3a-d87668fb7804] succeeded in 0.5188984139822423s: None rabbitmq logs: 2020-11-20 08:42:34.239 [info] <0.16979.4> accepting AMQP connection … -
Best JavaScript Frawework to Use With Django
I have a general question about JavaScript frameworks and Django. Most of the time when I have been developing a project in Django, I have used J Query to add dynamic functionality to the rendered HTML templates, but from what I understand J Query should be avoided these days in the 2020s. My question would be what is the best alternative to use instead? I have previously made projects where I have used the Django REST Framework to build a back end REST API and then have built a front end in React which has worked fine, but the thing with this is that I have to host both the back end and front end separately. What would I be best doing if I wanted to render the front end using Django, but want the same sort of functionality that J Query allows for. Is the only option plain vanilla JavaScript or is there something new now? Please let me know if this should be posted in a different community as it is more about a recommendation, but I wasn't sure which community this should be posted under. -
Unity3d/django : You are seeing this message because this HTTPS site requires a “Referer header” to be sent by your Web browser, but none was sent
I am using a C# script to communicate to django https://mywebsite.co.uk/ from Unity3d editor using UnityWebRequest. My script: using System; using System.Collections; using System.Collections.Generic; using System.Text; using TMPro; using UnityEditor; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; //for reference - with some code if you would rather post a form public class WebFormPost: MonoBehaviour { public TMP_Text resultText; public string webAPIserver = "https://mywebsite.co.uk/"; private void Awake() { resultText.text = "Getting results from: " + webAPIserver +"\n"; } public void GetWebPage() { resultText.text += "Getting some results .... \n"; StartCoroutine(GetWebResult(resultText)); } public IEnumerator GetWebResult(TMP_Text results) { WWWForm form = new WWWForm(); //string mimeType = "image/jpg"; //string imageName = "screenshot.jpg"; //byte[] imageToUpload = image.EncodeToJPG(); // form.AddBinaryData ( "img", imageToUpload, imageName, mimeType); string searchURL = webAPIserver; results.text += "about to send. . . \n"; using (UnityWebRequest w = UnityWebRequest.Post(searchURL, form)) { yield return w.SendWebRequest(); if (w.isNetworkError) { Debug.Log(w.error); } else { Debug.Log("POST web call successful!"); // Print Headers StringBuilder sb = new StringBuilder(); foreach (System.Collections.Generic.KeyValuePair<string, string> dict in w.GetResponseHeaders()) { sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n"); } Debug.Log("received headers: "); Debug.Log(sb.ToString()); // Print Body var downloadedText = w.downloadHandler.text; Debug.Log("received body text: "); Debug.Log(downloadedText); results.text = downloadedText; } } }} However, when I run the code I get the … -
ModuleNotFoundError using LayerMapping
Using ogrinfo -so I've found the structure of the shapefile and based on this structure I've created a model: from django.contrib.gis.db import models class Villages(models.Model): . . . After that I've created the load.py as mentioned here inside the same directory of models.py: from pathlib import Path from django.contrib.gis.utils import LayerMapping from .models import Villages villages_mapping = { . . . } villages = Path(__file__).resolve().parent / 'gis' / 'villages.shp' def run(verbose=True): lm = LayerMapping(Villages, villages, villages_mapping, transform=False) lm.save(strict=True, verbose=verbose) Then, I try to use load.py: /geodata$ python3 load.py but I see this error: Traceback (most recent call last): File "load.py", line 3, in from .models import Villages ModuleNotFoundError: No module named 'main.models'; 'main' is not a package The app name is geodata, I've added this app inside settings.py and finalized the creation of the table with makemigrations and migrate. I'm using Django 3.0.7. I don't understand where is the problem -
Django filter date > datetime.now
I have a view that displays a list sorted by date. I would like to make a filter to display values where the date is greater than the current date. How to do it correctly? class UpcomingEvents(generics.ListAPIView): queryset = Event.objects.all().order_by('start_date') serializer_class = EventSerializer -
Flask application folder structure like Django
Is it possible to a Flask application looks like django application folder structure. I just want to organize the folders and separate the MVC part of the code and also I can use a class base which is kinda looks good vs on one file where your model, route and views live on single file. -
How to filter a field from a child model which has a foreign key in parent model in django rest framework?
I am trying to build an API in drf for listing the different travel packages. I have two models. The package is a parent model and Topactivities is a child model which has a foreign key to the Package model. Now when I hit localhost:8000/api/allpackages api I need to list all the packages which is not a problem. The problem is I want to filter the packages with activities title in the query. For eg: If I do localhost:8000/api/allpackages?activities=trekking, I need to show all the packages which have the activity of trekking. However, activities are not a field in the package. I am trying to use filter backends. Here are my models: class Package(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) featured = models.BooleanField(default=False) price = models.IntegerField() duration = models.IntegerField(default=5) discount = models.CharField(max_length=255, default="15% OFF") discounted_price = models.IntegerField(default=230) savings = models.IntegerField(default=230) special_discount = models.BooleanField(default=False) rating = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5)) ) image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) content =RichTextField() highlights = RichTextField() itinerary = RichTextField() image_1= models.ImageField(blank=True,null = True) image_2= models.ImageField(blank=True,null = True) image_3= models.ImageField(blank=True,null = True) date_created = models.DateField() def __str__(self): return self.package_name class TopActivities(models.Model): package = models.ForeignKey(Package, … -
DJANGO - Error with complex AND, OR condition in 1 FILTER, but works with many FILTERS ? Why?
I had this query which I did quite nice query = LeadtimeConfig.objects.filter(last_mile__isnull = True, Q(origin = _origin_area) | Q(origin__isnull = True), Q(destination =_destination_area) | Q(destination__isnull=True), Q(delivery_type = _delivery_type) | Q(delivery_type__isnull = True) | Q(delivery_type = '') ) However, I keep receiving this error query = LeadtimeConfig.objects.filter(last_mile__isnull = True, Q(origin = _origin_area)|Q(origin__isnull = True), Q(destination =_destination_area)|Q(destination__isnull=True), Q(delivery_type = _delivery_type) | Q(delivery_type__isnull = True) | Q(delivery_type = '') ) ^ SyntaxError: positional argument follows keyword argument But when I did this : query = LeadtimeConfig.objects.filter(last_mile__isnull = True) .filter(Q(origin = _origin_area) | Q(origin__isnull = True)) .filter(Q(destination =_destination_area) | Q(destination__isnull=True)) .filter(Q(delivery_type = _delivery_type) | Q(delivery_type__isnull = True) | Q(delivery_type = '')) It works -
how can users upload file into Django model?
With these codes, I want each user to be able to upload their own file in their own model forms.py: class sp_UserNewOrderForm(forms.Form): file= forms.FileField() models.py: class sp_Order(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.owner.username class sp_OrderDetail(models.Model): order = models.ForeignKey(sp_Order, on_delete=models.CASCADE) file= models.FileField() def __str__(self): return self.order.owner.username views.py: @login_required def add_user_order(request): new_order_form = sp_UserNewOrderForm(request.POST or None) if new_order_form.is_valid(): order = sp_Order.objects.filter(owner_id=request.user.id).first() if order is None: order = sp_Order.objects.create(owner_id=request.user.id) file= new_order_form.cleaned_data.get('file') order.sp_orderdetail_set.create(file=file) # todo: redirect user to user panel # return redirect('/user/orders') return redirect('/') return redirect('/') HTML: <form method="post" action="/add_sp"> {% csrf_token %} {{ form.count }} <button type="submit" class="btn btn-primary container"> upload </button> </form> But these codes do not create the model. what is the problem? -
How to add picture into datatables?
I'm using datatables to show the data from API which I saved in my local database. I want to add images to every record when click on some edit button to show the form and to have the possibility to browse picture in my machine and render it in another column in datatables. Any idea or resource how to achieve this? my current jQuery script: <script> $(document).ready(function() { var data; fetch("http://192.168.1.80:8000/fetchapi/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); $('#datatable').DataTable( { data: data.users, deferRender: true, scrollY: false, scrollX: false, scrollCollapse: true, scroller: true, columns: [ { data: "user_id" }, { data: "user_name" }, { data: "user_email" }, { data: "status" }, { data: "user_type" }, ] } ) }) } ); $(document).ready( function () { $.fn.DataTable.ext.pager.numbers_length = 5; var table = $('#example').DataTable({"pagingType": "full_numbers"}); } ); </script> -
(Hidden field author) This field is required
I followed this django tutorial on how to restrict other users in the blog post posts. (The Video Link: https://www.youtube.com/watch?v=TAH01Iy5AuE&list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi&index=17) But I get this message when I try to post (Hidden field author) This field is required? This is my views.py file from .forms import PostForm, EditForm class AddPostView(CreateView, LoginRequiredMixin): model = Post form_class = PostForm template_name = "add_post.html" # fields = "__all__" This is my forms.py file from .models import Post, Category from django import forms # choices = [('uncategorized', "uncategorized"), ("gaming", "gaming"), ("youtube", "youtube"),] choices = Category.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ("title", "title_tag", "author", "category", "body") widgets = { "title": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title"}), "title_tag": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title Tag"}), "author": forms.TextInput(attrs={"class": "form-control", "id": "Rashaad", "value": "", "type": "hidden"}), # "author": forms.Select(attrs={"class": "form-control"}), "category": forms.Select(choices=choice_list, attrs={"class": "form-control"}), "body": forms.Textarea(attrs={"class": "form-control", "placeholder": "Body"}), } class EditForm(forms.ModelForm): class Meta: model = Post fields = ("title", "title_tag", "category", "body") widgets = { "title": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title"}), "title_tag": forms.TextInput(attrs={"class": "form-control", "placeholder": "Title Tag"}), # "author": forms.Select(attrs={"class": "form-control"}), "category": forms.Select(choices=choice_list, attrs={"class": "form-control"}), "body": forms.Textarea(attrs={"class": "form-control", "placeholder": "Body"}), } my add_post.html file {% extends 'base.html' %} {% block content …