Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: cannot redirect to UpdateView after item is deleted
I'm creating a view just for deleting ListItems that correspond to a List objects, through a ForeignKey. I can successfully delete the ListItem, but I cannot redirect to the original template. def full_remove_listitem(request, listitem_id): list_item = ListItem.objects.get(id=listitem_id) list_item.delete() lista_id = list_item.lista.id return redirect('lists:list_details lista_id') I get: NoReverseMatch at /listas/borrar-producto-de-lista/29/ Reverse for 'list_details lista_id' not found. 'list_details lista_id' is not a valid view function or pattern name. I've also tried: return reverse('lists:list_details', kwargs={'lista_id': lista_id}) But I get: AttributeError at /listas/borrar-producto-de-lista/30/ 'str' object has no attribute 'get' Urls.py: app_name = "lists" urlpatterns = [ path('', views.ListFormView.as_view(), name='my_lists'), path('agregar-producto/', views.add_product_to_list, name='add_product_to_list'), path('mis-listas/', views.update_lists_count, name='update_lists_count'), path('lista-detalles/<int:lista_id>/', views.ListDetailsFormView.as_view(), name='list_details'), path('escuelas-csv/', views.schools_upload, name="schools_upload"), path('borrar-producto-de-lista/<int:listitem_id>/', views.full_remove_listitem, name='full_remove_listitem'), path('borrar-lista/<int:lista_id>/', views.full_remove_list, name='full_remove_list'), path('borrar-escuela/<int:school_id>/', views.full_remove_school, name='full_remove_school'), ] HTML: <div class="row"> {% for list_item in list_items %} {% if forloop.counter0|divisibleby:3 and not forloop.first %}<div class="w-100"></div>{% endif %} <div class="card margin-right3" style="width: 14rem;"> <div class="card-body"> <h5 class="card-title">{{ list_item.product.short_name }}</h5> <p class="card-title">$ {{ list_item.product.price }}</p> <p class="card-text">{{ list_item.description }}</p> <a href="{% url 'lists:full_remove_listitem' list_item.id %}" class="custom_icon"><i class="fas fa-trash-alt custom_icon"></i></a> </div> </div> {% endfor %} views.py: View where I want to redirect: class ListDetailsFormView(LoginRequiredMixin, UpdateView): model = List form_class = ListForm context_object_name = 'lista' pk_url_kwarg = 'lista_id' template_name = "scolarte/listas/lista-detalles.html" def get_context_data(self, *args, **kwargs): … -
Where does Django Signal print the message?
I'm new to Django and this might sound as a silly question but I'm trying to understand the signals and use it in my project. I thought that signals are used to execute action when there is modification in model's instance. However, when I modify my Movie model from Django Admin page, nothing happens. What is the signal supposed to do in this case? Where can I see the "printing a message" message? Thank you very much! apps.py from django.apps import AppConfig from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from .signals import my_signal_function from .models import Movie class MoviesAppConfig(AppConfig): name = 'movies_app' def ready(self): mysender = self.get_model(Movie) post_save.connect(my_signal_function, sender=mysender, dispatch_uid="my_unique_identifier") signals.py def my_signal_function(sender, **kwargs): print("printing a message...") -
Django Rest Framework Model viewset only editable by user who created using username lookup
I have a services model which is linked to the User model using foreign key. I want users to be able to have crud operations from a url of http://localhost:8000/api/users/username-goes-here/services/edit/services/. How do I make a model viewset which can only create, edit, and delete if you are that user? I want the Username to be the lookup field. All help is greatly appreciated. Here is the model: class Services(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='artistservices') name = models.CharField(max_length=50) viewset: from .serializers import ServicesSerializer class EditUserServicesView(viewsets.ModelViewSet): queryset=Services.objects.all() serializer_class = ServicesSerializer urls.py: from .views import EditUserServicesView from rest_framework.routers import DefaultRouter from rest_framework import routers router = routers.DefaultRouter() router.register('services', EditUserServicesView) from django.urls import path, include urlpatterns = [ path('users/<username>/services/edit/', include(router.urls)), ] serializers.py from models import Services class ServicesSerializer(serializers.ModelSerializer): class Meta: model = Services fields = '__all__' Thank you very much! -
Django search form not rising validation error
I'm new into programming (just started learning Django&Python). I'm having issues in validating a form used for a DB search ( bellow the code ).The form should validate if the first field is empty or if the second and third fields are empty. At this moment the behavior is kinda strange. If i remove the form validation everything works as expected in terms of search functionality. With it in place as bellow NO validation is done BUT weird things start to happen: If i enter valid data for 1st field or (field 2 &field 3) -> valid data is returned (expected) If i leave the fields empty and hit search all DB data is returned (not expected) If i enter wrong data only for field 2 or field 3 all DB data is returned (not expected) If i enter wrong data for field 1 or field 2 & field 3 nothing is returned (expected) Totally appreciate any help? #forms.py: class SearchForm(forms.ModelForm): cnp_nbr = forms.IntegerField(label='CNP', widget=forms.TextInput(attrs={'class': 'form-control' }), required=False) first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': 'form-control'}), required=False) last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': 'form-control'}), required=False) def clean(self): # most used!!! all_clean_data = super().clean() cnp_nbr = all_clean_data.get('cnp_nbr') first_name = all_clean_data.get('first_name') last_name = all_clean_data.get('last_name') if … -
django.db.utils.OperationalError: SSL connection has been closed unexpectedly
We have a Django project, which involves also IO operations with Postgres. Recently, we started getting from time to time the following error: django.db.utils.OperationalError: SSL connection has been closed unexpectedly The error occur when trying to create an object: SOME_MODEL_CLASS.objects.create(...) I had many Postgres instances, but have not encountered such a problem. My relevant Django project's database settings: 'HOST': 'localhost', 'PORT': '5432', 'ENGINE': 'django.db.backends.postgresql', The Python's version is 3.6.9, and the package is: django==1.11.11 psql==10 psycopg2==2.7.7 I assume that version upgrade for one/some/all of Django, psql and psycopg2 might do the job, but understanding the reason will help to make sure (or increase the chance) that such an error won't happen again, or at least, will allow me to test it. Any idea for the reason and for solution? -
Django - Migration is applied before its dependency
I'm working on a Django project, and had some trouble which a coworker helped me overcome. However, when we were investigating the issue, she deleted a migration because it seemed to cause some issues. At the end, the issue wasn't related to that, but she left the company now. The project seemed fine, until I tried to apply a change to a model and run "makemigrations" and "migrate", and saw some errors, stating that Migration <migration_name> is applied before its dependency <migration2> on database 'default'. For what I saw online and my coworker told me, I decided to delete the local database and the migrations and re-do them. But when I tried to make the migrations from scratch, some errors appeared, and I tried to recover the migrations in our production server and copy them to my local project, to maybe migrate those instead of generating them on my local project. However, I still can't run the project properly, even with the "good" migrations I got from the production server, it still says that a migration is applied before its dependency. I tried migrating each migration individually, with python manage.py migrate project_name migration_name But it says the same exact error, … -
Django view that processes 2 forms at the same time is not loading any values into the template
The view I have created works and loads the form template up fine and displays all the inputs from both forms. I cannot get it to populate with the values from the User object. I have validated that pk_url_kwarg is being passed a valid pk and is loading the object. class UserProfileEditView(generic.UpdateView): model = User form_class = UserEditForm second_form_class = UserProfileEditForm template_name = 'registration/user_profile_edit_page.html' def get_object(self): user = get_object_or_404(User, pk=self.pk_url_kwarg) return user def get_context_data(self, **kwargs): context = super(UserProfileEditView, self).get_context_data(**kwargs) if 'form_2' not in context: context['form'] = self.form_class(self.object) if 'form_2' not in context: context['form_2'] = self.second_form_class(self.request.GET) return context def get(self, request, *args, **kwargs): super(UserProfileEditView, self).get(request, *args, **kwargs) form = self.form_class form_2 = self.second_form_class return self.render_to_response(self.get_context_data( object=self.object, form=form, form_2=form_2)) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) form_2 = self.second_form_class(request.POST) if form.is_valid() and form_2.is_valid(): user = form.save(commit=False) user.save() user_profile = form_2.save(commit=False) user_profile.user = user user_profile.save() else: return self.render_to_response( self.get_context_data(form=form, form_2=form_2)) def get_success_url(self): return reverse('user_profile_edit') -
Issue Dockerising Django + Celery... Unable to load celery application
I'm having a slight issue with spinning up a Dockerised stack of: Django, Redis, Celery on a server backbone of nginx and gunicorn. The Django application connects to an external PostgreSQL database. I have the following docker-compose.yaml file: version: '3.7' services: web: build: context: ./django dockerfile: Dockerfile expose: - "8000" volumes: - django-static:/usr/src/app/static - django-uploads:/usr/src/app/uploads depends_on: - redis links: - redis:redis environment: ... command: /usr/src/app/wave.sh nginx: build: context: nginx dockerfile: Dockerfile restart: on-failure ports: - 80:80 - 443:443 volumes: - ssl_data:/etc/resty-auto-ssl environment: ALLOWED_DOMAINS: "${STAGING_ALLOWED_DOMAINS}" SITES: "${STAGING_SITES}" redis: restart: always image: redis:latest ports: - '6379:6379' celery: build: ./django command: celery --app=Wave.celery.app worker --loglevel=DEBUG environment: ... volumes: - './django:/usr/src/app/' links: - redis:redis depends_on: - web - redis - nginx restart: on-failure celery-beat: build: ./django command: celery --app=Wave.celery.app beat --loglevel=DEBUG environment: ... volumes: - './django:/usr/src/app/' links: - redis:redis depends_on: - web - redis - nginx restart: on-failure volumes: ssl_data: django-static: django-uploads: However, on utilising: docker-compose -f docker-compose.wave-api-staging.yml up --build --force-recreate The wave.sh script is as follows: #!/bin/sh rm -rf celerybeat.pid ln -s /run/shm /dev/shm python3 manage.py collectstatic --no-input python3 manage.py migrate python3 manage.py shell < createsuperuser.py pip3 freeze /usr/local/bin/gunicorn Wave.wsgi:application --timeout 3600 --log-level=DEBUG -w 5 -b :8000 Which replaces the following command instruction … -
Two way parent - child relationship among users
I am building an app to register and update children information, this information is to be provided by their tutors. Every child can have multiple tutors, and a tutor can be a tutor for multiple children. This has been solved specifing a Table where I relate a student with each of their tutors by a unique registry, and characterize that relationship accordingly. Now, we are facing the need to specify read/write permissions among some of the tutors that tutor a student. My idea is to create a new table where I relate each of the pairs formed by those tutors, and specify the read and wirte permissions. The problem is that those permissions are not reciprocal, a tutor can have permissions over another, while that other may not have permissions over the first one. I dont know what is better, to have only one registry for each pair of tutors and add boolean fields for every type of posible permission, or define a parent-child type of registry where the parents has permissions over the child. This second option would mean having two registries for each pair of tutor, on where tutor 1 is parent over tutor 2 and another where … -
Is it possible to create a django query that finds the latest unique dates across two models?
I've got two models: class ModelA(models.Model): active_date = DateField() # A bunch of other fields class ModelB(models.Model): active_date = DateField() # A bunch of other fields What I need is an ordered list of active_date values in either table. Additionally, I need to be able to page this list (e.g.- grab [0:10] or [10:20]). The list will get quite long, thus I'd like to be able to do it all in a query. Currently I am getting my dates like: a_dates = ModelA.objects.all().order_by('-active_date').distinct('active_date').values('active_date') b_dates = ModelB.objects.all().order_by('-active_date').distinct('active_date').values('active_date') dates_list = merge_dates(a_dates, b_dates) # function merges lists, drops duplicates, and puts in descending order return dates_list[start:end] Obviously when my number of entities gets large, and that date list gets large, this will become slower. Any thoughts on a better way to do this? -
I want to Create my first URL using the command prompt
I have Django installed,but I was trying to create my first URL and I typed the following using the command prompt "cd myproject" then again I typed "manage.py runserver 127.0.0.1:8000" And I got the following output: "System check identified no issues<0 silenced> you have 17 unapplied migration. Your project may not work properly until you apply the migrations for app: admin,auth,contenttypes,sessions." Please what do I do to fix this problem so that my project can work properly? Note that: I am new in using Python and Django -
Update Queryset of Model Choice Filter in a filter method instead of init
I know that we can modify a django filter in its init method and we can define custom filter functions for filtering the queryset. I have a model choice filter which fetches cities from the db. The cities contain different values for example: Aachen, Achen (Kreis) etc. self.filters["city"] = ModelMultipleChoiceFilter( queryset=City.objects.exclude(name__contains="Kreis").order_by("name") ) I have a Boolean Filter named include_kreis self.filters["include_kreis"] = BooleanFilter( field_name="city", widget=forms.CheckboxInput, method=self.kreis_custom_filter, label="Include Kreis" ) As you can see that initially, I have excluded Kreis values and the checkbox is unchecked. My custom function for include_kreis filter is: def kreis_custom_filter(self, queryset, name, value): if value == False: return queryset.exclude(city__name__contains="Kreis") else: return queryset.all() I am adding the cities with Kreis in its name to the queryset based on the value of Bool filter. What I want is to also modify the values in the model choice filter City. Something like this: self.filters["city"].queryset = City.objects.all().order_by("name") I tried writing the above line in the custom filter function "include_kreis" in else statement but the dropdown on the frontend doesn't update the values. FAILED ATTEMPT: def kreis_custom_filter(self, queryset, name, value): if value == False: return queryset.exclude(city__name__contains="Kreis") else: self.filters["city"].queryset = City.objects.all().order_by("name") return queryset.all() A way to do this can be sending an ajax … -
How to add on click to list of products in html and get the item clicked to firestore
I'm trying to make a simple shopping cart using Django and Firebase Admin SDK, I have queried the Firestore data in a list and displayed them in HTML, now I want to add a click listener to the list of items and get the item clicked into a Firestore collection using javascript. Now, when I click on an item other than the first item nothing happens, that is, when I click on the first item displayed on the page everything works out fine, but the other does not. python view.py to display the items def home(request): collection_ref = db.collection(u'products').get() documents = list(doc.to_dict() for doc in collection_ref) return render (request,'store/home.html',{'product':documents}) home.html {% block content %} {% for doc in product %} <div class="jumbotron"> <div class="col-sm-4"> <div class="card" > <div class="card-body"> <a href="#" class="img-prod"><img class="img-fluid" id="productUrl" src="{{doc.productImage}}" alt="{{doc.productName}}"> <h1 class="card-title" id="productName">{{doc.name}}</h1> <p class="card-subtitle mb-2 text-muted" id="productPrice">{{doc.price}}</p> <p class="card-text" id="productDescription">{{doc.description}}</p> <button type="button" id="addtocart">Add to cart</button> </div> </div> </div> </div> {% endfor %} {% endblock content %} js code firebase.initializeApp(firebaseConfig); var db = firebase.firestore(); var addToCart=document.getElementById('addtocart'); addToCart.addEventListener('click', (event) =>{ var image=document.getElementById('productUrl').src; var productName = document.getElementById('productName').innerHTML; var productPrice= document.getElementById('productPrice').innerHTML; db.collection("orders").add({ pName: productName, price: productPrice, url:image }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) … -
Django forms all changes in other field except the image field is working
image changes are working in django admin but when I am trying to change the same in html form all other changes except the image field are being reflected. views.py def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() return redirect('view_profile') else: form = EditProfileForm(instance=request.user.userprofile) args = {'form': form} return render(request, 'post/update_profile.html', args) update_profile.html {% extends "post/header.html"%} {% block content %} <div class="container"> <form method="post" enctype='multipart/form-data'> {% csrf_token %} <p >Bio: {{ form.bio }}</p> <p> Phone {{ form.phone }}</p> <p> Website : {{ form.website }} </p> <p> Image : {{ form.image }}</p> <button type="submit">Submit</button> </form> <br> </div> {% endblock content %} forms.py class EditProfileForm(UserChangeForm): class Meta: model = UserProfile fields = ( 'bio', 'phone', 'website', 'image', ) model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) bio = models.CharField(max_length=100, default='',blank = True) website = models.URLField(default='',blank = True) phone = models.IntegerField(default=0,blank = True) image = models.ImageField(upload_to='profile_image',default = 'octocat.png') def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) -
Django ORM - sort by name and score
I have these two models: class Game(models.Model): name = models.CharField(max_length=255) ... class Score(models.Model): score = models.BigIntegerField() ... And I would like to order all the scores by: Game name Score within the game So, the results I want is: Game A 100.000 90.000 80.000 Game B 50.000 40.000 30.000 Game C 200.000 190.000 180.000 I hope you get the idea. Thanks! -
Django prefetch and select related
I'm having troubles to understand prefetch_related and select_related in Django ORM. I have the following models: class City(models.Model): name = models.CharField(max_length=35) state = models.ForeignKey('states.State', on_delete=models.CASCADE) class Street(models.Model): name = models.CharField(max_length=35) building = models.ForeignKey('buildings.Building', on_delete=models.CASCADE) city = models.ForeignKey('cities.City', on_delete=models.CASCADE) And now my views.py: cities = City.objects.all() streets = Street.objects.all() for city in cities: has_bank = streets.filter(building_id=1) if has_bank: city.has_bank = 1 has_cinema = streets.filter(building_id=2) if has_cinema: city.has_cinema = 1 has_church = streets.filter(building_id=3) if has_church: city.has_church = 1 But now it hits the database 3 times in each time the for loop iterates. I'm trying to improve the time complexity - which is now 3N + 2 where N is number of cities, but I can't understand the select_related and prefetch_related. Can you give me an example how would I improve this so it does not hit the database 3 times in for loop? -
Uniqueness validation in django form (Both ADD and EDIT)
Here, I wanted to achieve mobile number uniqueness validation in both conditions i.e. at the time of ADD and EDIT form details. I am facing a problem in form edit mode because I am unable to perform uniqueness validation in form edit submit. I wanted only a single mobile no to be stored in a database. While I am editing the form it is bypassing my logic and allowing duplicate entries from EDIT. Could you guys suggest any solution for uniqueness validation? forms.py class StudentForm(forms.Form): name = forms.CharField(required=True,max_length=10) city = forms.CharField(required=True,max_length=10) mobile_no = forms.CharField(required=True, max_length=10) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(StudentForm, self).__init__(*args, **kwargs) def clean_mobile_no(self): mobile_no = self.cleaned_data.get('mobile_no') id = self.request.POST.get('id') if stu_id: if Student.objects.filter(mobile_no=mobile_no).count()>1: raise forms.ValidationError("You have already added mobile no.") else: return mobile_no elif mobile_no and Student.objects.filter(mobile_no=mobile_no).exists(): raise forms.ValidationError("Alreadsy exists.") return mobile_no views.py def add_edit_(request, stu_id=None): if stu_id: stu = CaStudent.objects.get(pk=stu_id) if request.method == 'POST': form = CarServiceForm(request.POST, request=request) if form.is_valid(): name = request.POST['name '] city = request.POST['ccity'] mobile_no = form.cleaned_data['mobile_no'] if stu_id: stu.name=name stu.ccity=city stu.mobile_no=mobile_no cstu.save() messages.success(request, 'Edit Successfully...') return redirect('/.../') else: p = Student(name=name, city=city, mobile_no=smobile_no ) p.save() messages.success(request, 'Information added Successfully...') return redirect('/../') elif id: form = CStudentForm(initial={'name':stu.name, 'city':stu.city,'mobile_no':std.mobile_no '}) else: form … -
NameError: name 'serializers' is not defined
File "E:\django-restAPI\restdrfw2\restapp\serializers.py", line 5, in EmployeeSerializer esal=serializers.FloatField(required=False) NameError: name 'serializers' is not defined serializers.py: from rest_framework import serializers from restapp.models import employee class EmployeeSerializer(serializers.ModelSerializer): esal=serializers.FloatField(required=False) class Meta: model=employee fields='__all__' -
MultiValueDictKeyError at /accounts/signup/ 'password'
I am new in django python and I am getting this weird error during signup process. Please let me know where I am doing wrong. This is my code in views.py: if request.method=='POST': #SignUp if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username = request.POST.get('username1')) return render(request, 'accounts/signup.html', {'error':'username is already taken'}) except User.DoesNotExist: user = User.objects.create_user(username=request.POST['username1'], password=request.POST['password']) auth.login(request, user) return redirect('home') else: #enter info return render(request, 'accounts/signup.html') If i put user= request.POST.get('username1') I get the 'username already taken' message no matter what is my input. my html code: <form method="POST" action="{% url 'signup' %}" class="form" autocomplete="off"> {% csrf_token %} <div class="form__group"> <input type="text" placeholder="username" name="username1" class="form__input" id="username1" autocomplete="off"/> </div> <div class="form__group" autocomplete="off"> <input type="email" placeholder="email" name="email" class="form__input" autocomplete="off"/> </div> <div class="form__group"> <input type="password" placeholder="Password" name="password1" class="form__input" /> </div> <div class="form__group"> <input type="password" placeholder="Confirm Password" name="password2" class="form__input" /> </div> <input class="btn btn-primary" type="submit" value="signup!"/> </form> The error is: MultiValueDictKeyError at /accounts/signup/ 'password' Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 2.2.9 Exception Type: MultiValueDictKeyError Exception Value: 'password' Exception Location: C:\Users\HP\Desktop\django\zakevenv\lib\site-packages\django\utils\datastructures.py in __getitem__, line 80 Python Executable: C:\Users\HP\Desktop\django\zakevenv\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\HP\\Desktop\\django\\producthunt-project', 'C:\\Users\\HP\\Desktop\\django\\zakevenv\\Scripts\\python37.zip', 'C:\\Users\\HP\\Desktop\\django\\zakevenv\\DLLs', 'C:\\Users\\HP\\Desktop\\django\\zakevenv\\lib', 'C:\\Users\\HP\\Desktop\\django\\zakevenv\\Scripts', 'C:\\Users\\HP\\Anaconda3\\Lib', 'C:\\Users\\HP\\Anaconda3\\DLLs', 'C:\\Users\\HP\\Desktop\\django\\zakevenv', 'C:\\Users\\HP\\Desktop\\django\\zakevenv\\lib\\site-packages'] Server time: Thu, 23 Jan 2020 15:20:06 +0000 I have … -
How to get the fieldname of a FileField in the upload_to method, for a field translated with modeltranslation in Django?
I am using django modeltranslation on a FileField. I would like this file to be uploaded in a path /path/to/file/<lang>/file.ext and I guess the best way is to extract the lang from the fieldname (file_en, file_it, file_fr, ...) where upload_to is operating. # models.py def upload_method(instance, filename): lang = "" # how to get this variable? return f"/path/to/file/{lang}/file.ext" class Obj(models.Model): file = models.FileField(upload_to=upload_method) # translation.py @register(models.Obj) class ObjTranslationOptions(TranslationOptions): fields = ("file", ) -
How to reorder using django orm?
Simple model with 3 data columns. input: id ts val var 1 1 1 10 2 2 2 20 3 2 3 30 4 1 4 40 5 1 5 50 6 2 6 60 output: ts val var 1 [1,4,5] [10,40,50] 2 [2,3,6] [20,30,60] AND ts val_var 1 [1,10] [4,40] [5,50] 2 [2,20] [3,30] [6,60] What should be used: annotate() aggregate() group_by()? -
Django: template does not show new records automatically
I'm creating records of my model School on a template. The problem is that the page does not show the elements created after the "Submit" button is clicked. I've to do a refresh to show the new objects on template. why? **views.py:** ### Read CSV file to create records ### import csv, io from django.shortcuts import render from django.contrib import messages def schools_upload(request): template = "scolarte/escuelas/escuelas.html" data = School.objects.all() prompt = { 'orden': 'El orden de las columnas del archivo CSV debe ser: escuela, direccion, referencia, provincia, cantón, parroquia', 'escuelas': data } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'El archivo no es un archivo CSV') data_set = csv_file.read().decode('iso-8859-1') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = School.objects.update_or_create( name=column[0], address=column[1], address_reference=column[2], provincia=column[3], canton=column[4], parroquia=column[5], ) context = {} return render(request, template, context) html: {% block content %} {% if messages %} {% for message in messages %} <div> <!-- | means OR operator--> <strong>{{message|safe}}</strong> </div> {% endfor %} {% else %} <h1>Creación de escuelas</h1> <p>{{orden}}</p> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label for="file1">Subir archivo</label> <input type="file" id="file1" name="file"><br> <small>Solo se aceptan CSV files</small> <button type="submit">Crear escuelas</button> … -
Django, mozilla-django-oidc and admin
i am trying to connect Okta with a custom Django (v.3.0.2) app i am coding, using the mozilla-django-oidc library. So far the initial user authentication and account creation (using Django's user model) works, but i don't understand what i need to do to have the Django AdminSite work. The Adminsite, before introducing mozilla-django-oidc worked as expected. I created an admin user, named "admin" and the user was able to login. To integrate the mozilla-django-oidc library i followed the instructions here: https://mozilla-django-oidc.readthedocs.io/en/stable/installation.html. The instructions do not have any specific mention of the AdminSite. When i access the AdminSite after the library integration, i have the following: The AdminSite uses the default template - my assumption was that it would also use Okta to authenticate. The admin account "admin" that used to be able to login into the AdminSite does not work anymore My goal is to be able to access the AdminSite. I don't mind if it will be over Okta or over the vanilla interface as long as i can access it. Below are the relevant segments from the files (in order to integrate): urls.py urlpatterns = [ path('', static_site.site_index, name='site_index'), path('admin/', admin.site.urls), path('review/', include('review.urls')), path('oidc/', include('mozilla_django_oidc.urls')), ] settings.py # … -
Django + jQuery - Create Placeholders
I have this form: <form method="POST" id="my_form" autocomplete="off"> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> {{ field.label_tag }} renders this label: <label for="id_name">Name:</label> {{ field }} renders this inputfield: <input type="text" name="name" maxlength="20" required="" id="id_name"> Unfortunately, there are no placeholders, so I created them by myself: $(".form-group").each(function(){ $('input[type="text"]').attr("placeholder", "placeholder"); }); The placeholders show up, now I want to populate them with the corresponding values from the database. What would be the best approach to do this? Thank you -
How do I return data from Pandas DataFrame to be returned by Django's JsonResponse?
The answer to this is probably something really simple, but after hours of searching, I really could not find it. I am trying to return a JsonResponse using Django from a pandas dataframe. One of the many things I've tried is the following: from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import pandas as pd @csrf_exempt def do_request(request): result = pd.DataFrame({'bla':[1,2,3],'bla2':['a','b','c']}).to_json(orient='records') return JsonResponse(result, safe = False) The below ends up returning: "[{\"bla\":1,\"bla2\":\"a\"},{\"bla\":2,\"bla2\":\"b\"},{\"bla\":3,\"bla2\":\"c\"}]" when in fact I want it to return: '[{"bla":1,"bla2":"a"},{"bla":2,"bla2":"b"},{"bla":3,"bla2":"c"}]'