Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic Templates in Django Views
I am wondering whether it is possible to insert template names dynamically into Django views from urls.py. That is, suppose I have an app whose entire purpose is to serve as a container for various static landing pages. The plan is to create this app and have various entries in its urls.py correspond to paths to various landing pages. Each page would have a separate .html correspond to it. The question is whether one could get away with writing only one (class-based or other) view for all of these templates or would there need to be a view for each page? Django version 2.1-2.2 P.S. If there is an alternative, laconic way of accomplishing something similar, I am all ears. -
How to count clicks of a link and store in database(Django)?
How do I edit this code to count the times the "Link" was clicked and add this to the database model "T_shirt" in a new column? HTML <ul class="products"> {% for v in owner_obj %} <div class="container"> <a href={{ v.Link }} target="_blank" rel="noopener noreferrer"> <img src={{ v.Images }} width="150" height="150"> </a> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }} </b></figcaption> </div> {% endfor %} </ul> Models.py class T_shirt(models.Model): Images = models.ImageField() Titles = models.CharField(max_length=250, primary_key=True) Prices = models.CharField(max_length=250) Link = models.CharField(max_length=250) -
DRF + React.js Best Security Practise
Hello everyone i'm building a web-app with Django rest framework and react js. Back-end and front end are completely decoupled its pretty basic.React project created with npm create-react-app and DRF API is pretty standard i will use it to provide the info that front-end needs .So its both my resource and auth(which holds the users info and issues tokens etc.)server what is the best practice in 2021. bonus question I'm trying to implement Authorization code with PKCE and OIDC with django-oauth-toolkit.A high level of steps to do would be nice . for example i register an application on the admin interface and to get code http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=<client_id>&redirect_uri=<redirect_uri> and i get an url with the grant code but only i'm logged in as admin user. (what good is that? I think i'm missing something here.) Also any help or information regarding the subject is much appreciated -
Setting a default value for an instance in django views
I am tracking histories on my models using simple history and this works fine.Problem is , some changes made to the models are done by the application and so do not have a history_user, thus return null. The result I get form the api in this case is as below. I am trying return the id of the history_user for those that have one and set the ones that are null to a specific id, say 1.But am struggling a bit. I have added a function get_history_user to return 1 in case the value is null .But the code just runs and returns the initial result with no errors.Can this work as it is? What am I doing wrong? { "invoice_history": [ { "history_id": 452, "history_user": 8, "history_type": "+", "history_date": "2021-04-28T13:22:16.045294+03:00", "id": 919 }, { "history_id": 451, "history_user": null, "history_type": "+", "history_date": "2021-04-28T13:22:15.572174+03:00", "id": 918 }, { "history_id": 450, "history_user": null, "history_type": "+", "history_date": "2021-04-28T13:22:13.477117+03:00", "id": 917 } ]} Views.py class AllHistoryView(APIView): def get(self, request, format=None): all_invhist = Invoice.history.all() serializers = InvoiceHistorySerializer(all_invhist, many=True) try: result = {} res = serializers.data result = res invoice_history = result[0:3] def get_history_user(invoice_history): history_user = invoice_history["history_user"] if isinstance(history_user, (float, int)): return history_user return 1 # … -
How to solve Django forms inline radio button bullet point problem
I'm try to use Django forms with radio buttons but if I like to use it as inline class I have bullet points in the row. How could I hide them? This is the result: models.py class Attitud(models.Model): def __str__(self): return str(self.user_name) class question(models.IntegerChoices): Nem_jellemző = 0 Néha_jellemző = 1 Nagyon_jellemző = 2 user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) att_v001 = models.IntegerField(verbose_name="Kérdés 1", default='', null=True, blank=False, choices=question.choices) forms.py class AttitudForm(forms.ModelForm): class Meta: model = Attitud fields = ['att_v001'] widgets = { 'att_v001': forms.RadioSelect(attrs={'class': 'form-check-inline ml-5'}) } html {% extends 'stressz/base.html' %} {% block body%} <div class="container w-75"> <div class="display-4">Helló {{ user.get_short_name}}! </div> <p class="text-justify">Kérlek, hogy az alábbi kérdések esetében válaszd ki, hogy melyek a rád leginkább jellemző kijelentések. </p> </div> <form method = "POST"> <div class="container w-75 bg-light rounded-3 pt-3"> <div class="form-group"> {% csrf_token %} {{ form.as_p }}<br> </div> <button class="btn btn-large btn-primary" type="submit">Mentés</button> {% comment %} {{ form.att_v001|crispy }} {% endcomment %} {% endblock %} -
Prevent Authenticated Users from accessing the inbuilt login form in djagno
I'm using Django's default login form from within a custom template.However,once a user logs in using this form,they can still go back to the login form.Now,I'm aware of a method to prevent something like this from happening: decorators. However,these decorators wont work on the way I'm rendering the login view.Have a look at the urls.py : from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns=[ path('',auth_views.LoginView.as_view(template_name='main/login.html')), path('home',views.home,name='home') ] Normally,decorators are imported within views.py and called right above the view function.This can't be done here. I dont know whether it will help,but here's the form part of 'main/login.html': <form method="POST" class=""> {% csrf_token %} <div class="form-group"> {{ form.username.label }}: {{ form.username }} </div> <div class="form-group"> {{ form.password.label }}: {{ form.password }} </div> <div class="form-group"> <input type="submit" class="login-input btn btn-warning" value="Login!" /> </div> </form> Thank you very much! -
Django FormViews displays dropdown menu instead of char- and textfield
I'm new to Django and I'm trying to use the FormViews but when I display the view it looks fine except the fields with a ForeignKey (companyAddress and companyContactInformation). Instead of creating a Char- and Textfields for each variable it just makes a dropdown field. I've looked into formsets, inline_formsets and model_formsets but can't seem to figure it out. from django.db import models from django.forms import ModelForm class address(models.Model): streetName = models.CharField(max_length = 45) houseNumber = models.CharField(max_length = 25) postalCode = models.CharField(max_length = 4) region = models.CharField(max_length = 45) def __str__(self): return '{} {} {} {}'.format(self.streetName, self.houseNumber, self.postalCode, self.region) class contactInformation(models.Model): phoneNumber = models.CharField(max_length = 11) email = models.CharField(max_length = 100) mainContact = models.CharField(max_length = 50) def __str__(self): return '{} {} {}'.format(self.phoneNumber, self.email, self.mainContact) class company(models.Model): companyName = models.CharField(max_length = 145) companyAddress = models.ForeignKey(address, on_delete = models.CASCADE) description = models.TextField() companyContactInformation = models.ForeignKey(contactInformation, on_delete = models.CASCADE) websiteURL = models.CharField(max_length = 100) relationToDjango = models.TextField() def __str__(self): return '{} {} {} {} {} {}'.format(self.companyName, self.companyAddress, self.description, self.companyContactInformation, self.websiteURL, self.relationToDjango) class addressForm(ModelForm): class Meta: model = address fields = '__all__' class contactInformationForm(ModelForm): class Meta: model = contactInformation fields = '__all__' class companyForm(ModelForm): class Meta: model = company fields = ['companyName', 'companyAddress', 'description', … -
can anybody help me to run this django github project in window?
I used these steps to run this projects: downloaded and extracted and opened with vscode created virtual env using virtualenv test after django installation pip install -r requirements.txt 4)after successfully installation of requirements showing not found two modules celery and dotenv The link of Github-project is given below: https://github.com/MicroPyramid/opensource-job-portal -
Celery Beat sending tasks on startup (before the scheduled time)
I have a celery beat schedule: CELERY_BEAT_SCHEDULE = { "test-task": { "task": "myapp.tasks.test_task", "schedule": crontab(hour=20), # Should execute at 8pm UTC! } } And when I execute the beat instance, with celery --app myapp beat --loglevel DEBUG The celery beat instance automatically sends the task to the broker: [2021-05-03 14:12:04,022: INFO/MainProcess] Scheduler: Sending due task test-task (myapp.tasks.test_task) Is there a way to prevent it? The task should only be executed at 8pm and never before that time. -
Critical Section across multiple EC 2 Instances
I have a code hosted on two different EC2 servers, and it might happen that the given code can be executed simultaneously on two different machines for certain set of variables. It will be ok for me if if they execute one by one. For .e.g my current sequence at two machines(A, B) runs like this, where CS gets executed simultaneously on both machines, depending on two conditions (say condition1, condition2) if condition1 and condition2 A1 B1 A2 B2 "CS" "CS" A3 B3 But what I am trying to do is something like: if condition1 and condition2 A1 B1 A2 B2 "CS" A3 "CS" B3 My code is hosted on Django. What can I do to prevent simultaneous execution. -
Django chart.js multi axis line chart
Hi Guys I have inspired from this Fiddle example to try to create a similar multi axis line chart in my django project. I have in my views : class dashboard(TemplateView): template_name = 'users/dashboard.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['qs'] = DummyData.objects.all() data = DummyData.objects.all() years=[] for i in range(data.count()) : if data[i].year not in years : years.append(data[i].year) context['years'] = years return context in in my dashboard.html : {% extends 'users/base.html' %} {% load static %} {% block content %} <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- semantic UI --> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css"> <!--Chart js--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" /> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function (){ var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for year in years %} '{{year}}', {% endfor %}], datasets: [{% for item in qs %} { label: '{{item.site}}', yAxisID: '{{item.site}}', data: [100, 96, 84, 76, 69] , {% endfor %} ] }, options: { scales: { yAxes: [{ id: 'A', type: 'linear', position: 'left', }, { id: 'B', type: 'linear', position: 'right', ticks: { max: 1, min: 0 } }] } } … -
django - template does not exists at /
I'm starting a new Django project, but straight away I can't set up the correct templates directory path. this are my settings.py: import os TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... ], }, }, ] I have a very simple view in the project folder: def dashboard(request): context = { } template_name = 'dashboard.html' return render dahsboard.html is located in BASE_DIR/templates/dashboard.html. Pretty straight forward, but still I get the Error: "TemplateDoesNotExist at / dashboard.html" -
my python path for new env does not run the code , while mu main python path run it as normal
while I am testing some mediapipe functions and modules on my windows PC I noted that when I run any thing on my main python path its fine but , if I run it on the new env path some functions does not work this error -->(FileNotFoundError: The path does not exist.) appears ''' when I comment this on my env path I works fine but if I uncomment those two lines FileNotfoundError #appears import mediapipe as mp mp_holistic = mp.solutions.holistic holistic = mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) print("any_thing") print(mp_holistic) print(holistic) ''' enter image description here enter image description here -
Set value of a form class field
# forms.py class AvatarForm(forms.ModelForm): class Meta: model = Profile fields = ('avatar', 'user', 'banner', 'bio') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(AvatarForm, self).__init__(*args, **kwargs) self.fields['avatar'].widget.attrs = { 'class': 'd-none', 'accept': 'image/*', } self.fields['user'].widget.attrs = { 'class': 'd-none', } self.fields['banner'].widget.attrs = { 'class': 'd-none', } self.fields['bio'].widget.attrs = { 'class': 'd-none', } # set the value here, something like this self.fields['user'] = self.user self.fields['bio'] = str(Profile.objects.filter(user=self.user).first().bio) self.fields['banner'] = str(Profile.objects.filter(user=self.user).first().banner) # views.py def main(request, username): form = AvatarForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() ... // js file var formData = new FormData(); formData.append('croppedImage', blob); $('.cropper-container').remove(); $.ajax($`/{${'#auth_username'}}/`, { method: "POST", data: formData, processData: false, contentType: false, success: function () { $('.avatar-container-wrapper').load(location.href + ' .avatar-container'); }, error: function () { } }); The only thing I want to upload is the avatar field, rest other fields must have a default value that I want to set in the forms.py file itself. How to achieve this.. The other fields are part of the Model but the only field I want to change is avatar. Any help is appreciated. Thank you! -
Patching Django FileSystemStorage location does not take effect [putest]
I have a simple model as such: #models.py from django.core.files.storage import FileSystemStorage LOCATION = 'old_location' class FileArchive(models.Model): file = models.FileField(storage=FileSystemStorage(location=LOCATION)) I have a view through which I populate the mentioned model and call .save(). My aim is to have a functional test to try to upload a file and assert that the file exists on the provided (patched) LOCATION. The problem is no matter how I patch the LOCATION, which is located in my models.py, the test still uses the hard-coded location in my model. Here are the ways I tried to patch LOCATION. Some of the ways I tried to patch the LOCATION attribute: from . import models def test_uploaded_file_is_stored(monkeypatch): monkeypatch.setattr(models, 'LOCATION', 'new_location') ... Another way: def test_uploaded_file_is_stored(mocker): mocker.patch.object(modesl, 'LOCATION', 'new_location') ... Another way: from unittest.mock import patch def test_uploaded_file_is_stored(mocker): with patch('filestorage.models', 'LOCATION', 'new_location') ... I'm guessing I am patching the wrong place. Any ideas? -
is there a method to run javascript only after loading page url?
html : <li><a href="{% url 'list_article' %}"> article</a></li> i want to execute javascriptcode only after the href i.e after going on list_article url : var rules = $('#builder').queryBuilder('getRules'); liste_rules=[{"id":"source","field":"source","type":"string","input":"text","operator":"contains","value":"google"}] liste_rules={"condition":"AND","rules": liste_rules}; $('#builder').queryBuilder('setRules', liste_rules); $('#FormQueryBuilder').submit(); -
Django Channels 3.0 - different middleware for different websocket routes
I am currently experiencing a conundrum. I am attempting to implement a inter-device communication/signalling system. I am attempting to tackle this via WebSockets (Django Channels and Consumers), as real-time event handling is important for my use case. I would like to be able to apply authentication middleware to only certain WebSocket protocol URLs (specific Consumers), allowing others (like registration and login via JWT) to occur without asking for authentication. The documentation covers a root-level ProtocolTypeRouter and encourages developers to wrap an ASGI application (like a URLRouter) in an authentication middleware stack. However, the end result is that all of the "websocket" protocol requests are forwarded to this middleware. What I would like to do, is somehow split the handling of websocket protocol requests based on their URL. Ideally, to give ProtocolTypeRouter two URLRouters, one wrapped with the middleware and one not. Like so: device_handling_service/urls.py from channels.routing import URLRouter from django.urls import re_path from .consumers import IoTRegisterConsumer,\ IoTLoginConsumer,\ IoTPollConsumer websocket_needs_auth = URLRouter([ re_path(r"^$", IoTPollConsumer.as_asgi()) ]) websocket_no_auth = URLRouter([ re_path(r"^register/$", IoTRegisterConsumer.as_asgi()), re_path(r"^login/$", IoTLoginConsumer.as_asgi()), ]) asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import device_handling_service.urls from .middleware import JWTAuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IoTHub.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter([ JWTAuthMiddlewareStack(device_handling_service.urls.websocket_needs_auth), … -
IntegrityError: null value in column "is_approved" violates not-null constraint
Firstly , i was told to add a field to my model to help the admin approve, disapprove or pend products before they can be seen on the website. So, i added class Product(models.Model): ...there are some fields here... is_approved = models.BooleanField(default=False) to my product model, did the routine migrations, edited the serializer, views,urls,tested it and pushed to microsoft azure. 2nd, i had another instruction to change the same field to approval_status STATUS = [ ('0', 'Pending Approval'), ('1', 'Approved'), ('2', 'Rejected') ] class Product(models.Model): ...there are some filed here... approval_status = models.CharField( choices=STATUS, default='0', max_length=2 ) after deploying, i have this error IntegrityError at /marketplace/create_product/ null value in column "is_approved" violates not-null constraint DETAIL: Failing row contains (620, , , 2.00, FTF, 0, PR, , , , 113, 2021-05-03 11:38:28.57937+00, null, 0). i am suspecting the server database couldn't replace the is_approved field with approval_status, but rather included it, and hence trying to return that value. i have am expecting 13 fields but 14 are been returned Kindly help me with ideas to solve the error. my model class Product(models.Model): owner = models.ForeignKey( 'Accounts.BusinessInfo', on_delete=models.CASCADE ) name = models.CharField( max_length=100, blank=True, ) description = models.TextField( blank=True ) price = … -
HOW TO OPTIMIZE DJANGO QUERIES
Could you, please help me optimizing this view? It's takes more than 30 minutes to accomplish the job. I think the problem is in the Django queries.cSomeone recommended me to put all queries in a list or dictionary I tried it but I don't see how to deduce the Django queries def upload_edge(request, pk): template = "networks/edge.html" roadnetwork = RoadNetWork.objects.get(id=pk) road_type = RoadType.objects.get(pk=2) if request.method == 'POST': form = EdgeForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] objects = json.load(datafile) L=[] for object in objects['features']: objet_type = object['geometry']['type'] if objet_type == 'LineString': properties = object['properties'] geometry = object['geometry'] point1 = geometry['coordinates'][0] point2 = geometry['coordinates'][1] location = GEOSGeometry( LineString(geometry['coordinates'])) target = properties.get('target') source = properties.get('source') name = properties.get('name') try: target_node_instance = Node.objects.get(node_id=target) source_node_instance = Node.objects.get(node_id=source) target = Node.objects.get(network_id=target_node_instance.network_id, node_id=target_node_instance.node_id) source = Node.objects.get(network_id=source_node_instance.network_id, node_id=source_node_instance.node_id) node = Edge( geometry=location, road_type=road_type, target=target, source=source, network=roadnetwork) L.append(node) except: pass Edge.objects.bulk_create(L) return redirect('home') else: form = EdgeForm() return render(request, template, {'form': form}) -
Where to store PDF files from user input in a React/Django project
I am creating an job application website with React and Django. I want the users to upload 3 PDF files as part of the form in the application. I want to store these files in the backend(Django) and send the files to another React page. My problem is storing these PDF files. The application model uses FileField. Can these files be stored in Django or is it better to use somehting like AWS? -
How can I use ImportExportModelAdmin and SearchAutoCompleteAdmin to the same model admin?
I'm new to Django and I really search everywhere to solve this situation but I didn't find How exactly I can do it. this is my model.py: class User(models.Model): username = models.CharField(max_length=35,verbose_name='Username') site = models.CharField(max_length=35,verbose_name='Site') This is my model admin.py: from django.contrib import admin from search_admin_autocomplete.admin import SearchAutoCompleteAdmin class AdminUser(SearchAutoCompleteAdmin,ImportExportModelAdmin): list_display = ('username','site') search_fields = ['username'] list_filter = (site, ) admin.site.register(User,AdminUser) I can not use SearchAutoCompleteAdmin and ImportExportModelAdmin together. I really need to have a solution that can make my model has a searchAutocomplete and an ImportExport in the django admin page. -
Get Django ready for Angular with Corsheaders
I am trying to integrate my Django backend app to Angular. But for some reason, this error always starts showing up. This is what my settings.py file is looking like: INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleWare', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ] And this is the Error: ImportError: Module "corsheaders.middleware" does not define a "CorsMiddleWare" attribute/class Who knows what I am doing wrong here? Or if there's a fix for that? -
Django_Rest_Framework efficient way to perform calculations across models
I am using django_rest_framework for a web application. I have created the necessary API end points for all the necessary CRUD operations for the respective tables. Now I want to perform calculations on the data of multiple tables and send the calculated result as a Response. I could think of two ways of doing this, which would be more efficient (or the correct was to do it, if any): 1. Calculations using Pandas Create a view which will be called with a GET request Get the querysets of data from the necessary tables Convert them to pandas DataFrames Perform the necessary calculations Reconvert the DataFrame to a JSON object and return a Response 2. Create a Separate Model, Serializer and View for the Calculations If there is some other library or method that can do this, please provide some suggestions -
Text beneath image going out of circular div
I have a circular div which I made by applying some css styling like border-radius. Within the div, it contains an icon and below the icon, the corresponding text. However, the image is getting displayed properly, but the text is going out of the div. There is much vertical space between the icon and the text. How do I solve this? Here is my code: .internship_cat{ object-fit: contain; background-color: #06314e;; margin-top: 5px; margin-bottom: 10px; margin-left:10px; border-radius: 50px; transition: transform 450ms; width: 110px; height: 110px; align-items: center; justify-content: center; } .internship_cat:hover{ transform: scale(1.08); } </style> <div class="internship_categories" style="margin-top:10px; display:flex; overflow-x:scroll; overflow-y:hidden" > {% for ind_type in industry_type %} <div class="internship_cat"> <img src="{{ ind_type.picture_icon.url }}" alt="" width="100" height="100"> <span class="caption" style="color: white; ">{{ind_type.industry_name}}</span> </div> {% endfor %} -
Am beginner with Django & angular and I want to upload an excel file path from angular to a function in Django and make some modification to the file
I am developing an application using Django and angular I want to upload an excel file path from angular to a function in Django to be able to upload data from excel to the database