Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImproperlyConfigured at /catalog/borrowed/
I'm a beginner in python-django coding. Currently I am trying to complete the challenge on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication but I am facing LoanedBooksByAllUserListView is missing the permission_required attribute. Define LoanedBooksByAllUserListView.permission_required, or override LoanedBooksByAllUserListView.get_permission_required(). In urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name='authors'), path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), path('borrowed/', views.LoanedBooksByAllUserListView.as_view(), name='all-borrowed'), ] In views.py from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, 'num_visits': num_visits, } # Render the HTML template index.html with the data in the context variable. return render(request, 'index.html', context=context) from django.views import generic class BookListView(generic.ListView): model = Book paginate_by = 5 class BookDetailView(generic.DetailView): model = Book class AuthorListView(generic.ListView): model … -
How to differ the web engage curl request in Django without affecting the performance of the API?
How to differ the WebEngage curl request in Django without affecting the performance of the API? -
What is / in python?
I'm wondering about / in python. I know that it divides two integers, but I've seen something like this 'NAME': BASE_DIR / 'db.sqlite3' Thank you in advance. -
How do I render individual radio buttons in my django template
I want to individually render radio button in my django template. Is that possible?? models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title forms.py: class ComplaintForm(ModelForm): highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) class Meta: model = Complaint fields = ['title', 'description', 'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') return cleaned_data template: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field" name="title">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr " name="description">{{form.description}}</div> {{message}} <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" name="submit" class="btn btn-secondary save-btn" value="Submit"><i class="fas fa-save"></i> Save</button> </form> </div> <!-- Right Container --> <div class="col right-pro-con"> <div class="img-cir"> <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} {% if request.user.profile.profile_pic.url %} <img src={{request.user.profile.profile_pic.url}} alt="" width="100px" height="100px" class="pro-img"> {% else %} <img src="{% static 'profileimages/msi.jpg' %}" alt="" width="100px" height="100px" class="pro-img"> {% endif %} <p class="my-name">{{request.user.profile.first}} <p> <p class="my-email-id">{{request.user.profile.email}}</p> </form> </div> <p class="prio-txt">Priority</p> <div class="form-check"> … -
Custom BarChart using Chart.js
I'm using normal Bar Chart, but I want to custom the Labels and Bars to make the same output in the picture below. Please give me some idea or reference. Thank You. Bar Chart image Here's my code in normal Chart, but I want to make same output in the picture var dept_chart = new Chart(ctx1, { type: 'bar', data: { labels: ["Department 1","Department 2", "Department 3", "Department 4"], datasets: [{ label: 'Sum of Product Amount', data: item_data, backgroundColor: [ 'rgba(23, 128, 173)', 'rgba(207, 154, 50)', 'rgba(196, 195, 187)', ], borderColor: [ 'rgba(23, 128, 173)', 'rgba(207, 154, 50)', 'rgba(196, 195, 187)', ], borderWidth: 1 }, { label: 'Sum of Discount Amount', fill: true, backgroundColor: 'rgba(207, 154, 50)', borderColor: 'rgb(207, 154, 50)', }, { label: 'Sum of Net Amount', fill: true, backgroundColor: 'rgba(196, 195, 187)', borderColor: 'rgb(196, 195, 187)', }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); window.onload = function(){ var ctx1 = document.getElementById("report_monthly").getContext("2d"); window.myBar = new Chart(ctx1).Bar(dept_chart, { responsive : true }); } } Im using Django in backend and API, $.ajax({ method: "GET", url: URLreport, success: function(report_data){ item_data = report_data.item setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) Chart output what … -
How to generate puppet script with python django
I am start to learning puppet, I have a file in my web and when I press run button, my web will generate a puppet script describe my file. Anyone can give me some advice to do this. You can see the photo for more virtualization. Image demo for generate a puppet script to describe the file -
403 Forbidden when coming up with a new page for staff user instead of normal user: Forbidden (CSRF token missing or incorrect.): /accounts/login/
I'm a beginner in python-django coding. Currently I am trying to complete the challenge on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication but I am facing the 403 Forbidden issue on my login page. This issue happen when i try to add a page for a staff user. Appreciate if anyone could help me. Thank you Below are the codes: In urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name='authors'), path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), path('borrowed/', views.LoanedBooksByAllUserListView.as_view(), name='all-borrowed'), ] In views.py from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, 'num_visits': num_visits, } # Render the HTML template index.html with the data in the context variable. return … -
"Missing filename. Request should include a Content-Disposition header with a filename parameter." Error? Problem with django-simplejwt
I am trying to work with djangorestframework-simplejwt and trying to follow this tutorial: https://www.jetbrains.com/pycharm/guide/tutorials/django-aws/rest-api-jwt/ Currently I'm at this point where I have a superuser account already set up and I'm using Postman to send a request to http://127.0.0.1:8000/api/token to access the TokenObtainPairView view from simplejwt. But I keep on getting this problem: I'm not sure why I'm getting this error. When I do to Headers and add in the key "Content-Disposition" and value "attachment; filename=file". I get a different problem where my body is populated with the username and password but the response keeps on saying the field is required even though I provided in Body. This is my code for urls.py urls.py from django.contrib import admin from django.urls import path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView ) urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] I'm not sure what is going on and any help would be appreciated. Thank you so much! -
best Error handling with csv reader in django
So I've got a small application, and I am uploading bulk data via CSV reader. Everything uploads great, provided I go through my CSV with a fine comb. The only issue is the error handling. Whether it works or fails, I get a 500 error page. Then I have to look through the data base to find at what point the CSV reader failed or compare row count to ensure all values went through. Here is the code for my view: def admin_calv_csv(request): template = "calves/admin_calv_csv.html" prompt = { 'order': 'Order should be eid, visual_id, dairy_id, dob, ship_in_date, ship_out_date, slug, sex, breed, destination, medical_history, milk_consumed, program,' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a CSV') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) for _ in data_set: try: next(io_string) for column in csv.reader(io_string, delimiter=','): _, created = Calf.objects.update_or_create( eid=column[0], visual_id=column[1], dairy_id=column[2], dob=column[3], ship_in_date=column[4], ship_out_date=column[5], slug=column[6], sex=column[7], breed=column[8], destination=column[9], medical_history=column[10], milk_consumed=column[11], program=column[12], ) except IntegrityError as e: error_message = str(e.__cause__) messages.error(request, error_message) test = str(_) messages.info(request, 'error on' + _) pass context = {} return render(request, template, context, messages) -
Handling 2 Django forms - passing data from one to the other
I have 2 Django forms: one, where the user uploads an article, and the second, where the user can edit a list of article words into one of three buckets (change the column value: bucket 1-3). forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ('name','last_name','docfile',) class Doc_wordsForm(forms.ModelForm): class Meta: model= Doc_words fields= ('id','word','word_type','upload',) #upload is foreign key value After the user uploads the article, I have a function in views.py that breaks down the uploaded article into a list of words. I want these words to be looped through and added to a database table(where each row is a word), then have the second form reference these words. Views.py # upload_id = (request.GET.get("id")) if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() data = request.FILES['docfile']#.read().decode('UTF-8') words=get_keywords(data) results=list(find_skills(words)) for word in results: form2 = Resume_words(word = word, word_type='exclude', upload = upload_id) form2.save() return render(request, 'word_list.html',{ "results":results }) else: form = UploadForm() return render(request, 'upload.html', { 'form':form }) I having trouble pulling these pieces together and I'm desperate for help of any kind! I having trouble with the following steps: I don't know how to capture the current users instance when saving to the table. I get an … -
How do I query data from the database base on user in a completely separated frontend Django REST
So I have this basic model: class Text(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=255) def __str__(self): return self.title so usually when you're using regular Django and you want to query Text from the database based on the user you would do: def main_page(request): userTexts = Text.objects.filter(user=request.user) context = {} return render(request, '', context) but now I've been using Django REST React stack and built a completely separated frontend and the only way I access the data from the backend is by making HTTP request to it, so now request.user wont work anymore because it's just going to return anonymousUser fortunately though I already have an authentication system working and already have a user object inside my react state all I have to do is design a view and an API call to query the data from the backend but I cant imagine how to do both of those things. -
Django Queryset filter array field by exact string
so I haven't been working with Django for too long. I am running into a problem filtering a queryset by the exact name of a string of arrays that is passed into it. Currently, I am filtering the queryset by icontains, which works. For example the current implementation works like this: If I pass in one string called "test" my queryset will be filtered and show deals with tags "test1" "test2" and "test3". This is not what I want. I want to filter by the exact name of the strings that are passed in. So if I have a "test" as one of the strings then my queryset will only search for test, not anything that is contained into it. I've tried multiple implementations, such as switching from icontains to iexact, and exact. Goal. Filter queryset by array of multiple tags. old query: values is an array of tags (strings) that are passed in values = value.replace(" ", "").split(",") return qs.filter(reduce(operator.or_, (Q(tags__iontains=item) for item in values))) What I have tried: I have tried passing in the iexact with the list of values like below. I have also tried just passing iexact, and then passing in only one hardcoded string from … -
How to restrict access by group membership, roles, and ID in Django using class-based views
I'm a relative newbie, working on a Django directory-based app that serves many companies, and I want to know best practices/standards for restricting access by company-membership, user ID, and user role. The app is structured so that a company manager (CM) has superuser-like permissions for that company only, and then company team members (CTM) may or may not have restricted permissions to modify pages specific to that group/company only. The public user needs to be able to access the company's pages so companies are separated using their slug in the url. So company "A"'s home page is found by example.com/A/home. Using LoginRequiredMixin effectively restricts access to only logged-in users but logged-in users can be of the following types in this app: a public member, an app admin (like myself), a company manager, a company team member. I need to make sure of the following: 1) the logged-in user belongs to the company that is trying to be accessed (ie if I am a public user or belong to company "B" I cannot access company "A" restricted pages simply by being logged in and entering the slug in the url), 2) the logged in user has necessary permissions, even if the … -
How to correctly install django with pip in a virtualenv on windows?
Hi I am very new to python, I am trying to the django framework. However, I don't seem to be able to install django with pip on my venv. Whenever I enter pip install django on my venv file this happens. Unable to create process using 'c:\users\jason lo\appdata\local\programs\python\python39\python.exe "C:\Users\Jason Lo\desktop\learndjango\venv\Scripts\pip.exe" install django' Any help is greatly appreciated, thanks. -
Django TemplateDoesNotExist - moving working project from windows to linux
I am working to move a Django project from windows to linux. It works great in windows, but I am running into all sorts of errors trying to get it running on linux. The current issue I am facing is saying the template cannot be found. I have tried all the recommendations I can find online so I am looking for a little help. Furthermore, I am a little confused because one of the directories it says it is looking in which has the actual file, Django still does not see it. Here is part of the error in the picture showing which directory it looked at to find the file. The file is actually in this directory, so I am not sure what is going on. One thing I noticed is the back slash is incorrect, not sure where this directory is located in the code to fix this? django.template.loaders.filesystem.Loader: /home/pi/Desktop/MarketJungle/project_settings/templates/Website\base_template.html (Source does not exist) Settings.py Error -
Django BooleanField(default=False) Confusion
Can anyone help me out here? I am inserting data into my postgreSQL DB. admin_created is a booleanfield set to false by default. I've provided a true value for the first workout, but left the second workout blank for the booleanfield. Based on my understanding it should automatically be set to false, but i'm getting the error message below. Any ideas on why this is happening? #.sql INSERT INTO main_app_workout(name, description, admin_created) VALUES ('Yoga', 'Roll up your yoga mat and discover the combination of physical and mental exercises that have hooked yoga practitioners around the globe.', 'True'); INSERT INTO main_app_workout(name, description) VALUES ('Boxing', 'Ready to get your sweat on? Learn the six basic punches to build the foundation of an experienced boxer.'); #models.py class Workout(Model): name = models.CharField(max_length=40) description = models.TextField() exercises = ManyToManyField(Exercise, blank=True) admin_created = models.BooleanField(default=False) #Error code psql:db/create_main_exercises.sql:49: ERROR: 23502: null value in column "admin_created" of relation "main_app_workout" violates not-null constraint -
error[2] no such file found when using django with pipeline
I am editing a site on Python 3.9 with Django 2.0.13, and am having some issues getting the site up. The most current one seems to be caused by pipeline. The traceback is (and I apologize for the length....) Traceback: File "/project/lib/python3.9/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/project/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 158. response = self.process_exception_by_middleware(e, request) File "/project/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 156. response = response.render() File "/project/lib/python3.9/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/project/lib/python3.9/site-packages/django/template/response.py" in rendered_content 83. content = template.render(context, self._request) File "project/lib/python3.9/site-packages/django_jinja/backend.py" in render 106. return mark_safe(self.template.render(context)) File "/project/lib/python3.9/site-packages/jinja2/asyncsupport.py" in render 76. return original_render(self, *args, **kwargs) File "/project/lib/python3.9/site-packages/jinja2/environment.py" in render 1008. return self.environment.handle_exception(exc_info, True) File "/project/lib/python3.9/site-packages/jinja2/environment.py" in handle_exception 780. reraise(exc_type, exc_value, tb) File "/project/lib/python3.9/site-packages/jinja2/_compat.py" in reraise 37. raise value.with_traceback(tb) File "/project/src/apps/users/templates/users/login.html" in <module> 1. {% extends 'users/_layout.html' %} File "/project/lib/python3.9/site-packages/jinja2/environment.py" in render 1005. return concat(self.root_render_func(self.new_context(vars))) File "/project/src/apps/users/templates/users/login.html" in root 14. {{ error }} File "/project/src/apps/users/templates/users/_layout.html" in root File "/project/src/templates/layout.html" in root 20. {# === STYLES === #} File "/project/src/templates/layout.html" in block_critical_css 72. {% endblock static_js %} File "/project/src/libs/pipeline/templatetags/pipeline_plus.py" in _inline_stylesheet 110. return node.render_compressed(package, name, 'css') File "/project/lib/python3.9/site-packages/pipeline/templatetags/pipeline.py" in render_compressed 66. return self.render_compressed_output(package, package_name, File "/project/lib/python3.9/site-packages/pipeline/templatetags/pipeline.py" in render_compressed_output 80. return method(package, package.output_filename) File "/project/src/libs/pipeline/templatetags/pipeline_plus.py" in render_css 49. str(staticfiles_storage.get_modified_time(path).timestamp()), File … -
Object of type BoundField is not JSON serializable
A have a chain of OneToMany relations (one) Construction -> Camera -> Frame -> Event models.py def name_image(instance, filename): return '/'.join(['images', str(instance.name), filename]) class Construction(models.Model): """ Объект строительства""" developer = models.ForeignKey( Developer, related_name="constructions", on_delete=models.CASCADE ) name = models.CharField(max_length=100) plan_image = models.ImageField(upload_to=name_image, blank=True, null=True) address = models.CharField(max_length=100) coordinates = models.PointField(blank=True) deadline = models.DateTimeField(default=timezone.now, ) workers_number = models.IntegerField(default=0) machines_number = models.IntegerField(default=0) def __str__(self): return self.name class Camera(models.Model): building = models.ForeignKey( # not important Construction, related_name="cameras", on_delete=models.CASCADE ) name = models.CharField(max_length=100) url = models.CharField(max_length=100) ... class Frame(models.Model): """ Фото с камеры """ camera_id = models.ForeignKey( Camera, related_name="frames", on_delete=models.CASCADE ) ... class Event(models.Model): frame_id = models.ForeignKey( Frame, related_name="events", on_delete=models.CASCADE ) ... I want to output data about Camera in EventSerializer (GET method). I am using get_construction method I want to use ConstructionSerializer for Construction object ( <class 'api_buildings.models.Construction'>) But I have an error Object of type BoundField is not JSON serializable How can I fix this error (I know, that I can use model_to_dict, but I want to use ConstructionSerializer) class EventSerializer(serializers.ModelSerializer): time = serializers.DateTimeField(format=TIME_FORMAT) camera = serializers.SerializerMethodField() construction = serializers.SerializerMethodField() frame = serializers.SerializerMethodField() developer = serializers.SerializerMethodField() class Meta: model = Event fields = ( 'id', 'frame_id', 'frame', 'developer', 'camera', 'construction', 'type_of_event', 'class_name', 'grn', … -
Question: What is the best js, back-end frameworks together for big projects with Multi User Authentication?
I Have A Big Project And Want To Know What is The Best js And Back-end Frameworks And This website Contains a lot of Features Such As Multi User Authentication And Much More ... -
TypeError: data.map is not a function, even though the data is an array (i think)
Im using Django rest to send data to react: [ { "id": 1, "username": "Dewalian", "question": [ { "id": 5, "title": "how to cook?" }, { "id": 6, "title": "how to exercise?" } ] }, { "id": 2, "username": "Edward", "question": [] }, { "id": 3, "username": "Jeremy", "question": [] } ] and then fetch it using a custom hook from a video tutorial: import useFetch from "./UseFetch"; import DataList from "./DataList"; const MainContent = () => { const {data: question, isPending, error} = useFetch("http://127.0.0.1:8000/api/user/"); return ( <div className="main-content"> {error && <div>{error}</div>} {isPending && <div>Loading...</div>} {question && <DataList data={question} />} </div> ); }; export default MainContent; finally i map it on another component: const DataList = (data) => { return ( <div> {data.map(user => ( <div key={user.id}> <p>{user.username}</p> </div> ))} </div> ); } export default DataList; but i get "TypeError: data.map is not a function". Im pretty sure the problem is on the json, but i dont know what's wrong. so, what's wrong and how to fix this? thanks. -
get values from input and excute function django
I have two inputs in my HTML page and I want to send them to a function in Django views.py. so I have a table as shown : And I want to take the Quantity and disc values from the inputs + another value from the from and the HTML code is: <table id="table_id" class="table-wrapper table-sm"> <thead class="thead-light"><tr> <th>Item Description</th> <th>Quantity</th> <th>Disc %</th> <th></th> </tr></thead> <tbody> <tr > {% for Field in AllItemes %} <td>{{Field.Item_Code}}</td> <td> <input class="form-control mr-1" placeholder="1" name="select_date" type="number" min="0" pattern="\d*"/></td> <td> <input class="form-control mr-1" placeholder="0" name="select_Disc" type="number" min="0" pattern="\d*"/></td> <td><a href="{% url 'Up_InvoiceTACH' Field.Item_Code select_date select_Disc %}" class="btn btn-info btn-sm">Add</a></td> </tr> {% endfor %} </tbody> </table> my views.py is: def Up_InvoiceTACH(request, id_itm, id_itm2 , id_itm3): pass and the URL is like this: path('up_InvoceTACH/<int:id_itm>/<int:id_itm2>/<int:id_itm3>/', views.Up_InvoiceTACH, name='up_InvoceTACH'), So how do I send those three parameters especially from the inputs? -
Reducing the number of queries in a Django app using a raw query
Objects of MyClass have associated history table that is populated by the database triggers, so not under control of the application. Current code has a method to query the history: class MyClass: @classmethod def history_query(cls, id): query = f'select * from history_table' if id: query = f"{query} where id='{id}'" def history(self): return MyClass.objects.raw(self.history_query(self.id)) The problem is when I list all the objects, the history table gets queried once for every object, creating thousands of queries... I'm trying to speed up the sluggish application by changing this to one query. Here's my current attempt: class MyClass: _full_history = None @classmethod def history_query(cls, id=None): query = f'select * from history_table' if id: query = f"{query} where id='{id}'" def history(self): if self._full_history: return self._full_history[self.id] return MyClass.objects.raw(self.history_query(self.id)) @classmethod def history_by_id(cls): if cls._full_history is None: history_list = MyClass.objects.raw(cls.history_query()) history_dict = {} for item in history_list: id = item.id history_dict[id] = history_dict.get(id, []) history_dict[id].append(item) cls._full_history = history_dict return cls._full_history Is there a better or more efficient way to do this? Would it be possible to do it with prefetch? -
how to rendering post form in django rest framework and some errors
from django.shortcuts import render from django.shortcuts import get_object_or_404 from .serializers import missionSerializer from .models import Mission_list from rest_framework.renderers import JSONRenderer from rest_framework.renderers import TemplateHTMLRenderer from rest_framework import viewsets from django.http import HttpRequest from rest_framework.views import APIView # Create your views here. class mission_list(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'mission_list/mission_list.php' def get(self, request, pk): mission = get_object_or_404(Mission_list, pk=pk) serializer = missionSerializer(mission) return Response({'serializer': serializer, 'mission': mission}) def post(self, request, pk): mission = get_object_or_404(Mission_list, pk=pk) serializer = missionSerializer(mission, data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer, 'mission': mission}) serializer.save() return redirect('mission-list') views.py in this code I got "init() takes 1 positional argument but 2 were given" error. how can I solve this error or have any other way to post data in D.R.F with html template? -
Nginx 1.18.0 | The plain HTTP request was sent to HTTPS port
I run Ubuntu 20.04 with Nginx 1.18.0 I have installed my Django app and everything works fine in http. I bought ssl certificate from GoGetSSL and installed it but I have this freaking issue. I tried every thing but nothing works, this is my Nginx Configurations: server { listen 443 default_server ssl; server_name www.elamanecc.com.dz elamanecc.com.dz; ssl_certificate /etc/nginx/ssl/www_elamanecc_com_dz/ssl-bundle.crt; ssl_certificate_key /etc/nginx/ssl/www_elamanecc_com_dz/www_elamanecc_com_dz.key; # Logs access_log /home/elamancc/logs/nginx_site1/access.log; error_log /home/elamancc/logs/nginx_site1/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/elamancc/commerce/pre/pre-elamanecc; } location /media/ { root /home/elamancc/commerce/pre/pre-elamanecc; } location / { proxy_set_header Host $host; #include proxy_params; proxy_pass http://unix:/run/ccenamale.sock; } client_max_body_size 7M; } If I set ssl off; as some mentioned in other solutions, then it will redirect me to http and display this message (I don't want http, I only want https works) : Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. -
Django ForeignKey.limit_choices_to with ForeignKey to ManyToMany scenario
I have a complex relation scenario as shown below. I'd like limit_choices_to Questions that are related to JobChecklistAnswer.job_checklist.checklist on JobChecklistAnswer.question. How can I filter those Questions as Q object (or callable as the docs say)? class Checklist(models.Model): name = models.CharField(_("name"), max_length=150) description = models.CharField(_("description"), max_length=150) class Question(models.Model): checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE) question = models.CharField(_("question"), max_length=200) class Job(models.Model): ... ... class JobChecklist(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE) class JobChecklistAnswer(models.Model): job_checklist = models.ForeignKey(JobChecklist, on_delete=models.CASCADE) # FIXME: Add limit_choices_to query question question = models.OneToOneField(ChecklistItem, on_delete=models.CASCADE) answer = models.TextField(_("answer"))