Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Jinja2, showing form field is required
How can I make an if condition in Jinja to display something in case that the field is required? if tried f.is_required | f.required | f.widget.attrs['required'], and none of them seem to work, and I'm not able to find information about this in the documentation. I also don't mind just to add another attribute, I'm just not able to understand how do I access them. my form: class PositionForm(ModelForm): salary_min = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'placeholder': 'Minimum Salary'})) salary_max = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'placeholder': 'Maximum Salary'})) years_of_experience = forms.IntegerField(required=False, widget=forms.NumberInput( attrs={'placeholder': 'Years of previous experience'})) class Meta: model = Position widgets = { 'name': forms.TextInput(attrs={'placeholder': 'Name'}), 'description': forms.Textarea(attrs={'placeholder': 'Job Description'}), 'city': forms.TextInput(attrs={'placeholder': 'City'}), } fields = '__all__' -
Is it possible to use signals when data are added/updated directly from postgresql database?
I've used post_save signal in my app to send email when new user account is created. It works. But, when I deploy my project in production, I create first accounts using data migrations. Doing like this, signal is not triggered. Is thier a way to ahceive this goal? I have read about trigger in Postgresql (LISTEN/NOTIFY) and celery to use asynchronous task but I would like a more simpler way... -
using Django URLs in templates
I need to send a JavaScript variable to the view and based on that variable,a new page opens.I've send the variable using ajax and it works well but when I call the URL to open the page based on sent variable,the variable gets 0. Here is my template : <a onclick="click(this.id)" id="author[i].name" href="{% url 'app:export-pdf' %}" >export pdf</a> author[i].name is the JavaScript variable that I send it to view in this way : function click(name){ $.ajax({ type: 'POST', url: '{% url 'app:export-pdf' %}', data: {'name': name }, }); }; This is part of my view if needed : @csrf_exempt def battery_render_pdf_view(request): name = request.POST.get('name') print(name) data = MyModel.objects.filter(name=name) When I run the code, I'll get for example : Mike None The view get None as name but it must get Mike for filtering. What is wrong with my code?(I think it happens because I call the Url 2 times but I didn't find out how to correct it.) Thank you all. -
What is the use of the sites framework in setting up google login through django-allauth in django?
I am learning to provide social log ins through django-allauth in django through this tutorial https://medium.com/@whizzoe/in-5-mins-set-up-google-login-to-sign-up-users-on-django-e71d5c38f5d5. In this tutorial in step7 it says to add a site in the admin dashboard's site section and fill in the domain name and display name as 127.0.0.1:8000. And then it says to add a social application under the social accounts section, and fill in the client id and secret key, the provider and name but we also have to add the site which we created above. According to my reasoning, the site should be 127.0.0.1:8000 to link the log in to this site but I can still log in through google even when I change the domain name to anything with www. as the starting and .com as the ending. For example, www.example.com,www.google.com, and even absurd domain names, but still I can log in through google. Can anyone explain why this is happening? -
Is there a way to stop a repeating task in Django Background-Tasks
I've been successful in creating a repeating task in Django Background-Tasks that I can start with a button on my web page. I know need a way to stop this repeating tasks again with another button. Reading the documentation and here on stackoverflow I cannot seem to see a way in background-tasks which can eliminate this task again (for my stop button). What would be a nice clean solution to solve this? -
What exactly are WSGI_HANDLER and WSGI_APPLICATION_
i'm building a django project on IIS. I've seen WSGI_HANDLER = django.core.wsgi.get_wsgi_application(), in a guide. But in my settings.py i've WSGI_APPLICATION = 'tvekstra.wsgi.application' I don't know if i put WSGI_HANDLER under WSGI_APPLICATION and i don't know what they do actually. Any explanation is great, thanks. -
Display only the data which depends upon different objects of different model
Have three different models in my app class HOD(models.Model): id = models.AutoField(primary_key=True) # hod_name = models.CharField(max_length=100) emp_no = models.CharField(max_length=50,unique=True,default=0) dept_id = models.ForeignKey(Department, on_delete=models.DO_NOTHING, default=1) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Employee(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) emp_no = models.CharField(max_length=50,unique=True,default='NULL') dept_id = models.ForeignKey(Department, on_delete=models.DO_NOTHING, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class ApprovalReportEmployee(models.Model): id = models.AutoField(primary_key=True) employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE) approval_date = models.CharField(max_length=255) approval_message = models.TextField() approval_status = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() I want to display the approvals made by a user: employee and the approval should appear under HOD of the same department approval view, should I make a new table for this? Not getting any solution. -
How to specify certain data to store in MySQL database through Django?
I set up the standard connection to my MySQL database in the Django settings.py, which works fine. The problem is that all of the data fields from a class are stored in the database. Is there a way to only choose certain fields to store in the database? I've looked around a lot online, but most of the information only deals with establishing connections. For example, with the class below, I only want to store first_name and last_name in MySQL. All data is stored in Elasticsearch anyways, but I want a simple db in MySQL as well. ''' class Employee(models.Model): first_name = models.TextField() last_name = models.TextField() email = models.EmailField(max_length=254, default='Enter valid email.') company_name = models.ManyToManyField("Company", blank=True) salary = models.CharField(max_length=10, null=True) currency = models.TextField(choices=CHOICES_CURRENCY, null=True) pan = models.CharField(max_length=10, default='AAA0000000') gender = models.TextField(choices=CHOICES_GENDER, null=True) marital_status = models.TextField(choices=CHOICES, null=True) address_1 = models.CharField(default="Address Line 1", max_length = 1024) address_2 = models.CharField(default="Address Line 2", max_length = 1024) city = models.TextField(default="City") state = models.TextField(default="State") pin_code = models.CharField(max_length=10, default="0000000000" ) country = models.TextField(default="Country") ''' -
Django CKEditor Restrict Image Properties
Currently im using CKeditor to allow user to write nice looking posts. Now when i try to integrate the image option, I only want the user to upload images, when i click on the image symbol it shows: ImageInfo (lets the user choose an image from server folder), Link for a web image, Upload to open a file browser and let user choose his own, and Advanced, which i do not know about. I only want the user to be able to upload images from his computer. How do i deactivate the other properties? here is my config in settings.py: CKEDITOR_CONFIGS = { 'default': { 'width': '150%', 'toolbar': 'Custom', # Specify Custom Shit - GPL License - 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline', '-', 'Image', 'Link', 'CodeSnippet', '-', 'NumberedList', 'BulletedList', 'HorizontalRule', '-', 'Undo', 'Redo'], ], 'extraPlugins': 'codesnippet' } } -
Django+supervisor+daphne: "failed: Error during WebSocket handshake: Unexpected response code: 200"
Currently I built a webssh platform based on django and xterm.js. I am trying to deploy this project on server. However, when I start nginx service, everytime I tried start connection it returned failed: Error during WebSocket handshake: Unexpected response code: 200. I have tried directly run python manager.py runserver 0.0.0.0:8000, daphen -b 0.0.0.0 -p 8001 myproject.asgi:application and supervisord -c /etc/supervisor/supervisord.conf, all of which run successfully. I realize that the problem may be nginx.conf but I don't know where is the problem. can anyone help me about this? my nginx.conf is: upstream wsbackend { server 127.0.0.1:8001; } server { listen 80; server_name leeshen.net www.leeshen.net; client_max_body_size 75M; location /media { alias /srv/http/MyBlog/media; } location /static { alias /srv/http/MyBlog/static; } location / { root /srv/http/MyBlog; uwsgi_pass 127.0.0.1:8000; include /etc/nginx/uwsgi_params; } location /ws { proxy_pass http://wsbackend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } -
How to filter manytomany field values in django restframework
I am trying to query values from model, I want to include manytomanyfield values in query but now I am getting some numbers instead of values, I am using modelviewset in views.py file. I know what have done is wrong, How to do this in right way models.py class TrainingDetailsViewSet(viewsets.ModelViewSet): queryset = TrainingDetails.objects.all().order_by('Name') serializer_class = TrainingDetailsSerializer views.py class TrainingDetails(models.Model): Code = models.CharField(max_length=60) Name = models.CharField(max_length=60) TrainerName = models.ManyToManyField(TrainerDetails, blank=True, related_name='trainer') Agenda = models.FileField() Date = models.ManyToManyField(Date,blank=True, editable= True, related_name='date') Data = models.ManyToManyField(TrainingData, blank=True, related_name='data') def __str__(self): return self.Name serializers.py class TrainingDetailsSerializer(serializers.ModelSerializer): class Meta: model = TrainingDetails fields = ('Code', 'Name', 'TrainerName', 'Agenda' , 'Date' , 'Data' ) I'm getting in response, [ { "Code": "TRA123", "Name": "something", "TrainerName": [ 5, 6 ], "Agenda": "something", "Date": [ 2 ], "Data": [ 2 ] } ] I want, [ { "Code": "TRA123", "Name": "something", "TrainerName": [ 'john' , 'james' ], "Agenda": "something", "Date": [ '19/101/2020' ], "Data": [ 'something' ] } ] `` -
Setting up gunicorn.service [Service] for Django app
Following the documentation and online tutorials on setting up my gunicorn.service results in ModuleNotFoundError: No module named 'my-app' when I run sudo systemctl status gunicorn I realise something is being imported wrong or I do not have the correct directory listed in my gunicorn.service, but I'm struggling to figure out where the issue is regarding the [Service] part. My /etc/systemd/system/gunicorn.service : [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myname Group=myname EnvironmentFile=/home/myname/my-app/my-app/env WorkingDirectory=/home/myname/my-app/my-app/app ExecStart=/home/myname/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ my-app.app.wsgi:application [Install] WantedBy=multi-user.target My directories are as follows: ./ ./ env/ (./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/) .bash_history .bash_logout .bashrc .cache/ .cloud-locale-test.skip .gitconfig .local/ .profile .ssh/ .sudo_as_admin_successful .vim/ .viminfo my-app/ |_ .DS_Store |_ .git/ |_ .idea/ |_ .travis.yml |_ Dockerfile |_ docker-compose.yml |_ env/ (./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/) |_ requirements.txt |_ my_app/ |_ .flake8 |_ db.sqlite3 |_ env |_ manage.py* |_ static/ |_ app/ |_ ./ |_./ |___init__.py |___pycache__/ |_asgi.py |_settings.py |_urls.py |_wsgi.py Also, my settings.py since it might be relevant: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # … -
Having an issue on my heroku dashboard,various resources are not being loaded for a couple of months now
enter image description here[Heroku wont load resources][1] -
POST method working in POSTMAN but shows error from frontend
I have an api end point that is working fine in POSTMAN but when I try to POST method from frontend axios it gives error JSON detail "Authentication credentials were not provided." from fontend const config = { headers: { "Content-type": "application/json", Authorization : `JWT ${localStorage.getItem("access")}` }, }; axios.post( `...................................`, config, ) But in POSTMAN it works fine with these Authorization enter image description here and Headers enter image description here but in Browser console it shows error with this request enter image description here and for response error enter image description here I know I am adding unnecessary image links here but that's the best way in which I can show my problem.If you need any other details to debug this or If you have any idea why this might be happening? .Please Comment before down voting(it is unclear or not useful). I will really appreciate your help. -
'staticfiles' is not a registered tag library: These solutions don't work
I'm new to Heroku and Django. Now I'm in the middle of Getting Started on Heroku with Python. When I access https://(...secret...)-app-123.herokuapp.com/db, I got the following error: 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz Then I found these solutions. However, these solutions don't solve my problem. Firstly, I changed {% load staticfiles %} to {% load static %} ... in db.html. It gave me: run python manage.py migrate Running python manage.py migrate on ⬢ (...secret...)-app-123... up, run.3361 (Free) Operations to perform: Apply all migrations: admin, auth, contenttypes, hello, sessions Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Since the error message tells me to run manage.py makemigrations, I ran: manage.py makemigrations Traceback (most recent call last): File "C:\Users\xxxxx\python-getting-started\manage.py", line 8, in ? from django.core.management import execute_from_command_line ImportError: No module named django.core.management No module? Django is installed on my machine. I didn't know what to do, so I updated Django on my local machine: C:\Users\xxxxx\python-getting-started>pip install django --upgrade … -
Change pdf filename in Django while downloading
In my admin panel i am uploading a CSV with a certain name and downloading csv in pdf format. but while downloading the pdf the name of downloaded file is static which is given by us that is processed_1 but i want the filename of pdf to be same as of the csv filename while we are uploading csv . PDF function def download_pdf(self, request): # fill these variables with real values csv_file_id = request.GET.get("csv_file_id") try: csv_file = AICSVFile.objects.get(id=csv_file_id) except Exception as e: raise Http404('File not found!') fl_path = get_pdf_file_full_path(settings.MEDIA_ROOT, csv_file.user.id, csv_file_id) filename = 'processed_%s.pdf' % (csv_file_id) try: open(fl_path, 'r') except Exception: raise Http404('File not found!') with open(fl_path, 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=%s" % filename return response raise Http404('File not found!') context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", # "data": data } csv_file_id = request.GET.get("csv_file_id") data = AICSVFileOutput.objects.filter(csv_file_id=csv_file_id) # print(csv_data) context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", "data": data } pdf = render_to_file('pdf/duplicate_defects_org_updated.html', context) # print(pdf) if pdf: response = HttpResponse( pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") filename = "output.pdf" content = "inline; filename='%s'" % (filename) download = request.GET.get("download") if download: content = … -
Django - ImportError: Could not import 'drf_yasg.generators.OpenAPISchemaGenerator' for API setting
I'm trying to add https://github.com/axnsan12/drf-yasg this library to our django application and getting the below error. permission_classes=(permissions.AllowAny,), File "/env/lib/python3.7/site-packages/drf_yasg/views.py", line 67, in get_schema_view _generator_class = generator_class or swagger_settings.DEFAULT_GENERATOR_CLASS File "env/lib/python3.7/site-packages/drf_yasg/app_settings.py", line 122, in __getattr__ val = perform_import(val, attr) File "env/lib/python3.7/site-packages/rest_framework/settings.py", line 166, in perform_import return import_from_string(val, setting_name) File "env/lib/python3.7/site-packages/rest_framework/settings.py", line 180, in import_from_string raise ImportError(msg) ImportError: Could not import 'drf_yasg.generators.OpenAPISchemaGenerator' for API setting 'DEFAULT_GENERATOR_CLASS'. ImportError: cannot import name 'URLPattern' from 'rest_framework.compat' (env/lib/python3.7/site-packages/rest_framework/compat.py). after some research I found some people suggested installing this package to solve the issue pip3 install packaging But this is not making any difference. Any other good api documentation library available for django rest api? -
django attendance system for specific student
i am making attendance system for student but i not getting how i wanted, so looking for your suggestions, i think i'm missing something, i'm not getting list of specific student's attendance in my DetailView just getting one single student attendance, i exactly wanted list of student's attendanc in DetalView, in listView (where show list of subject and from there go in DetailView) i tried with m2m but, it's not possible to specific present and absent days for specific student :( models.py class Student_Attendence(models.Model): lecturer = models.ForeignKey(Lecturer, on_delete=models.SET_NULL, blank=True, null=True) department = models.ForeignKey(to='sis.Department', on_delete=models.SET_NULL, blank=True, null=True) semester =models.ForeignKey(to='sis.Semester', on_delete=models.SET_NULL, blank=True, null=True) subject = models.ForeignKey(to='sis.Subject', on_delete=models.SET_NULL, blank=True, null=True) student = models.ForeignKey(to='sis.Student', on_delete=models.SET_NULL, blank=True, null=True) date = models.DateField(blank=True, null=True) present = models.PositiveIntegerField() absent = models.IntegerField() def get_absolute_url(self): return reverse('lecturer:student_attendence_detail', kwargs={ 'pk': self.pk }) views.py # where show list of subject name class Attendence(generic.ListView): model = Student_Attendence template_name = 'attendence.html' context_object_name = 'queryset' def get_context_data(self, *args, **kwargs): profile = Lecturer.objects.all() semester_course = Student_Attendence.objects.all() context = super().get_context_data(**kwargs) context['profile'] = profile context['test'] = semester_course return context # attendance.html <thead> <tr> <th> No </th> <th> Date </th> <th> Code </th> <th> Subject Name </th> </tr> </thead> <tbody> {% for a in queryset %} <tr class="odd gradeX"> … -
TypeError: topics() missing 1 required positional argument: 'topic_id'
I'm following along a Django tutorial book to make a basic blogging application where users can write journal entries about whatever topic they choose. I've written the url, pattern, view, and template for my topic page but I keep getting this same error. but I think something is wrong with the url pattern. urls.py # Defines url patterns for learning_logs app from django.conf.urls import url from . import views urlpatterns = [ # Home Page url(r'^$', views.index, name='index'), # Topic Main Page url(r'^topics/$', views.topics, name='topics'), # Detail page for a single topic url(r"^topics/(?P<topic_id>\d+)/$", views.topics, name='topic'), ] views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): # This is the home page for our learning_logs app return render(request, 'learning_logs/index.html') # This is the view for 'topics' page 9.5.20 def topics(request, topic_id): '''show a single topic and its entries ''' topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topics.html', context) And the error: TypeError: topics() missing 1 required positional argument: 'topic_id' Any advice? Thank you. -
How to remove object from database on tab close django
I have an image loaded on-page and it's loaded from the database and I want to remove that object from the database when the tab is close how can I do that? framework- Django -
Pipeline - Django social app save image user
I try to save the FB image from my user after a connexion but I got only the url. Any idea about that? If I click on the link of the result, I automatically download the image... so I'm bit lost. models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) image = models.ImageField(default='user/user-30.png',upload_to='user/',null=True,blank=True) full_address = models.CharField(max_length=128) settings.py SOCIAL_AUTH_PIPELINE = ( ... 'user.pipeline.save_image_profile', ) pipeline.py from .models import UserProfile def save_image_profile(backend, user, response, *args, **kwargs): if backend.name == "facebook": if UserProfile.objects.filter(user_id=user.id).exists(): user_object = UserProfile.objects.filter(user_id=user.id)[0] user_object.image = response['picture']['data']['url'] user_object.save() else: UserProfile.objects.create( user=user, image=response['picture']['data']['url'] ) -
How to use library Django-RQL to filter fields of type 'Time' in Django Rest Framework?
I would like using filter in my REST API in my field 'hora' but your type is Time. When I try do query, example: 127.0.0.1:8000/api/v1/queimadas/?hora=17:15:33, the error show: "RQL Parsing error." My task is filter this field 'hora' in beetween of times, like this: ?ge(hora,17:00:00)&le(hora,20:00:00) in url (Following the documentation), but I can not :( Thanks very much all. This is documentation the library django-rql - https://django-rql.readthedocs.io/en/latest/index.html My serializers.py: class QueimadaSerializer(serializers.ModelSerializer): satelite = SateliteSerializer(many=False,read_only=True) cidade = CidadeSerializer(many=False,read_only=True) class Meta: model = Queimada fields = [ 'id', 'latitude' , 'longitude', 'data', 'hora' , 'observacao', 'veracidade', 'visitado', 'satelite', 'cidade' ] My views.py: class QueimadasViewSet(viewsets.ModelViewSet): queryset = Queimada.objects.all() serializer_class = QueimadaSerializer filter_backends = (RQLFilterBackend,) rql_filter_class = QueimadaFilters @action(detail=True,methods=['get']) def satelite(self,request,pk=None): satelite = Satelite.objects.filter(queimada__id=pk) self.pagination_class.page_size = 10 page = self.paginate_queryset(satelite) if page is not None: serializer = SateliteSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = SateliteSerializer(satelite, many=True) return Response(serializer.data) My filters.py: class QueimadaFilters(RQLFilterClass): MODEL = Queimada SELECT = True FILTERS = ( { 'namespace' : 'cidade', 'filters':('id','nome'), 'qs' : SelectRelated('cidade'), }, { 'filter': 'data', }, { 'filter': 'hora', 'custom': True, 'lookups': { FilterLookups.EQ, FilterLookups.IN, FilterLookups.I_LIKE, FilterLookups.LE, FilterLookups.LT, FilterLookups.GE, FilterLookups.GT }, }, ) -
Call map.setView for javascript from a function with variables
I am running a django app with tables2. I then set up a field with linkify where i want to zoom to a feature by running a javascript function. My code in the renderd htm is: <div id="map" class="leaflet-container-default"></div> ...... <td ><a href="javascript:onclick=myFunction(7.22591038,61.1982749)">Zoom til</a></td>.... <script type="text/javascript"> function myFunction(lat,long) { map.setView([lat,long], 15); } </script> -
Django dumpdata fails on special characters
I'm trying to dump my entire DB to a json. When I run python manage.py dumpdata > data.json I get an error: (env) PS C:\dev\watch_something> python manage.py dumpdata > data.json CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined> Exception ignored in: <generator object cursor_iter at 0x0460C140> Traceback (most recent call last): File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly? FYI, all other DB functionalities work fine -
Specify action in API request - Django Rest framework
I have different serializers for List and Detail actions. By default an API has an action - List. How do I specify the action?