Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't create multiple dynamic sub menus using bootstrap 4
I am currently having issues creating dynamic submenus with bootstrap. Using a simple ajax request I want to get the name of the folders on my Django server and then display the chosen folder items, creating several submenus. I'm using bootstrap 4, the first JS snippet works as intended but I can't get the second one to behave similarly and iterate upon its parent object. HTML <div class="dropdown show"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Analyze </a> <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <li class="dropdown-submenu"> <a id='spec_library' class="dropdown-item dropdown-toggle" href="#">Library</a> <ul id='spec_lib' class="dropdown-menu"> <!-- <li><a class="dropdown-item" href="#">History</a></li> <li><a class="dropdown-item" href="#">Geography</a></li> <li><a class="dropdown-item" href="#">Sociology</a></li> --> </ul> </li> <li><a class="dropdown-item" href="#">Upload</a></li> </ul> </div> JS The first snippet works as intended $('#spec_library').on('click', function(e) { $.ajax({ type: "GET", url: "spectro_lib", /* Call python function in this script */ /* Passing the text data */ success: callback }); function callback(response){ console.log(response) instrument = response size = response.length; spec_lib = document.getElementById("spec_lib") console.log(spec_lib.childNodes.length) $("#spec_lib").empty(); if (spec_lib.childNodes.length <= size){ for (i = 0; i <= size - 1;i++){ var spec_lib_x = "spec_lib_" + i var lib_submenu = document.createElement("li"); lib_submenu.id= spec_lib_x lib_submenu.className="dropdown-item dropdown-submenu" document.getElementById("spec_lib").appendChild(lib_submenu) var lib_subitem = document.createElement("a"); lib_subitem.id= "spec_lib_instrument" lib_subitem.className="dropdown-item dropdown-toggle" lib_subitem.href="#" lib_subitem.innerHTML = response[i] document.getElementById(spec_lib_x).appendChild(lib_subitem) var … -
React vs django native templating language with django as backend
Recently I had started learning react. But I am a django developer. I had got a doubt that which one is to be used as frontend with django as backend. Is react as frontend and django APIs as backend Or Django templating language with django plain views as backend -
Where does Django stdout output go when running with nginx and Gunicorn?
In my my_application/settings.py file, for example, I have a couple of print statements, thus: print( 'running settings.py: ALLOWED_HOSTS: ' ) print( '\n'.join( ALLOWED_HOSTS ) ) ... where does this output actually go on a remote server running nginx and Gunicorn? NB I am aware this may be an egregious security breach to print ALLOWED_HOSTS anywhere, for all I know. This is merely an example: I am at the learning/experimentation stage. -
Google Drive API - File Download Issues with Service Account
I'm setting up a Django-Heroku app to allow users to download videos up to a size of 75MB. I have tried this two ways now, and neither works how I want, so I'd like to know if I'm hitting some limitation or not doing it properly. Environment I have a basic G Suite account with a service account that has the delegate-authority enabled. The JSON key is in place, the API is enabled, the account is authorized with the proper scopes and I am able to download the file contents. What I Want The user clicks on a link and the file downloads directly from Google Drive with no web app pass-through, no sign-in, no virus warning pop-up, etc. It should be seamless for the user -- click once and the file downloads. class GoogleDrive(): connection = None def __init__(self, version='v3', permissions=['read'], autoconnect=True, *args, **kwargs): super(GoogleDrive, self).__init__(*args, **kwargs) self.service = 'drive' self.version = version self.permissions = permissions # Connect automatically if autoconnect: self.connect() # Calls build() with appropriate scope / credentials Attempt 1 - Download GD file and return as HTTPResponse # Build a GD service with "readonly" scope gd = GoogleDrive() request = gd.connection.files().get_media(fileId='<SOME_GD_ID>') stream = io.BytesIO() downloader = … -
Dynamic Image Source Creating using Django
I want to make shopping website using Django and html + css. For this purpose, I have to have specific picture for each item and i am trying to find this picture source using combination of static file tagging. I could not store the image in the database, so images are chosen dynamically from the static folder. however, my code does not work, can someone help me to solve this issue? My HTML Code def sales_page(request): all_storage_products=Storage.objects.all(); sales_page_product={'all_storage_products_dict':all_storage_products} form1=search_field(); file_path =os.path.join(STATIC_DIR,'images'); if(request.method=='POST'): form1=search_field(request.POST); if(form1.is_valid()): all_storage_products=Storage.objects.filter(product_description__icontains=form1.cleaned_data['your_name'] ); sales_page_product={'all_storage_products_dict':all_storage_products} form1=search_field(); return render(request, 'first_app/sales_page.html',{'all_storage_products_dict':all_storage_products, 'forms':form1, 'image_path':file_path}); <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> .main_page_nav { width: 100%; height: auto; display: flex; } .main_page_nav ul{ height: auto; width: 100%; background-color: rgb(243,243,243); } .main_page_nav ul li{ display: inline; padding: 1rem; } .main_page_nav ul li a{ font-size: 2rem; } .main_page_nav ul li a:hover{ font-size: 2rem; border-style: solid; border-left-color: rgb(243,243,243); border-top-color: rgb(243,243,243); border-right-color: rgb(243,243,243); border-bottom-color: green; } #main_page_nav_last_item{ float: right; padding: 0; } #search_field{ width: 100%; } table, tr, td{ background-color: white; border-style: solid; } form p{ width: 100%; display: flex; justify-content: center; font-size: 2rem; } input[name="your_name"]{ width: 50%; border-radius: 5%; } input[name="your_name"]:focus{ outline-color: green; … -
How would i use django-filter if the search function and the results are on different pages?
how would django-filter work if the search function and the filtering are on different pages? For example, I have a home page with a search function, the results of the search are listed in the results page. On these results I want to apply filters ( like airbnb does for example). I'm able to filter results on the same page as the results currently. -
How to combine several models in the one DetailView
I have 3 models Course,CourseSection,SectionVideo and last 2 connected to the Course model. I want to create DetailView for the Course, which will contain all models, i mean where i can show sections inside and inside section show videos. How to do that? class Course(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=150, null=True, blank=True) description = models.TextField() image = models.ImageField(upload_to='courses/course_images',blank=True,null=True) cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE,null=True) students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE) certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True) languages = LanguageField(blank=True) rank_score = models.FloatField(default=0.0) price = models.FloatField(default=0.0) discount_price = models.FloatField(blank=True, null=True) class CourseSections(models.Model): title = models.CharField(max_length=50) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True) class SectionVideos(models.Model): video = models.FileField(upload_to='courses/course_videos',max_length=100) section = models.ForeignKey(CourseSections,on_delete=models.CASCADE,null=True) -
Get Data from Multiple ForeignKey Query Results
I have the following models.py set up: Student(models.Model): id = models.CharField(max_length = 15, primary_key = True, unique = True) first_name = models.CharField(max_length = 25) last_name = models.CharField(max_length = 25) ... Fine(models.Model): name = models.CharField(max_length = 25) description = models.CharField(max_length = 100) value = models.DecimalField(max_digits = 6, decimal_places = 2) StudentFines(models.Model): student = ForeignKey(Student, on_delete = models.CASCADE) fine = ForeignKey(Fine, null = True, on_delete = models.SET_NULL, related_name = 'fines') created = models.DateTimeField(auto_now = True) I've assigned two fines to a particular user in my database, so in my view.py I have this to get the fines that are assigned to the user: def detail(request, id): ... fines = StudentFines.objects.filter(student_id = id) ... context = { ... 'fines': fines, } And when I call it in my template with {% for fine in fines %}A fine.{% endfor %}, I get two results. Now I want to report the specific details of the fines: the name, description, and value. Eventually I plan to use a form to add an entry directly from the page, but that's future stuff. I've scoured the Internet and came across several ways to try and get the ForeignKey's data, but none of what I try has worked. I've … -
How to carry out calculations in Django Rest Framework viewsets.ModelViewSets?
I have an API that pulls from a MySQL game database and I would like to get a list of top unique scorers. My Viewset looks like this: -
Form not uploading imageField in Django
I'm following an online course about Django. I need to upload an image via a form but it doesn't work. My form is in blog/contact and when I submit it goes back to blog/ without saving the for, also I can see the that form is bound= false and valid = false after submitting. If anyone can help me ? Here is my code : # views.py def nouveau_contact(request): sauvegarde = False #il ne faut pas oublier le request.FILES sinon ça ne marche pas form = NouveauContactForm(request.POST or None, request.FILES or None) print ("erreur : ") print(form.is_valid) if form.is_valid(): contact = Contact() contact.nom = form.cleaned_data["nom"] contact.adresse = form.cleaned_data["adresse"] contact.photo = form.cleaned_data["photo"] contact.save() sauvegarde = True return render(request, 'blog/contact.html', { 'form': form, 'sauvegarde': sauvegarde }) # forms.py class NouveauContactForm(forms.Form): nom = forms.CharField() adresse = forms.CharField(widget=forms.Textarea) photo = forms.ImageField() # Media files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") I am using anaconda and I have already downloaded pillow Thank you in advance for your help -
Unexpected tokens in <!DOCTYPE html> in pycharm community edition
I am new in using pycharm but I am loving it gradually. I am getting a red underline on and the error is "Unexpected Token". Why pycharm shows it? I can't understand. -
Django save image form data
I currently have a 3x3 grid of images. I want the user to select an image press next and record that response in the database. I've been trying to solve this for a while and I am not sure what to do. Any help is greatly appreciated. templatetag: random_Image.py {% random_images_category1 3 as images_normal %} <div class="row no-pad display-flex my-row"> {% for image in images_normal %} <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col- my-col my-col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4 my-col"> {% csrf_token %} <input class="img-thumbnail" type="image" id="image" alt="Image" src="{{ MEDIA_URL}}{{ image }}"> {# <img class="img-thumbnail" src="{{ MEDIA_URL}}{{ image }}">#} </div> {% endfor %} </div> template_tag: @register.simple_tag def random_images_category1(count=3): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/normal/' path = '/app_pickfeel/static/app_pickfeel/images/normal/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] print(random.sample(files, count)) return [rand_dir + filename for filename in random.sample(files, count)] -
ModuleNotFoundError For Rest Framework
I've installed django rest framework using pip install djangorestframework And added the rest framework to the INSTALLED_APP: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', ] yet I still get this error when I run python3 manage.py runserver: ModuleNotFoundError: No module named 'rest_framework' And to rectify this error I have already tried all this: 1.Tried to install django rest framework using: pip3 install djangorestframework 2.Checked for , after adding 'rest_framework' to INSTALLED_APPS 3.My virtual environment is active 4.I have added markdown and django-filter also using : pip install markdown pip install django-filter 5.Upgraded my pip using: python -m pip install --upgrade pip 6.Tried adding 'rest_framework' as the first app in INSTALLED_APPS 7.Tried deactivating and the activating again the virtual environment I'm using Django == 3.0.2 and Django REST Framework == 3.11.0 So now what should I do to remove this error?? -
AttributeError: This QueryDict instance is immutable for test cases
I am trying to change my request.data dict to remove some additional field. It is working completely fine in views. But when I run test cases for the same, I get this error: AttributeError: This QueryDict instance is immutable Here is my viewset: def create(self, request, *args, **kwargs): context = {'view': self, 'request': request} addresses = request.data.pop("addresses", None) serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) response = super(WarehouseViewSet, self).create(request, *args, **kwargs) if addresses is None: pass else: serializer = self.get_serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) addresses = serializer.update_warehouse_address(request, addresses, response.data["id"]) response.data["addresses"] = addresses return Response(data=response.data, status=status.HTTP_201_CREATED) and here is my test case for the same view: def test_create_warehouse_authenticated(self): response = client.post( reverse('warehouse_list_create'), data={ 'name': self.test_warehouse['test_warehouse']['name'], 'branch': self.test_warehouse['test_warehouse']['branch'], }, **{'HTTP_AUTHORIZATION': 'Bearer {}'.format( self.test_users['test_user']['access_token'] )}, ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) How to fix this error? -
CAN NOT import rest framekwork in Django
I am very very NEWBIE in django. But i've faced the problem, that i couldn't find here. I have installed virtualenv; IN virtualeenv i've installed django and rest_framework. However, i cannot import rest to the project. when i install again: Requirement already satisfied: djangorestframework in src\myvenv\lib\site-packages (3.11.0), etc. My projects and virualenvs in disk 'D' if it's somehow affects. I have latest django and python version. Thank you -
how to create unique_together index using Uniqueconstraints function in django?
official document says: UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future. here is my code class Meta: constraints = [models.UniqueConstraint(fields=['token','obj'], name='hello')] when i migrate it creates a migrations with message '- Create constraint create_like on model helloWorld'. but it is not creating an index on database. -
How can I add if statement to a deleteview? CBV django
Hey I want to add if statement and according to it decide if to delete the object or not. I could not find it online. In general how can I add if statements to any CBV including Update for example.. -
Django REST Cache Invalidation
I have a Django project and API view implemented with Rest framework, i'm caching it using the @cache_page decorator but i need to implement a cache invalidation and im not finding how to do that, do i need a custom decorator? The problem: The view check the access of the API KEY and it caches it for previuos access check, but if the user changes the API KEY before the caches expires the view will return an OK status of the key that doesnt exist anymore -
Annotate Queryset with Related Model fields
I have following Schema in Django with PostgreSQL. Class Person (models.Model): name = models.CharField(max_length=255) email= models.CharField(max_legth = 255) created_at = models.DateTimeField() Class PersonTask(models.Model): title = models.TextField() created_at = models.DateTimeField() Class PersonHistory(models.Model): note = models.TextField() created_at = models.DateTimeField() Now I need to query the DB like all values of Person with latest PersonTask__title and latest PersonHistory__note Eg: <Queryset: [{name: "abc" ,email:"abc@gmail.com",created_at :"2019-01-02", Task_Title:"This is my latest tasktitle" , HistoryNote : "This is my latest history note"}, {name: "abcd" ,email:"abcd@gmail.com",created_at :"2019-03-02", Task_Title:"This is my latest tasktitle for abcd" , HistoryNote : "This is my latest history note for abcd"}]> But, I could max get is either id of Latest Task and Latest History by Person.objects.filter(customer_id= 1).annotate( max_task = Max('persontask')).annotate(max_note = Max('personhistory')).order_by('-id') Or a random task or note texts using below query Person.objects.filter(customer_id= 1).annotate( max_task = Max('persontask__title')).annotate(max_note = Max('personhistory__note')).order_by('-id') How this can be tackled?? -
Buffer dtype mismatch, expected 'SIZE-t' but got 'long long'
I developed 3 ML models in spyder, they are Linear Regression, Polynomial Regression and Random Forest Regression. In sypder all pf them worked well. However when I deployed on Django for creating a webapp, Random Forest was raising " ValueError: Buffer type mismatch, expected 'SIZE_t' but got 'long long' ". (I tried removing randomforest and other two models worked well). Check this out first:- ValueError Image of CMD Model Developed in Sypder """****************** Import Lib ******************""" import numpy as np import pandas as pd import seaborn as sns from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score """****************** Loading dataset ******************""" boston = load_boston() dataset = pd.DataFrame(boston.data, columns=boston.feature_names) dataset['target'] = boston.target """****************** Data Preprocessing ******************""" """ Data Analysis """ # Check Null dataset.isnull().sum() # Calculate X and y X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values.reshape(-1,1) # train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=25) """ Visualizing Data """ corr = dataset.corr() sns.heatmap(corr, annot=True, cmap='Blues') sns.pairplot(dataset) """****************** Regression Models ******************""" """ Linear Regression """ from sklearn.linear_model import LinearRegression regressor_linear = LinearRegression() regressor_linear.fit(X_train, y_train) cv_linear = cross_val_score(estimator = regressor_linear, X=X_train, y=y_train, cv=10) """ Polynomial Regression """ from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree = 2) X_poly = poly_reg.fit_transform(X_train) … -
How do I specify DRF oauth required_scopes in function based api_view?
I'm trying to make my function based rest framework views which use the @api_view decorator with the Django OAuth Rest Framework Toolkit, where I'm using TokenHasScope as the permission_class. However, this needs a mandatory attribute called required_scopes but I'm not sure how I can get this specified in a function based views? -
Django: How to save predefined values in modelForm
Good evening, is it possible to change the ModelForm inside my forms.py, so that already known values are saved inside the database? For example: models.py: class Customer(models.Model): name = models.CharField(max_length=255) class Project(models.Model): customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Entry(models.Model): user = ...request.user.id?... customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) project= models.ForeignKey(Project, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=255) forms.py: class EntryForm(ModelForm): class Meta: model = Entry fields = '__all__' def __init__(self, *args, pk, **kwargs): super().__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.filter(customer_id=pk) When entering the knew site, I already know about the only possible Customer (pk)! I don't want to place a choicefield inside my knew site, but the customer should be saved inside my database nonetheless! Same goes for the active user (request.user), respectively the id (request.user.id). Can this data be passed into the modelForm as well? Did someone else also had this problem and might know the solution? What do I have to change inside my modelForm to make it work? Thanks for all your efforts and a happy weekend to all of you! -
Running unix shell command from django app hpsted on aws and using apache2 web server
I am using os module for running shell command in django code . It is working fine on local but when running on the apache2 server it is not running os.system(commandDict[i]) on local it is giving status code 0 but on production server it is giving status code 1 can any one suggest alternative or what is going wrong in this . Thanks in advance -
Using a key from a for loop in django
I have an array of arrays that I am trying to put into a table. It's something that works easily in PHP but I can't seem to figure out how to do it in Django. I want to do something like this: {% for o in test %} <tr> <td>{{ test.row{{o}}.test1 }}</td> <td>{{ test.row{{o}}.test2 }}</td> <td>{{ test.row{{o}}.test3 }}</td> </tr> {% endfor %} -
How to run multiple instances of a Django app?
This question doesn't involve any code. I just want to know a way to run multiple instances of a django app and if it is really possible in the first place. I make django apps and host them on Apache. With the apps, I noticed a conflict between multiple users accessing the web app. Let us assume it is a web scraping app. If one user visits the app and run the scraper, the other user accessing the site from a different location doesn't seem to be able to visit the app or run the scraper unless the scraping that the first user started finishes. Is it really possibe to make it independent for all different users accessing the app? Please suggest! Thanks