Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Problems with Ubuntu + Django + Apache2
I'm a beginner to Django and apache2. Here's my server environment: ubuntu 18.04 + Apache/2.4.29 (Ubuntu) + Python 3.6.8 + Django 2.2.6 + MySQL 5.7 I follow the Django document: https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/modwsgi/ and also some solution from InterNet. Here's my /etc/apache2/sites-available/gostar.conf now: <VirtualHost *:80> LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so AddHandler wsgi-script.py DocumentRoot /var/www/html/kyle/GoStar4F1/src/GoStar # Alias /media/ /media/ # Alias /static/ /static/ LoadModule wsgi_module modules/mod_wsgi.so # <Directory /media> # Require all granted # </Directory> # <Directory /static> # Require all granted # </Directory> WSGIDaemonProcess GoStar python-path=/var/www/html/kyle/GoStar4F1/src/GoStar \ python-home=/home/kyle/testDjango WSGIProcessGroup GoStar WSGIScriptAlias / /var/www/html/kyle/GoStar4F1/src/GoStar/GoStar/wsgi.py \ process-group=GoStar application-group=%{GLOBAL} <Directory /var/www/html/kyle/GoStar4F1/src/GoStar/GoStar> <Files wsgi.py> #Require all granted Order deny,allow Allow from all </Files> </Directory> And I did the following command: $ sudo a2ensite gostar.conf $ sudo systemctl reload apache2 #response: Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. so I $ systemctl status apache2.service #response: ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) (Result: exit-code) since Tue 2019-10-29 13:56:38 CST; 27min ago Process: 28191 ExecStop=/usr/sbin/apachectl stop (code=exited, status=1/FAILURE) Process: 29149 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=1/FAILURE) Process: 28364 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS) Main PID: 28375 … -
Django application server requirement with ubuntu + apache + mod_wsgi
I need your guidence on setting up my production server for django application. Below are the details of my application . Its a simple website which connects 3 database/applications that is already available in 3 separate VM's. The 3 applications are: 1) MSSQL database(which will provide details of a parent table(model) and 15 or 20 child tables(model). when each record from the parent model is opened it fetches the details of other child tables and display them in the page) 2) Document management system to stream the files(average of 10 files with each documents with 150-200 kb size of each document) related to the records that are fetched with the previous step. 3) Mysql database (which will give few more details related to the parent model from the parent model) Now my new VM which we are going to setup should have a simple RDBMS created with postgreg to hold the basic details of django and the website users along with python and django. The current user base is 5-6 users at a time and may grow to 10 -12. Can some one recommend a capacity planning for the above requirement for DJANGO+ UBUNTU + APACHE + MOD_WSGI( please suggest … -
How to fix the html code in django template
The template has an issue. That is tag in my base.html shows that there is no closing tag and in list.html file the warnings are about {% already exists(expected endif instead of endfor) Python 3.8.0rc1,pip 19.3.1,and the django version is 2.2.6 list.html <ul> <li {% if not category %}class="selected"{% endif %}> <a href="{% url "shop:product_list"%}">All</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected"{% endif %}> <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> </li> {% endfor %} </ul> base.html <head> <meta charset="utf-8" /> <title>{% block title %}My shop{% endblock %}</title> <link href="{% static" css/base.css" %}" rel="stylesheet"> </head> The attribute name is missing(points at c.slug). I'm an amateur,I've just started working with django,please do help,Thanks in adavance. -
Django urls.py: best way to not have a page number in the first page of a list view?
Right now I have a list view that displays 10 posts per page: The urls would be something like this: www.example.com/posts/1 (First page with 10 results) www.example.com/posts/2 (Next page with 10 results) and my urls.py looks something like this: path('posts/<int:page>', PostList.as_view(), name='post-list'), I want to be able to have the first page of posts also visible when there is no number, for example: www.example.com/posts (First page with 10 results) The only way that I have been able to solve this is by adding another line in the urls.py that points to the same view and that has the same name. path('posts', PostList.as_view(), name='post-list'), path('posts/<int:page>', PostList.as_view(), name='post-list'), Is this the appropriate way of doing this or is there a better way? Many thanks! -
Docker run application in a volume
In my django docker app i would to use a volume for manage my application file here is my Dockerfile: FROM python:3.6-alpine EXPOSE 8000 RUN apk update RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk add postgresql-dev gcc python3-dev musl-dev VOLUME /var/lib/cathstudio/data WORKDIR /var/lib/cathstudio/data COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -t /var/lib/cathstudio/data -r requirements.txt ENV PYTHONUNBUFFERED 1 ENV PYTHONPATH /var/lib/cathstudio/data COPY . /var/lib/cathstudio/data ENTRYPOINT python /var/lib/cathstudio/data/manage.py runserver 0.0.0.0:8000 but when i run my app: docker run -d -it --rm --link postgres:postgres --name=cathstudio myrepo/app_studio:latest i get python: can't open file '/var/lib/cathstudio/data/manage.py': [Errno 2] No such file or directory the same also if i in my Dockerfile write just ENTRYPOINT python manage.py runserver 0.0.0.0:8000 where is my file wrong? how can i run my app using a volume for storing app files? So many thanks in advance -
Django AJAX working but test case failing in POST request
So I have this unit test: def test_delete_product(self): self.api_client.login(username=self.username, password=self.password) path = self.get_url_for_test_against_endpoint('/product/delete/') data = {'id': self.product.id} response = self.api_client.post(path=path, data=json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, 302) self.assertFalse(Product.objects.filter(id=self.product.id).exists()) and this view def post(self, request): pid = request.POST.get('id') get_object_or_404(Product, id=pid).delete() return redirect('product:products') My entry in urls.py is path('product/delete/', product_delete_view, name='product_delete') The AJAX I am using to call this view is: <script> const url = "{% url 'product:product_delete' %}" var id = "{{ product.id }}" var intId = parseInt(id) const data = { id: intId, csrfmiddlewaretoken: '{{ csrf_token }}' , contentType:'application/json'} $('#{{ product.id }}').click(function () { $.post(url, data, function (data, status) { console.log(`${data} and status is ${status}`) location.reload(true) }) }) </script> What works: When I call this view through ajax, everything works fine and the product is deleted. What does NOT work When I run the test, it fails because response.status_code returns 404. While trying to find out what the problem is, I used pdb.set_trace() in view and I found that request.POST.get('id') returns None. If I hard code pid to 1 test case passes which means in the view, it is unable to get id from the request which is weird because it is able to do that same through ajax call. If I do … -
Apache24 Django Don't download files. Not found. The requested resource was not found on this server
I am setting django project to Apache24 for windows. Everything works except download file from client. Upload also works. I have Hierarhical directory by attachments//. If I set BEDUG=TRUE then downloads working. Help me, please, where i wrong? below httpd.conf LoadFile "c:/<>/python/python36/python36.dll" LoadModule wsgi_module "c:/envs/myproject/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias / "c:/<myproject>/wsgi.py" WSGIPythonHome "c:/envs/myproject" WSGIPythonPath "c:/<myproject>" Alias /static/ "c:/<myproject>/static/" <Directory "c:/<myproject>/static"> Require all granted </Directory> <Directory c:/<myproject>> <Files wsgi.py> Require all granted </Files> </Directory> # Другие полномочия, если потребуются <Directory c:/<myproject>/attachments> Require all granted </Directory> -
How to access my domain on digital ocean droplet?
I amt trying to deploy a django website on digitalocean server.I am new to digital ocean.i added my domain on my droplet.when i access my domain it shows site can't be reached message.How can i activate my domain.Any help is appreciated. -
Django NoReverseMatch when trying to logout
I have a django view function signout that I want to call form a form/template. When i click logout, it calls the function but the redirect after doesnt work. I get the message Reverse for '<WSGIRequest: POST '/account/signout'>' not found. '<WSGIRequest: POST '/account/signout'>' is not a valid view function or pattern name. Urls.py urlpatterns = [ path('register', views.register, name='register'), path('login', views.login, name='login'), path('signout', views.signout, name='signout'), path('dashboard', views.dashboard, name='dashboard'), ] Views.py def signout(request): if(request.method == 'POST'): auth.logout(request) messages.success(request, 'You are logged out!') return redirect(request, 'index') Template form <form action="{% url 'signout'%}" id="logout" method="POST"> {% csrf_token %} <input type="hidden"> <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-sign-out-alt"></i> Log Out</button> </form> What is going wrong?? The rest of routes work just fine and they are declared the same as signout. -
"SMTP AUTH extension not supported by server." on live server, works fine on localhost
This is the code I'm using (after declaring a model): def order_update(sender, instance, created, **kwargs): subject = 'subject' from_email = 'sender@mail.com' to = 'receiver@mail.com' text_content = f'text' html_content = f'html' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=False) post_save.connect(order_update, sender=Order) On localhost it works fine, sends an e-mail whenever an object is being created. But when I upload it to a live environment, Ubuntu 16.04, it gives me this error: SMTP AUTH extension not supported by server.. -
Prevent Redis/Celery scheduled tasks from being processed multiple times - Django on Heroku
I am looking for some advice. I use Celery/Redis Scheduled tasks to check changes via an API request every 10 seconds. If there is a change, a database object will be created and when it did some calculations a boolean named is_called will be set to True, to prevent duplicates. This worked fine locally and for a time also on Heroku, but since an update (nothing in the task code changed) the worker seems busy and uses up to 7 ForkPoolWorkers. For example the ForkPoolWorker-1 will work on the same task as ForkPoolWorker-7, which ignores the is_called = True boolean and gives me duplicate calculations with 1 database object created. What's the best way to serve a task only to 1 ForkPoolWorker at a time? I read the docs and google research, but it's not completely clear what and how to do this. I build in Django on Heroku. -
TypeError: kitty() got an unexpected keyword argument 'startdate'
\\I am getting this error -TypeError: kitty() got an unexpected keyword argument 'startdate' which i am clueless. Probably a date format issue. model ----- //Model of the Kitty from django.db import models import datetime from datetime import datetime from multiselectfield import MultiSelectField class kitty(models.Model): company = models.CharField(max_length=3) code = models.CharField(max_length=6) type = models.CharField(max_length=10) name = models.CharField(max_length=100) startdate = models.DateField durinmonths = models.IntegerField() enddate = models.DateField totalmembers = models.IntegerField() totalamount = models.FloatField() installmentamount = models.FloatField() status = models.CharField(max_length=1) creator = models.CharField(max_length=20) cretime = models.DateTimeField(default=datetime.now) updator = models.CharField(max_length=20) updtime = models.DateTimeField(default=datetime.now, blank = True) //View that i have created View ----- from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect import datetime from .models import kitty from django.db import transaction from django.contrib import messages import re def index(request): return render(request, 'kitty/index.html') def kitty_save(request): if request.method == 'POST': company = "1" code1 = request.POST['code'] type1 = request.POST['type'] name = request.POST['name'] startdate = request.POST['startdate'] durinmonths = request.POST['durinmonths'] enddate = request.POST['enddate'] totalmembers = request.POST['totalmembers'] totalamount = request.POST['totalamount'] installmentamount = request.POST['installmentamount'] print(startdate) status = "A" creator = request.user kitty1 = kitty(company=company, code=code1, type=type1,name=name, startdate=startdate, durinmonths=durinmonths, enddate=enddate,totalmembers=totalmembers,totalamount=totalamount,installmentamount=installmentamount, status=status, creator=creator) kitty1.save() transaction.commit() messages.success(request, 'Kitty Added') return HttpResponseRedirect(request.path_info) else: return render(request, 'kitty/kitty.html') //URl file to render URL --- … -
The current path, % url 'accounts:logout' %, didn't match any of these
So, everything in my newly started Django project is working fine except this logout url. I'm using django=1.11.17 and python 3. When I try to logout from the accounts, this is the error I get. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%25%20url%20'accounts:logout'%20%25 Using the URLconf defined in conspiverse_project.urls, Django tried these URL patterns, in this order: ^$ [name='home'] ^test/$ [name='test'] ^thanks/$ [name='thanks'] ^admin/ ^accounts/ ^accounts/ The current path, % url 'accounts:logout' %, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. accounts/urls.py from django.conf.urls import url, include from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"login/$", auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), url(r"logout/$", auth_views.LogoutView.as_view(template_name="thanks.html"), name="logout"), url(r"signup/$", views.SignUp.as_view(), name="signup"), ] project/urls.py from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r"^$", views.HomePage.as_view(), name="home"), url(r"^test/$", views.TestPage.as_view(), name="test"), url(r"^thanks/$", views.ThanksPage.as_view(), name="thanks"), url(r"^admin/", admin.site.urls), url(r"^accounts/", include("accounts.urls", namespace="accounts")), url(r"^accounts/", include("django.contrib.auth.urls")), ] settings.py STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR,'static')] LOGIN_REDIRECT_URL = 'test' LOGOUT_REDIRECT_URL = 'thanks' I tried verifying the URL paths, cross-checked almost everything, it is driving me crazy. Huge … -
Django doesn't provide a DB representation for AnonymousUser- Django rest api
I tried to change password without the traditional way. Give old password and new password, update the old password. I used UpdateApiView.But i get the following error. Django doesn't provide a DB representation for AnonymousUser I tried passigng Authorization token in header using POST MAN. But Same error. view.py class ChangePassword(generics.UpdateAPIView): serializer_class = serializers.ChangePasswordSerializer model = models.Customer def get_object(self, queryset=None): obj = self.request.user return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get("new_password")) self.object.save() return Response("Success.", status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) serializers.py class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) urls.py path('update_password', views.ChangePassword.as_view()), -
Django Forms (with crispy forms) - Am I over complicating this? Is there an easier way?
I've created a form in Django using crispy forms, it works fine but I can tell just by looking at it that I've most likely over engineered it. It's a lot of very similar pieces of code. How should I actually be doing this? I would presume there's a much better way. class New_Contact(forms.Form): title = forms.CharField(label=False, max_length=10,required=False) givenName = forms.CharField(label=False, max_length=255) middleName = forms.CharField(label=False, max_length=255,required=False) surname = forms.CharField(label=False, max_length=255) jobTitle = forms.CharField(label=False, max_length=255,required=False) companyName = forms.CharField(label=False, max_length=255,required=False) department = forms.CharField(label=False, max_length=255,required=False) businessHomePage = forms.CharField(label=False, max_length=255,required=False) assistantName = forms.CharField(label=False, max_length=255,required=False) homePhones = forms.CharField(label=False, max_length=255,required=False) # phones mobilePhone = forms.CharField(label=False, max_length=255,required=False) # phones businessPhones1 = forms.CharField(label=False, max_length=255,required=False) # phones businessPhones2 = forms.CharField(label=False, max_length=255,required=False) # phones homeAddress = forms.CharField(label=False,required=False,widget=forms.Textarea(attrs={'style': 'height: 8em'})) # addresses businessAddress = forms.CharField(label=False,required=False,widget=forms.Textarea(attrs={'style': 'height: 8em'})) # addresses emailAddresses1 = forms.CharField(label=False, max_length=255,required=False) # mail emailAddresses2 = forms.CharField(label=False, max_length=255,required=False) # mail def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['title'].widget.attrs['placeholder'] = 'Title' self.fields['givenName'].widget.attrs['placeholder'] = 'First Name' self.fields['middleName'].widget.attrs['placeholder'] = 'Middle Name' self.fields['surname'].widget.attrs['placeholder'] = 'Last Name' self.fields['mobilePhone'].widget.attrs['placeholder'] = 'Mobile' self.fields['homePhones'].widget.attrs['placeholder'] = 'Home Phone' self.fields['emailAddresses1'].widget.attrs['placeholder'] = 'Email' self.fields['emailAddresses2'].widget.attrs['placeholder'] = 'Email' self.fields['homeAddress'].widget.attrs['placeholder'] = 'Address' self.fields['companyName'].widget.attrs['placeholder'] = 'Company Name' self.fields['department'].widget.attrs['placeholder'] = 'Department' self.fields['jobTitle'].widget.attrs['placeholder'] = 'Job Title' self.fields['assistantName'].widget.attrs['placeholder'] = 'Assistant Name' self.fields['businessHomePage'].widget.attrs['placeholder'] = 'Website' self.fields['businessPhones1'].widget.attrs['placeholder'] = … -
Django Postgres user vs apache user
I have set up environment variables for django user to connect to the postgres database, but the env variables are becoming the apache user as well, which won't give access to httpd file If I take out the postgres user env variables then the pod starts. If I add in the postgres user variables then the apache process can't access the httpd file -
Django-Admin Site: Combine two models in one html
here is my code in admin.py @admin.register(StudentsPaymentSchedule) class StudentsPaymentSchedule(admin.ModelAdmin): list_display = ('Students_Enrollment_Records','Payment_Schedule','Amount','Remarks') ordering = ('Students_Enrollment_Records',) @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type' ,'School_Year') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') Can you guys help me, If I click here, I just want to look like this -
How add blank line in messages django?
I have a line of my code messages.error(request, 'A soma das despesas correntes e das despesas de capital ultrapassam o valor total do projeto.') popping up a message in my template A soma das despesas correntes e das despesas de capital ultrapassam o valor total do projeto. But I want to get a new line after the point, like: A soma das despesas correntes e das despesas de capital, ultrapassam o valor total do projeto. How do I get that? I tryed A soma das despesas correntes e das despesas de capital, \n ultrapassam o valor total do projeto. and A soma das despesas correntes e das despesas de capital, < br \> ultrapassam o valor total do projeto. and {{ message|linebreak }} -
How to access all content from request.session | Django
I want to print all the content of request.session (a django.contrib.sessions.backends.db.SessionStore object). It looks like a dictionary but I am not able to parse it like so: for item in request.session: print(item) # returns KeyError '0' I found a quirky workaround that works in my case: for i in range(1, 4): print(request.session.get(str(i))) Though this is not very maintainable. What is a good way of fetching all the data from this session object? -
csrf verification failed request aborted when uploading media
I am getting the "csrf verification failed request aborted" error when uploading media files via forms. I am setup on a digital ocean server and everything else seems to be running fine. I have the {% csrf_token %} tags in my forms and have the proper settings in my settings.py: 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', My django version: django.VERSION (2, 2, 6, 'final', 0) Static files are also being served no problem. Everything works correctly on my local machine and I don't have this problem. Not sure where to go from here. -
search results from a Django model method including the results from earlier calls to the same method
I have a Django Model that tracks email message IDs as the message passes through different servers. It has a models.ForeignKey field to itself, so we can chain them together to follow the full path of a message through many servers. The model has a 'get_children()' method that recursively looks for all messages descended from the given message. class Msg(models.Model): hostname = models.CharField(max_length=48) qid = models.CharField(max_length=24) received_from = models.ForeignKey( "self", blank=True, null=True, default=None, on_delete=models.SET_DEFAULT ) def get_children(self, parent_messages=set()): for r in Relay.objects.filter(received_from=self): r._get_all_child_messages(parent_messages) parent_messages.add(self) p = list(parent_messages) parent_messages = set() return p If I run a single query from the Django shell, it works as expected. "Solo" messages return only themselves. Messages with multiple child/descendant messages are found as well. >>> r = Relay.objects.get(qid='xo2') >>> r.get_children() [<Relay: server2 foo>, <Relay: server3 bbb>, <Relay: server1 xo2>] If I kill and restart the shell, the next query works as expected, fetching a single message >>> r = Relay.objects.get(qid='singletonMsg') >>> r.get_children() [<Relay: server5 singletonMsg>] But if I run get_children() repeatedly within a single Django shell session, it always includes the results of the previous get_children() calls. >>> r = Relay.objects.get(qid='singletonMsg') >>> r.get_children() [<Relay: server5 singletonMsg>] # expected result >>> >>> r = Relay.objects.get(qid='xo2') … -
Django REST Framework: Direct assignment to the reverse side of a related set is prohibited. Use AuditedClientPeriodMatrices.set() instead
I have the next issue and i dont know why because im send: % self._get_set_deprecation_msg_params(), TypeError: Direct assignment to the reverse side of a related set is prohibited. Use AuditedClientPeriodMatrices.set() instead. Could you help me please? JSON { "clientName": "PRUEBA", "AuditedClientPeriods": [ { "clientNamePeriod": "PRUEBA", "AuditedClientPeriodMatrices": [ { "AuditedClientPeriodMatrizDatas": [] } ] } ] } serializers.py from rest_framework import serializers from ...models import Audited_Client, Audited_Client_Period, Audited_Client_Period_Matriz, Audited_Client_Period_Matriz_Data class AuditedClientPeriodMatrizDataSerializer(serializers.ModelSerializer): class Meta: model = Audited_Client_Period_Matriz_Data fields = [ 'id', 'clientName', 'clientNamePeriod', 'ANIO', 'MES', 'GRUPO', 'DOCUMENTO_MATRIZ', 'NOMBRE_MATRIZ', 'DOCUMENTO_CLIENTE', 'NOMBRE_CLIENTE', 'CNAE_ACTIVIDAD', 'SEGMENTO_IRB', 'ID_EXPEDIENTE', 'IND_DRC', 'SEGMENTO_DRC_S_CIRCULAR', 'TIPO_OPERACION_SUBTIPO_IRB', 'COD_INSOLVENCIA', 'CLASIFICACION', 'CONCEDIDO', 'DPTO_NORMAL', 'DPTO_VIG_ESPECIAL', 'DPTO_DUDOSO', 'DPTO_MUY_DUDOSO', 'DPTO_TOTAL' ] class AuditedClientPeriodMatrizSerializer(serializers.ModelSerializer): #Ojo esta variable esta en related_name en models.py AuditedClientPeriodMatrizDatas = AuditedClientPeriodMatrizDataSerializer(many=True) class Meta: model = Audited_Client_Period_Matriz fields = [ 'id', 'clientName', 'clientNamePeriod', 'matriz', 'author_matriz_audited_client_period', 'created_matriz', 'updated_matriz', 'AuditedClientPeriodMatrizDatas' ] class AuditedClientPeriodSerializer(serializers.ModelSerializer): #Ojo esta variable esta en related_name en models.py AuditedClientPeriodMatrices = AuditedClientPeriodMatrizSerializer(many=True) class Meta: model = Audited_Client_Period fields = [ 'id', 'clientName', 'clientNamePeriod', 'author_audited_client_period', 'created_audited_client_period', 'updated_audited_client_period', 'AuditedClientPeriodMatrices' ] class AuditedClientSerializer(serializers.ModelSerializer): #Ojo esta variable esta en related_name en models.py AuditedClientPeriods = AuditedClientPeriodSerializer(many=True) class Meta: model = Audited_Client fields = [ 'id', 'clientName', 'author_audited_client', 'created_audited_client', 'updated_audited_client', 'AuditedClientPeriods' ] #validated_data es un diccionario # y .pop(key) busca la clave especificada … -
Django admin Site 2 foreignkeys
class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Remarks = models.TextField(max_length=500,null=True,blank=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class ScheduleOfPayment(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) /admin StudentsEnrollmentRecordAdmin class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'amount' ,'School_Year') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') admin.site.register(StudentsEnrollmentRecord,StudentsEnrollmentRecordAdmin) ScheduleOfPayment @admin.register(ScheduleOfPayment) class ScheduleOfPayment(admin.ModelAdmin): list_display = ('Education_Levels','Payment_Type','Display_Sequence','Date','Amount','Remark','Status') ordering = ('Education_Levels','Payment_Type','Display_Sequence') list_filter = ('Education_Levels','Payment_Type') how to combine this two table/listview in Django admin site? please help me, i already research this for 3 days but i cant find solve this problem. -
Can't understand how work @login_required in Django
I look how work @login_required in Django and I can't understand one row. lambda u: u.is_authenticated Please explain me, from where appear 'u'. I can't understand where does this argument come from. Full code def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator -
why homepage is not showing while runserver in django and after uploading in heroku it's not working?
starting new in django, first i run pipenv and pipenv shell in cmd and then i have stated the "pages" project in django. in pages_project/settings.py file: ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ................... 'pages.apps.PagesConfig', # new ] TEMPLATES = [ {................. 'DIRS': [os.path.join(BASE_DIR,'templates')],.....} in pages_project/urls.py: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] in pages/views.py: from django.views.generic import TemplateView Create your views here. class HomePageView(TemplateView): template_name='home.html' class AboutPageView(TemplateView): template_name='about.html' in pages/urls.py: from django.urls import path from .views import HomePageView,AboutPageView urlpatterns = [ path('about/', AboutPageView.as_view(), name='about'), path('', HomePageView.as_view(),name='home'), ] i have created three html files in pages/templates/..... home.html, base.html and about.html home.html code: {%extends 'base.html'%} {%block content%} Homepage {%endblock%} about.html code: {%extends 'base.html'%} {%block content%} About Page {%endblock%} base.html code: Home|About {%block content%} {%endblock%} running python manage.py runserver base.html and about.html is working but when i click on home link it is showing the following: Using the URLconf defined in pages_project.urls, Django tried these URL patterns, in this order: admin/ about/ [name='about'] [name='home'] The current path, home, didn't match any of these. but about link is working and base is showing the front face. this is my first problem. after installing heroku and …