Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving api secret keys to database django
I want to store api keys to db as the application has subdomains and each subdomain can have individual keys, what I tried is as follows models class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) and in views I call it as follows def get_api_key(): return HttpResponse(ExternalKeys.objects.first().secret, content_type='text/plain') stripe.api_key = get_api_key().content.decode() this prints the key in terminal, but when I send request to stripe, it throws error Invalid API Key provided, how I can make it work, thank you -
JS calling django function
I have 2 html buttons, one that calls a JS function and one that calls a django request. My JS button who's function is to change the background color of a website: function change_background(){ document.body.style.backgroundColor = 'green'; } The JS html button is: <input type="button" value="java" onclick="change_background()")> In the Django backend i have a function the that reads and opens a file in a new window: def opening_function(request): file = open('peterexcel.xlsx', 'rb') response = FileResponse(file) return response The Django html button is: <input type="button" value="excel" onclick="window.open('making_the_excel')"> I want to make one button. What I want to do is change it so that when the JS button is pressed it will run the django function. Currently when the django function is ran a blank window pops up and the file is downloaded. I do not want this blank window to pop up. i want to connect the django file reading functionality to the JS button. Everything I have read says to use AJAX, and that this is not a language but rather a technique. I find the AJAX quite difficult to understand. Can anyone help with this? -
How can I map a django model to a python dataclass
There used to be a project in github that allowed you to map django models to python dataclasses, but it's gone now. You can still check it using the way back machine: https://web.archive.org/web/20201111163327/https://github.com/proofit404/mappers https://web.archive.org/web/20201101163715/https://proofit404.github.io/mappers/ I'm trying to find another way to map django models to python dataclasses, but I can't seem to find any similar projects -
404 media not found Django (the obvious? I know)
Yes, I know a lot of the same questions here, Still... I can't seem to find the right solution, I get the not found page, It's not the first project I work with and it's nothing different in the code, any help will be greatly appreciated, thanks in advance. in urls.py urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' in-browser URL: http://127.0.0.1:8000/media/qrcodes/username/qrcodeimg_msUTRj3.png -
How to integrate offline folium map onto django using maptiler server?
I am new to Django and I have installed mapTiler server on my mac to use it as as map server. I have a django app that has an embedded folium map and I want to host my data locally (offline) through the application: After getting the information from the server [mapTiler server interface][1], I have put this part of code in views.py tilesServer = "http://localhost:3650/api/tiles/2017-07-03_illinois_chicago/{z}/{x}/{y}.png" m = folium.Map(location=[41.85, -87.68], zoom_start=10, tiles=tilesServer,attr="<a href=\"http://www.openmaptiles.org/\" target=\"_blank\">&copy; OpenMapTiles</a> <a href=\"http://www.openstreetmap.org/about/\" target=\"_blank\">&copy; OpenStreetMap contributors</a>") m.add_child(fullscreen) and Then I called it in my template with {{my_map|safe}} the map doesn't load and it displays blank!!! As you can see on this picture [Heatmap][2] where the heatmap and the clusters are shown but not the tiles. Can some help or guide me ? [1]: https://i.stack.imgur.com/9eRWH.png [2]: https://i.stack.imgur.com/P0Sp4.png -
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> -
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? -
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 -
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 …