Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-wkhtmltopdf - call class to generate PDF, save to memory and add to zip
This is a multi-part question, I'm trying to accomplish two things: In a function, iterate through a query set and call my Generate PDF class Save the PDF in memory, append to a zip file. views.py import ZipFile import io ... def zip_pdf(request, foo_id): """ Collect a record and iterate through a queryset of related records, generating PDFs and saving them into a zip file""" foo = Foo.objects.get(id=foo_id) bars = Bar.objects.filter(foo=foo) waldos = Waldo.objects.filter(foo=foo) # Prepare the zip file zipfilename = f"{foo.name} package" buffer = io.BytesIO() zipf = zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED) # Add files in the database to the zip for bar in bars: filename = str(bar) filepath = bar.file.path zipf.write(filepath, f"bars/{filename}") # Generate PDF files and add to zip for waldo in waldos: # Call the class based view to generate PDF # *** This part is wrong, I am not sure how do it correctly *** # *** Currently it will present me with the option to save or open the first generated PDF and stops *** return Generate_PDF.as_view()(request, waldo_id=waldo.id) zipf.close() response = HttpResponse(buffer.getvalue()) content = f"attachment; filename={zipfilename}" response['Content-Disposition'] = content return response ... Class Generate_PDF(PDFTemplateView): template_name = 'appname/generatepdf.html' cmd_options = [ 'page-size': 'Letter', 'viewport-size': '1920x1080', 'footer-left': '[page]/[tppage]', … -
(Django) When I try to load fixture file into my database, I keep getting field clash error
When I try to load fixture data into my database, I get this error message api.Player.team: (models.E006) The field 'field_name' clashes with the field 'field_name' from mode my model only consist of one model which is Player class Player(models.Model): class Meta: db_table = 'player' pos = models.CharField(max_length=2, default="") name = models.CharField(max_length=30, default="") age = models.PositiveIntegerField() posRank = models.PositiveIntegerField() team = pos = models.CharField(max_length=5, default="") throwAtt = models.PositiveIntegerField() throwYd = models.PositiveIntegerField() throwTD = models.PositiveIntegerField() interception = models.PositiveIntegerField() rushAtt = models.PositiveIntegerField() rushYd = models.PositiveIntegerField() rushTD = models.PositiveIntegerField() rushAvgYd = models.FloatField() target = models.PositiveIntegerField() rec = models.PositiveIntegerField() recYd = models.PositiveIntegerField() recAvgYd = models.FloatField() recTD = models.PositiveIntegerField() totalTD = models.PositiveIntegerField() fumble = models.PositiveIntegerField() fpts = models.FloatField(null=True) ppr = models.FloatField() totGames = models.PositiveIntegerField() -
Creating a generic Search View that returns different template according to origin View
I have a search bar in every template of my project, and I'd like for it to run different lookups for different models according to the template (or view) that you click search on. For example: If you are currently in a page that lists Model A objects, the search bar should take the input and do a lookup for Model A. I've managed to do it like so: def Busqueda(request): """ Esta vista se encarga de buscar los parámetros introducidos en la barra de búsqueda. """ path = request.META['HTTP_REFERER'] b = request.GET.get('q') if 'articulo' in path or 'tablon' in path: # Búsqueda de artículos queryset = Articulo.objects.exclude( estado='r' ).filter( Q(producto__nombre_amistoso__icontains=b) | Q(producto__nombre_amistoso__icontains=b) | Q(producto__referencia__icontains=b) ).distinct( ).order_by('-nota__fecha') paginacion = Paginator(queryset, 15) pagina = request.GET.get('page') resultado = paginacion.get_page(pagina) # TODO: Crear plantilla para resultados_articulos return render( request, "gestion/r_articulos.html", {'resultado': resultado} ) if 'producto' in path: # Búsqueda de productos queryset = Producto.objects.filter( Q(nombre_amistoso__icontains=b) | Q(nombre_amistoso__icontains=b) | Q(referencia__icontains=b) ).order_by('nombre_amistoso') paginacion = Paginator(queryset, 15) pagina = request.GET.get('page') resultado = paginacion.get_page(pagina) # TODO: Crear plantilla para resultados_productos return render( request, "gestion/r_productos.html", {'resultado': resultado} ) if 'pedido' in path: # Búsqueda de Pedidos queryset = Pedido.objects.filter( Q(codigo__icontains=b) | Q(cpm__icontains=b) | Q(distribuidor__nomre__icontains=b) ).order_by('-fecha_creacion') paginacion = Paginator(queryset, … -
AttributeError at / 'Product' object has no attribute 'get_category_display'
hi I want in my products api show the name of category instead of showing category id . I wrote a function to do that for me but I have this error: AttributeError at / 'Product' object has no attribute 'get_category_display' serializers: class ProductSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField() category = serializers.SerializerMethodField() class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'attribute', 'price', 'available', 'created', 'updated', 'popular', 'discount', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } def get_comments(self, obj): comments_qs = Comment.objects.filter_parents_by_object(obj).order_by('posted') return CommentSerializer(comments_qs, many=True).data def get_category(self, obj): return obj.get_category_display() -
FileField working at localhhost and not in production
As the title says my code is working locally but not in production. I need to upload an xls file and check some details on it. It works locally but when I put it on production it doesnt work. I've checked the typical issues like . It simply doesnt work in my server but it does at localhost. Any help/question to fix this? class ExcelForm(forms.Form): def validate_file_extension(value): extension = os.path.splitext(value.name)[1] valid_extensions = ['.xls', '.xlsx'] if not extension.lower() in valid_extensions: raise ValidationError('Valid extensions: xls, xlsx') def validate_file_content(value): df = pd.read_excel(value.file) if 'X' in df.columns and 'Y' in df.columns and 'Z' in df.columns: for i in df.index: mail = df['x'][i] try: validate_email(mail) except ValidationError: raise ValidationError('Error ...') excel = forms.FileField(validators=[validate_file_extension, validate_file_content]) -
Unable to download to download files from my website
I have a small django website that allows file uploading hosted on pythonanywhere. The files are uploaded to aws s3. Now the problem is that even with the presence of download attribute in the html, the browser still renders the file instead of downloading it <a download href="{{file_url}}">Download</a> -
Populate SELECT options with Ajax and Django
I am trying to populate a form with a Select element using ajax and Django. The code I have is the following, but it only shows me one result, when sometimes there are more results. const cliente = document.querySelector('#selectClienteID') cliente.addEventListener('change', (event) => { event.preventDefault(); $.ajax({ type: "POST", data: $("#addPresupuesto").serialize(), url: '{% url "systemapp:add_presupuesto" %}', success: function (data) { const form_label = '<label for="vehiculo">Seleccionar vehículo</label>'+'<select name="vehiculo" class="form-control" id="vehiculo">'+`<option value="" selected="">Seleccionar vehículo</option>` for (x in data.cars) { var car = data.cars[x] console.log(car['marca']) const option = `<option value="`+car['id']+`">`+car['marca']+`</option>` $('#showVehiculos').html(form_label + option); } }, error: function () { console.log('Fail') }, }) }) From my views I send a list with a dictionary and the values to show: form = AddPresupuesto() if request.method == 'POST': if request.is_ajax(): cliente = Cliente.objects.get(id=request.POST.get('cliente')) vehiculos = Vehiculo.objects.filter(cliente=cliente) cars_list = [] for car in vehiculos: cars = {} cars['id'] = car.id cars['marca'] = f'{car.marca} {car.modelo}' cars_list.append(cars) return JsonResponse({'cars':cars_list}) but when showing the results in the template only one is shown It should be two in this case, as shown in the console: Could someone give me a hand? regards -
how to remove tables of uninstalled djago app permanently from mysql database
I have installed the django-notification-system and again uninstalled this package from my django application then made makeimigration and migrate to put its tables on mysql database. However after installing, In the project database list I see tables notification_system_notification, notification_system_target_user_record, and notification_system_target , and after uninstalling the package, still these tables remain in the tables' lists. Is there any way to get rid of them without manually dropping/deleting them? -
In Django how can we limit a model field to be values 1-10 and increment by whole numbers?
We are trying to create a slider for observed opacity of a sediment filter for a house. 1-10 are the possible values. How could we best accomplish/define this in a Django model. Currently we are using a similar approach with inline_filter_clarity = models.PositiveSmallIntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)]) in models.py and would like to use this in a both a change list and a view, with some limitations: Limit the values as whole numbers, if possible. A quick way to have a technician be able to select a value- "slider" is just a criteria suggested from a non-tech team member. We will live with whatever is easiest. -
Creating a form within a table that updates a dataframe using django
I have a django app that takes API data to generate a prediction. I would like to be able to take user feedback, and add that to the training data used to generate the prediction. I have a table that generates a prediction for every hour of the day. I'm trying to add a select/drop down menu for every row in the table. If the user selects a rating from the select button and submits it, that row will be added to the database along with the users 'feedback'. If the user does not select a drop down option, then that row will not be added to the database when they hit submit. I am having trouble finding the correct django method to do this. I am pretty familiar with django models and forms. Not sure how to merge that with a dataframe that has rows updating every few hours. Here is an image of the table -
a question about serializer's objects, their number
I have 2 classes in views.py. In one I display all records, and in the other I detail 1 record. In class 1 I only need 1 field - photo. And in the other class I need 6 fields: id,name... I created a class in serializer.py and specified fields = "all" there - this class serves for my second class in views.py. In order to do the first task, do I need to create a new class in serializer.py or can I pre-define fields somehow? Or if I pass all the fields and only use 1, is there something wrong with that? -
How to set 'A' model's ImageField from 'B' model's ImageField Using Django signal(Pre_save,Post_save)
Here Is my Model from django.db import models from django.utils import timezone # Create your models here. class send_message_model(models.Model): mail = models.EmailField(max_length=100) msg = models.TextField(max_length=500) class projectmodel(models.Model): project_name = models.CharField(max_length=100) project_url = models.URLField() project_desc = models.CharField(max_length=200) project_short_desc = models.CharField(max_length=100,default='') project_date = models.DateField(default=timezone.now) rate = models.IntegerField() project_thumb = models.ImageField(blank=True) def __str__(self): return f'{self.id}' class projectimage(models.Model): project_id = models.ForeignKey(projectmodel,on_delete=models.CASCADE,blank=True,null=True) project_pic = models.FileField(upload_to = 'imgs/') time = models.DateTimeField( auto_now=False, auto_now_add=True) def __str__(self): return f"{self.project_id}" I Want to set the ProjectImage's image to my projectmodel imageField,while saving projectmodel i have tried this, from django.contrib.auth.models import User from Portfolio.models import projectimage,projectmodel from django.db.models.signals import post_save,pre_save from django.dispatch import receiver def do_something(sender,instance,**kwargs): print("User Saved") print(sender) print(instance) # print(created) pre_save.connect(do_something,sender = User) @receiver(pre_save,sender=projectmodel) def add_image(sender,instance,**kwargs): if not instance.project_thumb: print("Image Empty") instance_id = instance.id img = projectimage.objects.filter(id = instance_id).order_by('id')[0] print(img) print(type(img)) thumb = projectmodel.objects.filter(id = instance_id) thumb_save = thumb(project_thumb = img) thumb_save.save() else: print("Image here") But its not working, showing this error, TypeError at /admin/Portfolio/projectmodel/4/change/ 'QuerySet' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/admin/Portfolio/projectmodel/4/change/ Django Version: 3.1.4 Exception Type: TypeError Exception Value: 'QuerySet' object is not callable Exception Location: C:\Django Python\SecondPortfolio\Portfolio\signals.py, line 27, in add_image Python Executable: C:\Program Files\Python38\python.exe Python Version: 3.8.2 Python Path: ['C:\\Django Python\\SecondPortfolio', … -
what its the meaning of Disallow: /*.html?lang=
User-agent: * Disallow: /reply Disallow: /fb/ Disallow: /suggest Disallow: /flag Disallow: /mf Disallow: /eaf Disallow: /*.html?lang= -
Accepting Custom Header for Django View/Model
Im trying to create a payment authentication system that automatically moves a user to a different member group on the site. The User pays through Stripe, which upon the success Webhook makes a call to my Django backend. My plan is to send a put request to /api/v1/users (my AbstractUser model) with a custom header that I make up like this: Frontend JS const headers = { 'PaymentCompleteToken': 'My_Made_Up_Secret_ENV_Key' } axios.post(`/api/v1/users/, data, { headers: headers }) .then((response) => { Models.py class User(AbstractUser): pass Model View class UserViewSet(viewsets.ModelViewSet): permission_classes = (CustomDjangoModelPermissions, ) model = User queryset = User.objects.all() serializer_class = UserSerializer Serializer class UserSerializer(serializers.ModelSerializer): groups = serializers.SlugRelatedField( many=True, read_only=True, slug_field='name' ) class Meta: exclude = ["username", "password"] model = User I only need to update one field, 'Group', in this model. Is there a way to require this header only for this field, the other fields are automatically populated by Django and I don't know if that would work with the header requirement. The other solution I was thinking of was to disable ADD permissions for users, and instead just make the request with my Superuser account and password as the headers instead. Would this be possible/a simpler method? Second Solution … -
Not expected django query set response
I´m making a query set with django to list some courses, the problem is when I made the query in the django shell the return is something like this: <QuerySet [<Course: Course object (1)>,....]> How can I made to obtain the table information? PSD: I made a query set with the users table exactly as I described and the result is the expected, but can´t show the result in the template. Thanks for help. class ListCursos( TemplateView): model1 = User model2 = Course template_name = 'plantillas/miscursos.html' def get_context_data(self, *args, **kwargs): context = super(ListCursos, self).get_context_data(**kwargs) context['usuarios'] = User.objects.all() context['cursos'] = Course.objects.all() return context -
optimize Django filter
I'm trying to optimize a Django filter. This works, but it runs a whole new query in filters.py to retrieve the set of communities that were already queried in views.py (via the select related function). How do link the query defined in the get_context_data function to the one in the filters.py file without creating a whole new query? views.py class PlatListView(SingleTableMixin,ExportMixin, FilterView): model = Phase template_name = 'blog/filtertable.html' filter_class = PlatFilter def get_context_data(self, **kwargs): context = super(PlatListView, self).get_context_data(**kwargs) query = Plat.objects.all().select_related('community').annotate(number=F('phase__number'),lot_count=F('phase__lot_count'), phaseid=F('phase__id'),using_vert_start_sch=F('phase__use_vertical_start_sch') ) f = PlatFilter(self.request.GET, queryset=query) t = PlatTable(data = f.qs) RequestConfig(self.request).configure(t) context['filter'] = f context['table'] = t return context filters.py class PlatFilter(django_filters.FilterSet): community= ModelChoiceFilter(queryset=Community.objects.all().order_by('community_name')) -
django heroku deployment postgres config
this is my first time deploying a Django app to Heroku I followed the the Django Heroku documentation the app is deployed successfully but when I open the app I got this error : relation "products_category" does not exist LINE 1: ...ory"."image", "products_category"."catogory" FROM "products_... this is the changes I did to my settings.py after reading the documentation : import django_heroku django_heroku.settings(locals()) the database configuration is still running with sqlite3: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } so what do I need to change in my setting to deploy my apps properly ? -
Getting last insert id of the object saved by serializer in Django
I have a visitorSaveSerializer which is responsible for validating the data to be saved: class VisitorSaveSerializer(serializers.ModelSerializer): class Meta: model = Visitor fields = ('gsm', 'email', 'firstname', 'lastname') The problem is: visitor_serializer = VisitorSaveSerializer(data={...related data here...}) if visitor_serializer.is_valid(): visitor_serializer.save() visitor_id = visitor.serializer.data.get("id", 0) // Fails for sure. OK, I know id is not among serializer fields, so last line fails. How should I approach saving an object when I need to get last inserted id? -
AttributeError: 'function' object has no attribute 'as_view',in urls.py
I written this logic in my views.py, and I used class based views, Detail view: @login_required class profileView(DetailView): model = profile template_name = "users/profile.html" and in urls.py file I've written this: from django.urls import path,include from . import views from .views import profileView urlpatterns = [ path('register/',views.register,name="register"), path('login/',views.login_user,name="login_user"), path('profile/',profileView.as_view(),name="profile_view"), ] the django version that I'm using is 3.1 and python version is 3.8. I hope that someone has an answer to my question. -
Getting an object from another thread in Python
I'm using Django Channels to implement a real-time multiplayer game. Inside an engine.py file, I have the following class: class GameEngine(threading.Thread): def __init__(self, group_name, **kwargs): super(GameEngine, self).__init__(daemon=True, name="GameEngine", **kwargs) self.group_name = group_name # other stuff... def run(self): while True: # update game state and broadcast it to channel This is meant to be called by the websocket consumer of the first player who joins a game. It gets passed a channel name (group_game) which allows it to broadcast messages to all players that are connected to the WS entry point corresponding to the channel. The way the GameEngine is initialized is by checking if the player who joined is the first one for the game: class GameConsumer(AsyncWebsocketConsumer): async def connect(self): # Join room group await self.channel_layer.group_add(self.group, self.channel_name) if await self.get_number_of_online_players(game_id) == 1: # if this is the first player self.engine = GameEngine(self.group) self.engine.start() This way, the consumer can then later send messages to the GameEngine by calling its methods directly: self.engine.meth_name(). Problem is, I have no way of accessing the engine from the consumers instantiated by the subsequent players who join the game. I need a way to retrieve that object that was created by the first consumer: how can … -
Html <img> not loading image even tougth they're in tha same directory
my code is like that: <body> <a href = "{% url 'pacientes' %}"> <img src="/aaa.png"/> </a> </body> my question is: Why the fu***** image don't load if the image and the html are in the same directory obs.: i already tried write the img tag out of the 'a' tag, and tried too. this html is part of a django project, idk if this really make difference -
SAML authentication for HUE revoking admin access AFTER first login
I'm trying to set up SAML authentication for HUE deployed with AWS EMR, using Azure SSO as the IdP. I can actually get the handshake to work and the users are logging in to HUE, matching network login details to the usernames that are prepopulated in the HUE backend database. We create the users in HUE first and part of that setup includes setting some users with "is_superuser" to TRUE. The only attribute I explicitly look for to get from the IdP to HUE is the username/network-credential The behaviour I'm trying to understand is that the first person to log into the HUE UI is getting authenticated via SAML and logging in, with the admin/superuser privileges intact. But anyone after that logging in who is set up as an admin is losing the flag to indicate an admin, i.e. logged in as a normal user. If I manually go in afterward and set the users to have admin access in HUE database and have the users log in again, the access will be granted to the admin permissions and the problem seems to disappear but I don't understand why every login after the first is removing these permissions? I tried … -
How can I use instaceof in Django template?
Hello there I have a template that is used by two views in this template a have a toggle for deleting objects and because I have 2 types of objects that can be deleted by the same form I want to verify somehow the instance of the object in orderd to decide which url to use for deleting. How can I write this in django template properly? <form method="POST" action="{% if object instanceof Income %}{% url 'delete-income' object.id %}{% elif object instanceof Spending %}{% url 'delete-spending' object.id %}{% endif %}"> -
Django use values or values_list with non related models
I have this both models: class GeneCombination(models. gene = models.ForeignKey(Gene, db_column='gene', on_delete=models.DO_NOTHING, db_constraint=False) class Gene(models.Model): name = models.CharField(max_length=50, primary_key=True) type = models.CharField(max_length=25) I know it's not the best model schema, it has to be like that due to business rules. I'm getting the values from GeneCombination model and some fields from Gene model. Now, It could be that a gene is not present in Gene model, in that case that rows are being filtered when I use values of values_list methods, which is what I want to prevent. This query is returning 31 elements: GeneCombination.objects.select_related('gene') But this query is returning 27 elements (is filtering the 4 elements whose gene does not exist in Gene table): GeneCombination.objects.select_related('gene').values('gene__type') How could I get empty values in case that It doesn't exist and prevent the rows to be filtered? Thanks in advance and sorry about my English -
Django is unable to find the view used for query params the other views are working perfectly
#urls.py from django.urls import include,path from rest_framework import routers from . import views router=routers.DefaultRouter() router.register(r'banks',views.BanksViewSet) router.register(r'branches',views.BranchesViewSet) router.register(r'branches/autocomplete/',views.BranchAutocompleteViewSet, basename='branches') urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] #views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import BanksSerializer,BranchesSerializer from .models import Banks,Branches class BanksViewSet(viewsets.ModelViewSet): queryset=Banks.objects.all().order_by('id') serializer_class= BanksSerializer class BranchesViewSet(viewsets.ModelViewSet): queryset=Branches.objects.all().order_by('ifsc') serializer_class=BranchesSerializer class BranchAutocompleteViewSet(viewsets.ModelViewSet): serializer_class=BranchesSerializer def get_queryset(self): branchName=self.request.query_params.get("q") limit=self.request.query_params.get("limit") offset=self.request.query_params.get("offset") queryset=Branches.objects.filter(branch__startswith=branchName).order_by('ifsc')[offset:limit] return queryset the BanksViewSet and BranchesViewSet are working fine but the other one is not working the problem might be the basename in urls.py as changing it doesn't do anything even when left as an empty string. this is what the console has: Django version 3.1.5, using settings 'bankApi.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /branches/autocomplete/ [19/Jan/2021 18:30:04] "GET /branches/autocomplete/?q=A&limit=5&offset=0 HTTP/1.1" 404 12148