Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ALLOWED_HOSTS when using Django behind Caddy reverse proxy
Using Django behind a Caddy reverse proxy leads to a lot of error notifications like the following: Invalid HTTP_HOST header: 'www.msftncsi.com'. You may need to add 'www.msftncsi.com' to ALLOWED_HOSTS. Isn't Caddy supposed to only pass on requests from my own domain to the Django app? The respective Caddyfile is: mydummyyapp.com { # Use 'route' to allow this ordering. Otherwise, 'file_server' would need to come last. route { # Redirects just to be nice. redir /login /accounts/login permanent # Serve static files directly. file_server /static/* { root /home/apps/mydummyapp } # Pass on everything else to django/daphne. reverse_proxy 127.0.0.1:8000 } log { output file /var/log/mydummyapp_access.log { roll_size 1gb roll_keep 5 roll_keep_for 168h } } } I would assume that requests that do not originate at mydummyyapp.com to not even reach the Django/daphne server running at 127.0.0.1:8000. Naive and wrong? -
Is there a way to put the paragraph on multiple lines in limited space?
i have this project: User should be able to add a comment in a box but the box is have max lenght of 250 characters. This is my snippet from Html: <div class="comment-box"> <div class="list-comments"> <span> Comments </span> <hr> {%for i in comments.all%} <div class="comment"> <p class="description"> {{i.description}} </p> <p> <i><b>{{i.user}}</b>, {{i.date}}</i> </p> </div> {%empty%} <p> There aren't comment here! </p> {%endfor%} </div> <div class="leave-comment"> <form action="{% url 'add_comment' item.id %}" method="POST"> {% csrf_token %} {{comment_form}} <input type="submit" value="Send comment" class="button"> </form> </div> Mine css .comment-box{ margin: auto; display: flex; flex-wrap: wrap; width: 60%; border: 1px groove rgb(133, 133, 219); border-radius: 5px; } .list-comments{ padding: 5px; flex-basis: 60%; overflow-y: scroll; height: 450px; width: 450px; } .leave-comment{ padding-top: 50px; font-size: 16px; margin-left: 10px; flex-basis: 30%; background-color: white; text-align: center; } .comment{ border: 1px groove rgb(133, 133, 219); border-radius: 5px; padding: 10px; background-color: white; } .description{ max-width: 320ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } And this is the result The problem is that the comment is displayed with ... and not entire comment. Is there a way to put the comment on multiple lines in limited space? -
How can I skip authentication in a Django APIRequestFactory call?
So essentially I want to make a request to a ViewSet without requiring to authenticate, does Django APIRequestFactory make this possible? This works: from django.test import TestCase from .views.SomeViewSet from rest_framework.test import APIRequestFactory class ViewSetsTest(TestCase): ... ... ... def test_db_instance_viewset(self): api_request = APIRequestFactory.patch("", HTTP_AUTHORIZATION="Bearer xyz123ppouu") detail_view = SomeViewSet.as_view({'patch': 'update'}) response = detail_view(api_request) self.assertEqual(response.status_code, 200) But the issue is, the bearer token is something that is generated 'somewhere far' every 24 hours. Hence, I want to skip authentication. Thank you in advance. -
If length of String > 33 then move to next line with same y axis coordinate in Reportlab PDF Django
Hey i have this type of code which helps me to build pdf from data render from database. But there is a problem if length of a string is too big then it overcross to other string like in billing head. Any Solution regarding this according to my code. This Pdf built through reportlab python in django. Image Attached. As u see Values in Charges Discription Overcross the coloumn of SAC section. I want to put half characters to next line if the length of Charges Discription is too big to avoid overcross. def sea_export_local_invoice_pdf(request, pk): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = ' filename="local_invoice.pdf"' c = canvas.Canvas(response) # _______________________ get object ___________________ lir_fed = SeaExLocalInvoiceReceivable.objects.get(pk=pk)c.setFont('Helvetica-Bold', 9) c.drawString(85, 548, 'Charges Description') c.line(201, 560, 201, 300) c.drawString(210, 548, 'SAC') c.line(237, 560, 237, 300) c.drawString(243, 548, 'Unit') c.line(268, 560, 268, 300) c.drawString(273, 548, 'Rate') c.line(296, 560, 296, 280) c.drawString(298, 548, 'Ex.Rate') c.line(332, 560, 332, 280) c.drawString(340, 548, 'Amount') c.line(381, 560, 381, 300) c.drawString(384, 548, 'IGST') c.line(407, 560, 407, 300) c.drawString(410, 548, 'CGST') c.line(437, 560, 437, 300) c.drawString(440, 548, 'SGST') c.line(467, 560, 467, 165) c.drawString(474, 548, 'Tax Amt') c.line(519, 560, 519, 280) c.drawString(533, 548, 'Total') c.line(25, 540, 575, 540) a = '07' # a = … -
"getattr(): attribute name must be string" in django rest framework
There is an error "getattr(): attribute name must be string",i don't know how to solve this, views.py class VideoViewset(ResponseViewMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): def post(self, request, *args, **kwargs): try: serializer = VideoSerializers(data=request.data) if not serializer.is_valid(): return self.jp_error_response('HTTP_400_BAD_REQUEST', self.error_msg_list(serializer.errors)) serializer.save() return self.jp_response(s_code='HTTP_201_CREATED', data={'video': serializer.data}) except Exception as e: print(e) return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) serializers.py class VideoSerializers(serializers.ModelSerializer): class Meta: model = Video fields = ('video_type', 'relevance', 'difficulty', 'category', 'sub_category') models.py class Video(BaseModel, Timestamps, SoftDelete): relevance_difficulty_choices = ( ('low', 'Low'), ('medium', 'Medium'), ('high', 'High') ) video_type_choices = ( ('micro', 'Micro'), ('mini', 'Mini'), ('grand', 'Grand') ) create_date = models.DateTimeField(auto_now_add=True, null=True) video_type = models.CharField(max_length=50, choices=video_type_choices, null=False) relevance = models.CharField(max_length=50, choices=relevance_difficulty_choices, null=False) difficulty = models.CharField(max_length=50, choices=relevance_difficulty_choices, null=False) category = models.CharField(max_length=254, null=False, blank=False) sub_category = models.CharField(max_length=254, null=False, blank=False) created_by = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE) contributer = models.CharField(max_length=254, null=False) file_url = models.CharField(max_length=254, null=True, blank=False) -
ValueError at /api/addorderitem badly formed hexadecimal UUID string in Django rest framework
I tried to create a random unique string in a charfield using uuid but it is giving me above error. My model is: from utils import create_new_ref_number class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True orderItem_ID = models.UUIDField(max_length=12, editable=False,default=str(uuid.uuid4())) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,) -
Is it good way to write all js code in html page and include that html page in another html page insted of .js file?
I just want to know that is it a good idea to write all javascript code in an HTML(instead of writing in .js) file and that the HTML file will be included in another HTML file. I'm writing js code in an HTML file because I can access Django templates in an HTML file. Django templates are not accessible in pure JS files. -
Django Framworks: URL error? my tutor has no clue
Maybe you could help me with the following issue, I'm following a course and changing the code for my own project. Original code: https://github.com/ckz8780/boutique_ado_v1 My project: https://github.com/asforrest/Milestone-4-CarFix The issue is coming from this page: https://8000-brown-earwig-xhtc2sv5.ws-eu03.gitpod.io/subscriptions/ And has to do with this app: https://github.com/asforrest/Milestone-4-CarFix/tree/master/subscriptions Any idea? Thank you. -
how to use a redirect Mixin in CreateView django for Registration Form?
i have created my registration form with CreateView, can i use custom Mixins to restrict user reach a webpage? i am trying to restrict users when they are --> is_authenticated. these are my codes, as you can see i have created a custom Mixin but it doesn't work! Mixins.py class UserAthenticatedRedirectRegisterMixin(): def dispatch(self,request,*args,**kwargs): if self.reuqest.user.is_authenticated: return redirect("account:home") else: return super().dispatch(request, *args, **kwargs) Views.py class Register(UserAthenticatedRedirectLoginMixin,CreateView): form_class = SignupForm template_name = "account/register.html" def form_valid(self,form): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) mail_subject = "ایمیل فعال سازی حساب کاربری" message = render_to_string('account/activate_account.html',{ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') # gereftane email user email = EmailMessage( mail_subject,message,to=[to_email] ) email.send() return HttpResponse('لینک فعال سازی به ایمیل شما ارسال شد. <a href="/login">ورود</a>') anyway to fix this problem? -
pushing into a declared list not working in jquery
I am trying to put id values into a list in jquery but I get an error saying that push is not a function. somehow it seems that my list is turned into an object. I am using django. It all worked but suddenly it stoped. why? <script> $(document).ready(function() { $("button").click(function() { var vals = []; console.log('cons1:',vals) console.log('cons1:',typeof(vals)) $.each($("input[name='checkb']:checked"),function(vals) { vals.push($(this).attr('id')); }); console.log('cons2:',vals) alert("values2: " + vals.join(", ")); }); }); </script> -
Show specific form-fields at specific places in the HTML template (Django)
I have a form with three fields field1,field2,field3 - in my template I want to show those fields at specific places, and not together. At best field1, field2 are "shown together" and then a bit further down, I need field3 to be shown. My HTML is right now <div class="content-section"> <div class="add-link-wrapper"> <legend class="border-bottom mb-4"> Add product </legend> <form method="POST"> {% csrf_token %} {{form|crispy}} <div class="form-group"> <button class="btn btn-outline-info" type="submit">Add</button> </div> </form> </div> </div> but {{form}} shows all three fields - I would like to have it a bit like <div class="content-section"> <div class="add-link-wrapper"> <legend class="border-bottom mb-4"> Tilføj produkt til tracking </legend> <form method="POST"> {% csrf_token %} {{form.field1 and form.field2 |crispy}} <!-- Show field1 and field 2 here --> <div class="form-group"> </div> </form> some more html code </div> {{form.field3|crispy}} <!-- Show field3 here --> <button class="btn btn-outline-info" type="submit">Add</button> </div> -
Show all possible error-messages for fields (Django)
In Django, say I have a User field and I want to change the "this user alread exist" error message. I know I can parse a dictionary in e.g forms.py like class MyForm(Form): . . . error_messages={"unique": ("Wups, enter a unique username")} but it requires I know the key/value pair, which might not always be obvious what the key is. Is there a way (in the Django documentation it seems pretty scattered) where these error-message key/value pairs are, or what is the most easy way to find those? -
referring to associated field in another model in Django
I want to create a table with buyer's name and the fruits that he bought based on that season. class Buyer(models.Model): name = models.CharField(max_length=10) season = models.ForeignKey(Season, on_delete=models.CASCADE) fruit = models.ManyToManyField(Fruit, through=‘Season’, related_name=‘seasonal_fruit’) class Fruit(models.Model): fruit_name = models.CharField(max_length=10) class Season(models.Model): season = models.CharField(max_length=10) fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE) The above code throws the following error: app.Season: The model is used as an intermediate model by 'app.Buyer.fruit', but it does not have a foreign key to 'Buyer' or 'Fruit'. -
Why do I get "reverse accessor for 'model.user' clashes with reverse accessor for 'model.account' even though I set AUTH_USER_MODEL?
I've seen the same question posted a few times, and the answer is always.. did you set AUTH_USER_MODEL? Here is the snippet from my settings.py file. ## Accounts AUTH_USER_MODEL = 'accounts.Account' Here is the error message I am getting when I try to generate migrations for my new model. ERRORS: admin.LogEntry.user: (fields.E304) Reverse accessor for 'LogEntry.user' clashes with reverse accessor for 'LogEntry.account'. HINT: Add or change a related_name argument to the definition for 'LogEntry.user' or 'LogEntry.account'. logs.LogEntry.account: (fields.E304) Reverse accessor for 'LogEntry.account' clashes with reverse accessor for 'LogEntry.user'. HINT: Add or change a related_name argument to the definition for 'LogEntry.account' or 'LogEntry.user'. Here is the model that is causing the problem. class LogEntry(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.SET_NULL, blank=True, null=True) entry = models.TextField() I'm developing on sqlite3, so I have tried destroying the sqlite file and emptying my migrations folders. I run the command again and get the same result. I know that I could define a related_name on the field, but I would rather address the underlying problem. It shouldn't class with LogEntry.user because I am not creating any association between those models directly... or am I? -
Date range filter doesn't work as expected
I made a custom filter by date range with a django-filter library. class AccountingStockBalanceFilter(filters.FilterSet): date = filters.DateFromToRangeFilter(method="filter_date") @staticmethod def filter_date(queryset, name, date_slice): queryset = queryset.filter( invoice_product__invoice__supplier_creation_date__range=( date_slice.start, date_slice.stop, ) ) return queryset but if I do request like this http://localhost/api/accounting/stock_balances/?date_after=2021-03-01&date_before=2021-04-20 then it won't return anything...Though if I do request like http://localhost/api/accounting/stock_balances/?date_after=2021-02-01&date_before=2021-04-20 (I have changed date_after from 2021-03-01 to 2021-02-01), then I'll get in some entries in response with only the date of 2021-02-11. Then I made this filtering with a built-in filter() function like this: class AccountingStockBalanceFilter(filters.FilterSet): date = filters.DateFromToRangeFilter(method="filter_date") @staticmethod def filter_date(queryset, name, date_slice): queryset = filter( lambda wp: date_slice.start < wp.invoice_product.invoice.supplier_creation_date < date_slice.stop if wp.invoice_product.invoice.supplier_creation_date else wp, queryset, ) ids = [wp.id for wp in queryset] queryset = ( WarehouseProduct.objects.prefetch_related( "invoice_product__invoice__order__serviceinvoice_set", "invoice_product__invoice__service_set", "invoice_product__invoice__order__invoice_set__invoiceproduct_set", "invoice_product__invoice__invoiceproduct_set", "invoice_product__invoice__order__serviceinvoice_set__service_set", "invoice_product__invoice__self_serial_number", "invoice_product__invoice__self_proforma_serial_number", ) .select_related( "nomenclature__category__unit_of_measure", "invoice_product__invoice__order", "invoice_product__invoice__supplier", "locator", ) .filter( ~Q(nomenclature__type=Nomenclature.Type.ASSEMBLY), locator__warehouse_id=1, quantity__gt=0, id__in=ids, ) ) return queryset And it works correctly returning me a response with dates like 2021-03-06 e.g. but it costs extra database queries and I got 18 queries instead of 9. What am I doing wrong with django's filter()? BTW here is my view: from warehouse_api.models import Product as WarehouseProduct class AccountingStockBalancesView(ListAPIView): """API endpoint that returns a list of … -
Django Rest Framework: Is it possible to allow users to get/post data via ajax but not directly via viewset url?
I'm learning web development since a few months, so the answer could be quite trivial: I also couldn't find anyone asking that before so it's probably a really stupid question, neither in the [drf official doc](https://www.django-rest-framework.org/api-guide/viewsets/). Most similar question I could find is [this](https://stackoverflow.com/questions/57328203/django-user-with-limited-permissions-can-see-all-default-models-in-rest-framewor), and I understood it but did not really help me. My problem is that I have a drf viewset very simple, like this, in views.py: from .serializers import MyModelSerializer from .model import MyModel from django.contrib.auth.decorators import login_required @method_decorator(login_required, name='dispatch') class MyViewSet(viewsets.ModelViewSet): serializer_class = MyModelSerializer queryset = MyModel.objects.all() My urls.py looks like this: from views import MyViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('myviewset', MyViewSet, basename='myviewset') urlpatterns = [ path('viewset/', include(router.urls)), # ... other paths ... ] Inside my javascript (jQuery) code I call this url, in some ajax requests: it performs well and that's wonderful. Unfortunately, users can do the same thing directly by going to /viewset/myviewset/ and this is a real problem to me. So, is it possible or am I simply using the wrong module to do this? In that case, what other module/objects could I use? Thank you very much. -
Django Password Reset timeout
Whenever I want to reset password, my browser goes timeout. I have the same EMAIL_HOST_USER and EMAIL_HOST_PASSWORD than in dev environment, yet it doens't work in Production. settings.py with open('/etc/config.json') as config_file: config = json.load(config_file) LOGIN_URL = 'login' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config.get('EMAIL_USER') EMAIL_HOST_PASSWORD = config.get('EMAIL_PASSWORD') config.json { "SECRET_KEY":"***", "EMAIL_USER":"***", "EMAIL_PASSWORD":"***" } -
Show checkbox only when a specific form-field is non-empty (Django)
I have a model class my_model(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE,null=True) start_price = models.FloatField(default=0) last_price = models.FloatField(default=0) will_buy= models.BooleanField(default=False) and my form class my_form(forms.ModelForm): class Meta: model = my_model In my template I want will_buy first being visible when last_price is filled in. Best of all will be as a kind "slow unpacking", but first of all I just need it to be hidden when last_price is empty. -
pipenv virtual environment name disappears everytime the VS Code terminal is refreshed
I was working on a Django project after activating the virtual environment created through pipenv. The virtual environment name given in brackets (lead-manager-full-stack-8btqndKQ) in the vs code terminal disappears everytime i runpython manage.py runserver When i select the powershell as terminal and runs pipenv shell again in order to activate the environment again it shows : Shell for C:\Users\USER.virtualenvs\lead-manager-full-stack-8btqndKQ already activated. No action taken to avoid nested environments. But it still doesn't show the virtual environment name inside the brackets like it is supposed to show. Then i tried to run pipenv shell in cmd and this time it shows the virtual environment name in bracket in the terminal. But whenever i reload the terminal or choose new terminal, it doesn't show the virtual environment. There must be a way to activate the virtual environment at all time, even after reloading the terminal if i am in a folder containing virtual environment right? Because activating virtual environment everytime i reloads the terminal doesn't seem like a good approach. -
Django tables connection
I have 3 django tables connected like this: Is there anyway to make a querry for table Table that will get id_equip from table equip? models.py class Vendor(models.Model): vendor_name = models.CharField(max_length=50) def __str__(self): return self.vendor_name class Equipment(models.Model): equipment_name = models.CharField(max_length=50) id_vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None) def __str__(self): return self.equipment_name class Table(models.Model): table_name = models.CharField(max_length=100) id_vend = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None) id_equip = models.ManyToManyField(Equipment) -
Shiftleft scan (SLS) vulnerability on read_excel of uploaded file
I'm working on a website using Django and to be safe we run everything through shiftleft scan. The website allows user to import "assignments" using an excel file. The question is: how do I do this safely such that it is shiftleft scan compliant? The code: class ImportView(generic.FormView): template_name = 'assignments/import.html' form_class = ImportForm success_url = reverse_lazy('assignment_import') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): # handle upload here assignments = pd.read_excel(request.FILES['file'].file) for i, assignment in assignments.iterrows(): assignment_obj = Assignment() assignment_obj.name = assignment['name'] assignment_obj.save() return self.form_valid(form) else: return self.form_invalid(form) The ciritical vulnerability the SLS returns: { "rule_id": "taint-traversal", "rule_name": "Directory Traversal", "severity": "CRITICAL", "cwe_category": "CWE-22", "owasp_category": "a5-broken-access-control", "source": { "label": "request", "line_number": 188, "path": "/app/survey/views.py" }, "source_trigger_word": "Framework function URL parameter", "source_type": "Framework_Parameter", "sink": { "label": "~call_2 = ret_pandas.read_excel(request.FILES[file].file, ...", "line_number": 196, "path": "/app/survey/views.py" }, "sink_trigger_word": "read_excel(", "sink_type": "Exfiltration", "type": "Vulnerability", "reassignment_nodes": [], "description": "Exfiltration of data (Path Traversal) due to user data from `request in views.py:188` influencing file operations in `views.py:196`.", "short_description": "Exfiltration of data (Path Traversal) due to user data from `request in views.py:188` influencing file operations in `views.py:196`." }, My MEDIA_ROOT is setup as follows (from settings.py, I realize that mix the pathlib.Path with os.path, … -
AttributeError: module 'djangoschool' has no attribute 'wsgi'
I once finished deploy it on another server without this error, but I try this with new server and install my new window server 2019.I start do it again but it got an error. I deploy my django project on IIS.I follow this tutorial https://www.youtube.com/watch?v=CpFU16KrJcQ When I browse my website on localhost. It got error messages like this. Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\python37\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handler handler = getattr(handler, name) AttributeError: module 'djangoschool' has no attribute 'wsgi' StdOut: StdErr: web.config <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python37\python.exe|c:\python37\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub2\wwwroot\djangoschool" /> <add key="WSGI_HANDLER" value="djangoschool.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="djangoschool.settings" /> </appSettings> </configuration> settings.py """ Django settings for djangoschool project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - … -
I am unable to format the logic for my project models in django
I'm working on a student result management app. I have other parts working but the logic of the marks entry and model creations have sent me lost. I need entry for marks for the various subjects for a group of students(students in particular streams for specific exams). A student belongs to a stream which belongs to a class which belongs to a particular school. I've created models for Marks, Subjects, School, Klass, Exam, Stream, Student. I've had no issues with the Student, Klass, Stream and School models. My problem is on the entry of the marks. Should I have Subjects and Marks models or can all these be put in one model or does each subject have it's model? Here are my trials. class Students(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE,help_text='A school must have a name') adm = models.IntegerField(unique=True,validators=[MinValueValidator(0), MaxValueValidator(1000),] ) name = models.CharField(max_length=200,help_text="Student's name") klass = models.ForeignKey(Klass, on_delete=models.CASCADE,null=True) stream = models.ForeignKey(Stream,on_delete=models.CASCADE,null=True) class Klass(models.Model): name = models.CharField(max_length=20,help_text='Class/Form in the school') school = models.ForeignKey(School,on_delete=models.CASCADE) class Stream(models.Model): name = models.CharField(max_length=50) klass = models.ForeignKey(Klass,on_delete=models.CASCADE) school = models.ForeignKey(School,on_delete=models.CASCADE) class Exam(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) year = models.ForeignKey(Year,on_delete=models.SET_NULL, null=True) term = models.ForeignKey(Term,on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=20) klass= models.ManyToManyField("students.Klass", related_name='klass',) class Marks(models.Model): school = models.ForeignKey(School,on_delete=models.SET_NULL,null=True,blank=True) year = models.ForeignKey(Year,on_delete=models.SET_NULL,null=True,blank=True) term = … -
Centos OS apache Django web app 500 Internal Server Error
I want to deploy my django website on Centos 8. My application is in /var/www/html/myproject. I created a new conf file (myproject.conf) in /etc/httpd/conf.d Alias /static/ /var/www/html/myproject/static/ WSGIScriptAlias / /var/www/html/myproject/myapp/wsgi.py WSGIPythonPath /var/www/html/myproject <Directory /var/www/html/myproject/myapp> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/html/myproject/static> Require all granted </Directory> When I restart the apache and I put the ip address, I have a 500 Internal Server Error. I don't understand why I got this error. Thank you for your help. -
Go to specific page using Django Pagination with restframework
I have a question about going to specific page using pagination in Django restframework. (Data needs to be rendered to HTML) Example: model.py class Book(models.Model): title = models.CharField(max_length=30) author = models.CharField(max_length=30) views.py class BookListView(viewsets.ModelViewSet): permission_classes = (AllowAny, ) template_name = 'booklist.html' queryset = Book.objects.all() renderer_classes = [TemplateHTMLRenderer] pagination_class = BookPagination serializer_class = BookSerializer def list(self, request): queryset = Book.objects.all() serializer = ProtocolSerializer(queryset, many=True) page = self.paginate_queryset(serializer.data) return self.get_paginated_response(page) I can show the paginated item with the codes above. And there are next and previous links in HTML. However, I need page list like [1,2,3,....], not just next and previous. I can view the data on the 3rd page by just click button 3. I need some steps to do this. 1: Retrieve the target page number(I don't know how to do this) 2: Get the data of on that page 3: Render to HTML I hope someone can help me with this.