Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply highlight function on each table row?
I developed a web project where I can upload two files and django server execute a function to return the lines that don't match with other in a pandas dataframe which is renderized in a html template. Is returned a two columns table, file1 and file2. I would like to have another column with the text and text difference 'highlighted'. I have no knowledge about javascript programing, but I don't know how to apply the function on each table row. My views.py def index(request): form = UploadFileForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): check = CheckFiles(form.cleaned_data["arquivo1"], form.cleaned_data["arquivo2"]).verifica_tamanho() if type(check) == str: return HttpResponse('The file are the same!') #return HttpResponse(check.to_html()) return render(request, 'index2.html', {'check': check}) else: print('Invalid Form!') return render(request, 'index.html', {'form': form}) and in my index2.html: <table class="table" border="1px"> <thead class="thead-dark"> <tr> <th scope="col">Original File</th> <th scope="col">Secondary File</th> </tr> </thead> <tr> {% for _, record in check.iterrows %} <tr> {% for value in record %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} </tr> </table> and the highlight javascript function is: highlight($("#new"), $("#old")); function highlight(newElem, oldElem){ var oldText = oldElem.text(), text = ''; newElem.text().split('').forEach(function(val, i){ if (val != oldText.charAt(i)) text += "<span class='highlight'>"+val+"</span>"; else text += val; … -
Stop all threads in ThreadPoolExecutor
So I need to check for a working proxy from a list with a ThreadPoolExecutor I created a function that send a request to a particular url and if function returns 200 status code I need to stop all other code running on other Threads and return a Response in django view. What can I do? Or do you have another approach to find a working proxy from a proxy list? -
which field should i use to allow more than one comment?
i am trying to add comments to the auction page but only allow adding a comment per auction which models field should i use to allow more than one comment? when i try add more than one comment in the admin page the page show it: Comments with this Auction already exists. models.py: class Auction_listings(models.Model): product_image = models.CharField(max_length=500) product_title = models.CharField(max_length=40) product_description = models.CharField(max_length=200) product_category = models.CharField(max_length=20, default="others") product_price = models.FloatField() #IntegerField() username = models.CharField(max_length=64) post_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.product_title}" class Bids(models.Model): auction = models.OneToOneField(Auction_listings, primary_key=True, on_delete=models.CASCADE) username = models.CharField(max_length=64) is_closed = models.BooleanField(default=False) bid_value = models.FloatField() def __str__(self): return f"by {self.username} in {self.auction}: {self.bid_value}" class Comments(models.Model): auction = models.OneToOneField(Auction_listings, primary_key=True, on_delete=models.CASCADE) username = models.CharField(max_length=64) content = models.CharField(max_length=150) date = models.DateField(auto_now_add=True) def __str__(self): return f"by {self.username} in {self.auction} on {self.date}" thank you in advanced -
Django dynamic image show in sub-directories
I'm trying to create a html template that represent a folder structure with images in it, but there are a lot of sub-directories and sub-sub-directories and sometimes it may change. So I wonder if there is a better way to do this that doubling the code. This is the folder structure, each subdirectory is a different page: -Folder: - Subdirectory 1: - Sub-sub-directory: - Sub-sub-directory: - image - image - Subdirectory 2: - file - sub-sub-directory: -image - sub-sub-directory: - sub-sub-sub-directory: - image - image In my models.py I have this to get the images in the folder, so I can get the images in the folder def getPath(s): s=s.split(os.path.sep, 1) s=s[1] return s def getListOfFiles(): filelist = [] for root, dirs, files in os.walk('C:/Users/g/Desktop/TestImages'): for file in files: filelist.append(os.path.join(root,file)) result = map(getPath, filelist) result=list(result) return result class Folders(Page): template = "almacen_folders/folders.html" ... files_folder=getListOfFiles() and I do this in my html file to get the images and show it, right now I have to duplicate the code to get the images for each level of the sub-directory so I think is much longer that it should be. page.files_folder is a list with the path of the images, page.title is the … -
Django DB design for deleting crucial models?
I've run into an issue that I really haven't dealt with before. I have a task to upgrade from django 1 ==> 2. (django 1 doesn't require on_delete when dealing with relationships) I have a couple of crucial models that have relationships inside, but I definitely don't want to CASCADE those records. For example, if a user deletes their account, I don't want their expenses to be deleted. Maybe we need to keep those expense instances for tax records later, etc. I have read that DO_NOTHING can also be dangerous. With a model like this, what would be the best course of action when dealing with the ForeignKeys? I appreciate all the help in advance. class Expenses(models.Model): user = models.ForeignKey(Account, null=True, blank=True, on_delete=models.?) event = models.ForeignKey(Event, null=True, blank=True, on_delete=models.?) payee = models.CharField(max_length=128, null=True, blank=True) category = models.ForeignKey(Category, blank=True, null=True, related_name='expense_category', on_delete=models.?) -
Populating template with PDFs using DjangoCMS
I have stored the PDFs that I want, in a database, using django-filer and I want to populate an html list, that is in a template, with the urls and the names of those PDFs. Is there anyn way I can do that? Because I can't find any documentation that points to an example like that. P.S I'm using Django 3.0.8 and Django-cms 3.7.3 -
Should I use a cron job, daemon Celery in Django?
What would be the particular use cases of a cron job, a daemon, and Celery? And when should I be using which? I'm aware with these terms but as for Django, I've only tried Celery for sending emails in the background that too as a learning project. I later read more about cron jobs but what would be some practical uses cases for each of these and when should I be using what? -
Update existing data based on days - DJANGO
I have a problem in my project that is not being able to update a column field based on time. That is, I will insert a data via form and fill in the date field, I want that over the days to update a specific field. For example, if 10 days have passed since I inserted the form in my database, I want that on the 11th I change the status of open order to late. I tried to overwrite the save method but it only works when I edit the form and save, or when I insert the form, but that is not my goal. models.py: class Order(models.Model): name = models.CharField(max_lenght = 100) data_start = models.DateField(default=date.today) status = models.Charfield( max_length=50, default='Open', choices=( ('Open', 'Open'), ('Late', 'Late'), ) def save(self, *args, **kwargs): days_for_late = datetime.timedelta(days=15) late = self.data_start + days_for_late today = datetime.date.today() if today > late: self.status = 'Late' super(Order, self).save(*args, **kwargs) I am days stuck in this stage, reading many similar questions here on the site, but I couldn't solve it. And most talk about overwriting the save method, which didn't work for my problem -
Django Blog using CKEditor
I use CKeditor for a blog post in Django, but it's showing horizontal lines in the post, I don't know why it showing this... see more in pictures enter image description here -
Problem populating Django many to many relationship with list
I am trying to populate my Django SQL db with data from external CSV files but when I run my population file, the parent ManyToManyField model (Film) won't take the query-object which I provide from the child (actor) model because (i think) it is a list. Is it possible to parse in a list to a model with a get_or_create call? If not, how can I work around this problem? My models.py file looks like this: class Actor(models.Model): actor_id = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=40) class Film(models.Model): film_id = models.CharField(max_length=20, unique=True) title = models.CharField(max_length=60) actors = models.ManyToManyField(Actor) And my populate.py file looks like this: import pandas df = read_csv('csv_file.csv') def populate_film(): for index, row in in df.iterrows(): film_csv_id = str(row['IMDb ID']) film_name = str(row['Film']) list_of_actors = row['Actors'] #The CSV actors column returns a the list of actor_ids which I query against the Actor model #I then put these queries into a list for the get_or_create step actor_query_list = [] for actor_csv_id in list_of_actors: actor_query = Actor.objects.get(actor_id = actor_csv_id) actor_query_list.append(actor_query.id) film = Film.objects.get_or_create(film_id = film_csv_id, title = film_name, actors = actor_query_list) The error message i receive reads: Field 'id' expected a number but got [xxxx, xxxx]. Thanks! -
How to convert Django queryset to excel file ? proper datetime format
class sold(models.Model): quantity=models.CharField(max_length=255) price=models.CharField(max_length=255) sold_date=models.DateTimeField() -
serializer only certain fields in foreing key relation
I'm trying to serializer two nested models linked by a foreing key: class Category(models.Model): sp = models.ForeignKey('species.Sp', on_delete=models.CASCADE, related_name='species_category') category_name = models.CharField(max_length=50) class Catch(models.Model): weight = models.IntegerField() category = models.ForeignKey('species.Category', on_delete=models.CASCADE,) I know is possible to use depth option, but it serialize all the fields of the related model, for example: class CatchesSerializer(serializers.ModelSerializer): class Meta: model = Catch fields = ['id', 'weight', 'category', ] depth = 1 returns [ { "id": 335, "weight": 4710, "category": { "id": 1, "category_name": "1", "sp": 41 } }, ... ] How is the way to serialize only certains fields of the related model? for example: [ { "id": 335, "weight": 4710, "category": { "sp": 41, } }, ... ] -
Inline Form Set Factory in Django does not allow to create instances
I'm implementing Inline Form Set Factory for adding many objects horario respect to medico object, I just can add one element, and for the next time I had the error [{'id': ['This field is required.']}] but my model doesn't have an id (I think it is added automatically). I'm not using form for this. VIEWS def crear_horario(request, medico_id): medico = Medico.objects.get(pk = medico_id) HorarioForm = inlineformset_factory(Medico, Horario, fields=('dia', 'inicio_hora', 'inicio_minutos', 'inicio_periodo', 'fin_hora', 'fin_minutos', 'fin_periodo',), extra = 1) if request.method == 'POST': formulario = HorarioForm(request.POST, instance = medico) if formulario.is_valid(): formulario.save() return redirect('crear_horario', medico_id = medico.id) else: print(formulario.errors) formulario = HorarioForm(instance = medico) context = { 'formulario': formulario, } return render(request, 'administrador/admi_crear_horario.html', context) MODELS. (I know it's terrible but the requirements for the work are these) class Medico(models.Model): ESPECIALIDAD = ( ('1', 'CARDIOLOGIA'), ('2', 'PEDIATRIA'), ('3', 'CIRUGIA'), ('4', 'ODONTOLOGIA'), ('5', 'OFTALMOLOGIA'), ) usuario = models.OneToOneField(User, on_delete = models.CASCADE) especialidad = models.CharField(choices=ESPECIALIDAD, max_length=1) def __str__(self): apellidos = self.usuario.last_name nombres = self.usuario.first_name return apellidos + ", " + nombres class Horario(models.Model): DIA = ( ('1', 'Lunes'), ('2', 'Martes'), ('3', 'Miercoles'), ('4', 'Jueves'), ('5', 'Viernes'), ('6', 'Sabado'), ) HORA = ( ('1', '01'), ('2', '02'), ('3', '03'), ('4', '04'), ('5', '05'), ('6', '06'), ('7', … -
Django models : Field 'id' expected a number but got 'Students'
I'm trying to filter objects based on a foreign key and I'm getting that error. When I use int( id of categories) the code below works. How can I make it work for strings? models.py: from django.db import models # Create your models here. class Category(models.Model): category_name=models.CharField(max_length=40) def __str__(self): return self.category_name class dash(models.Model): title=models.CharField(max_length=40) card_pic=models.ImageField(upload_to="dash_pics/") embed_tag=models.TextField() category=models.ForeignKey(Category,on_delete=models.CASCADE) objects = models.Manager() def __str__(self): return self.title views.py: def students(request): stu_dashboards = models.dash.objects.filter(category='Students') return render(request,'dashboards/students.html',{'dashboards':stu_dashboards}) -
ImportError: libGL.so.1: cannot open shared object file: No such file or directory while importing OCC
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I have installed anaconda and pythonocc-core package by creating a 10_anaconda.config file in .ebextensions folder. 10_anaconda.config; commands: 00_download_conda: command: 'wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh' 01_install_conda: command: 'bash Anaconda3-2020.02-Linux-x86_64.sh -b -f -p /anaconda' 02_conda_install_pythonocc: command: '/anaconda/bin/conda install -y -c dlr-sc pythonocc-core=7.4.0' Then I have created a folder in one of my apps and created a __init__.py and cadLoader.py file into that folder. So my project structure such as below; mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py app/ migrations/ __init__.py cad/ __init__.py cadLoader.py __init__.py admin.py apps.py models.py tests.py views.py ... I have added the anaconda path to __init__.py which it's in the cad folder; import sys sys.path.append('/anaconda/lib/python3.7/site-packages') And I have added the import lines to cadLoader.py for trying; import os from OCC.Extend.DataExchange import read_stl_file from OCC.Display.SimpleGui import init_display from OCC.Core.GProp import GProp_GProps from OCC.Extend.DataExchange import read_step_file from OCC.Extend.DataExchange import read_iges_file from OCC.Core.Bnd import Bnd_Box from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh from OCC.Core.BRepBndLib import brepbndlib_Add from OCC.Core.BRepGProp import brepgprop_VolumeProperties When I deployed it to Elastic Beanstalk, I got the error lines below. from data.modellib.cad.cadLoader import CADLoader File "/var/app/current/data/modellib/cad/cadLoader.py", line 2, in <module> from OCC.Extend.DataExchange import read_stl_file File "/anaconda/lib/python3.7/site-packages/OCC/Extend/DataExchange.py", line … -
Get value of boolean field at given datetime Django
I have a boolean field on a model that tracks if the user is active or not (different from the default is_active), and I am hoping to know how many users were active in each of the past 5 weeks. Is there a way in Django to find the value of my boolean at a given point in time? Or when it was changed? I currently do this: Customer.objects.filter(is_subscribed=False).count But obviously this just gets the current amount, and I need to get the amounts for the previous weeks. -
Python requests return status code 400 on Django but without django it is working fine
I am making an Amazon Scraper and facing some kind of problem. Here is my code def scrapedPage(self,URL, user_agent): header = {"User-Agent": user_agent, 'Accept-Encoding': 'identity', 'Server': 'Server', 'Content-Type': 'text/html', 'Accept-Ranges': 'bytes', 'Content-Encoding': 'gzip', 'Cache-Control': 'no-transform', 'Connection': 'keep-alive', 'Vary': 'Accept-Encoding' } proxy = {'https': proxy} page = requests.get(URL, headers=header, proxies=proxy) return page It returns status code 400 when I use in Django framework but the same code respond 200 status code when run stand alone without Django. -
How can I use django_filters to make filter fields dropdown?
I want to utilize django_filters to make a filter that has a dropdown to enter filter field values, and is able to filter on multiple fields at the same time. It should look something like this: Being new to Django, I don't have much of an idea how to do this. My current code is as follows: filters.py import django_filters class DeviceFilter(django_filters.FilterSet): class Meta: model = Device fields = ['serial_number', 'hardware_version', 'hardware_revision', 'asic', 'asic_version', 'status', 'location', 'part_number', 'received'] views.py from .filters import DeviceFilter class DeviceListView(LoginRequiredMixin, SingleTableMixin, FilterView): model = Device table_class = DeviceTable filterset_class = DeviceFilter template_name = "list.html" logger.debug("\n\nIn inv List View\n\n") def get_table_data(self): self.filter = DeviceFilter(self.request.GET, queryset = super(DeviceListView, self).get_table_data()) return self.filter.qs def get_context_data(self, *args, **kwargs): logger.debug("Getting inv context data for list view.") context = super(DeviceListView, self).get_context_data(*args, **kwargs) context["active"] = DeviceTable(self.filter.qs) context["filter"] = self.filter return context html page <div> <style> .form-control.is-valid, .form-control.is-invalid { background-image: none; padding-right: inherit; border: 1px solid #ced4da; } </style> {% if filter %} <form action = "" method="get" class = "form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} </div> This creates a filter with all the fields displayed simultaneously, which while functional isn't exactly what I'm looking … -
Is it possible to use more than one framework at the backend(Spring boot + Django)?
tl;dr: Is Spring + Django back-end possible? When I was new to industry and was still working my way around the office, I got interested in Django and created a very small, basic-level application using the framework. When I got to meet my team after a few weeks, they said to go for Spring framework. After spending half a year on the framework and the main proj, I finally started to get time to start working off-hours. But, I don't want to lose both the skills - My teammate(when we were still in office ;) ) once told me that they worked on a project that started with python code, and then later added features using Java. And I am unable to find any helpful google searches(mostly showing Spring vs Django). How should I go about it? Is it too much to ask for? Is it worthwhile? Will I learn some new concepts of application architecture a I noob like me would have missed. Please provide me with some insight. Are there resources(docs) I can go through? P.S. I'm not a diehard fan of either of the frameworks right now, just another coder testing waters. -
how to call a function to add new comments in Django?
I started to learn django a week ago and i'm trying to call a function for add comments for the product page but it doesn't work. i tried to call the function in another function but it doesn't work too views.py: def add_comment(request, item_id): if request.method == "POST": comment = request.POST.get("comment") new_comment = Comments(auction=item_id ,username=request.user.username, content=comment) new_comment.save() return redirect("view_item", id=item_id) def view_item(request, id): try: item_id = Auction_listings.objects.get(pk=id) comments = Comments.objects.filter(auction=item_id) bid = Bids.objects.get(auction=item_id) return render(request, "auctions/item.html", { "auctions": item_id, "comments": comments, "bid": bid }) except: return render(request, "auctions/item.html", { "auctions": item_id }) html: <div id="comments-area"> <h2>Comments</h2> {% if user.is_authenticated %} <form action="{% url 'add_comment' auctions.id %}" method="post"> {% csrf_token %} <input type="text" name="comment" class="text-field" placeholder="Add a comment..."> <input type="submit" value="Comment" class="submit-bnt"> </form> {% for comment in comments %} <div id="comment"> <a href="">{{ comment.username }}</a> &bull; <span id="comment-date">{{ comment.date }}</span> <p id="comment-content"> {{ comment.content }} </p> </div> {% endfor %} {% else %} <p id="comment-msg"> <a href="/login">Log in</a> or <a href="/register">Register</a> to see comments. </p> urls.py: from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("user/<username>", views.user_page, name="user_page"), path("new", views.create_listing, name="create_listing"), path("item/<id>", views.view_item, name="view_item"), path("item/<item_id>", views.add_comment, name="add_comment"), path("category/", views.category, name="category"), path("watchlist/", … -
Creating user with API Django Rest Framework
how would i go about creating a user inn the database with a api call? Im using the Model.serializer, ive tried to override the save method and create a user with the request.data but i cant seem to get it to work. Any tips? The error that i get is that when i try to asign the user to the request.data it comes back saying that the value needs to be a user instance. How do i make the requested data a user instance? This is my code. @api_view(['POST']) def createUser(request): serializer = userSerializer(data=request.data) print(request.data['username']) if serializer.is_valid(): serializer.save() if request.data['password'] == request.data['password2']: userModel = UserModel.objects.create( user=request.data, username=request.data['username'], email=request.data['email'], firstname=request.data['firstname'], lastname=request.data['lastname'], password=request.data['password'], password2=request.data['password2'] ) userModel.save() return Response('User was created') else: return Response('Passwords must match') -
'put_object() only accepts keyword arguments.'
I am getting the error "'put_object() only accepts keyword arguments.' while uploading a memory uploaded file in S3. upload_file1 = request.FILES.get('upload_file1') file_name1 = upload_file1._name upload_file_path = 'Client/' + client_id + '/' + file_name1 s3.put_object(settings.AWS_STORAGE_BUCKET_NAME,Body=upload_file1,Key=upload_file_path ) please suggest -
How to make data migration function more efficient
I'm cleaning up an older PostgreSQL database so that null isn't being used on string-based fields. To do this I'm using a Django data migration which works on my local machine (although it's a bit slow) but the migration is being killed on production. I'm guessing it uses a ton of memory. I've also tried doing this in the shell manually but the process is still being killed. Same with increasing the batch size. Is there a more efficient way of executing this function that won't use a ton of resources? from django.db import models def set_null_char_field_to_empty_string(apps, schema_editor): model_classes = [ apps.get_model('order', 'Order'), ] for model in model_classes: char_fields = [f.name for f in model._meta.get_fields() if isinstance(f, models.CharField)] if char_fields: filter_args = models.Q() for field in char_fields: filter_args |= models.Q(**{f'{field}__isnull': True}) objs = model.objects.filter(filter_args) objs_to_update = [] for obj in objs: for field in char_fields: setattr(obj, field, getattr(obj, field) or '') objs_to_update.append(obj) model.objects.bulk_update(objs_to_update, fields=char_fields, batch_size=500) -
Django passing user ID to filter models
I have trying to filter objects in a model to avoid people putting events in their calendars which over lap. I found the below link which helped (Django form field clean to check if entered date is in a stored range). It has left me with another issue that it blocks any other user from having an event at the same time. My Question is, can I pass the user id number to filter the queryset? it works if I manually input my user ID number? Code below with my last attempt? model.py from django.db import models from django.contrib.auth.models import User class Event(models.Model): manage = models.ForeignKey(User, on_delete=models.CASCADE, default=None) title = models.CharField(max_length=200, default='free') description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() def __str__(self): return self.title + " - " + str(self.start_time) + " - " + str(self.end_time) Form.py from django import forms from django.forms import ModelForm, DateInput from calendar_app.models import Event from django.contrib.auth.models import User class EventForm(ModelForm): class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = ['title','description','start_time','end_time'] def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # … -
Can't get jquery function to execute
For the life of me I can't figure out why I can't get JQuery functions to operate in my HTML. I have this HTML file and this simple JQuery "click" function that I have been using to test if things are working: {% extends "home/home-base.html" %} {% load static %} {% block js-sub %} <script> $("like").click(function(){ console.log("this worked") }); </script> <script> if (typeof jQuery === 'undefined') { console.log("NOPE")// jQuery is NOT available } else { console.log("WORKING")// jQuery is available } </script> {% endblock js-sub %} {% block home %} {% for post in posts %} <div class="card-body"> <h5 class="card-title"><a href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h5> <p class="card-text">{{ post.content }}</p> <div class="btn-group" role="group"> <button type="button" class="like" >Like</button> </div> </div> {% endfor %} {% endblock home %} I am trying to call the "Like" button with the "like" class but can't seem to get anything to post to the console on the click. I added the if function just to make sure JQuery was loaded and I do get "WORKING" posted to the console every time I load the page. I have also tried typing the same "click" function directly into the console and it works then. Any idea what I'm …