Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Keycloak - Remove username field from the insert query to client after user registration
Using email as a validation method in Keycloak, do I have an option (maybe with mappers, but I tried) to take away the username field from the insert query is sent to the client after user registration? I could apply a workaround to define a username field in the client side model, but I would like to fix this issue from the keycloak side. Thank you, I appreciate Mariano -
Heroku app: ModuleNotFoundError: No module named 'pwa'
I am trying to deploy my app to heroku and I keep getting this error even though when I run locally it works perfectly fine. I have added django-pwa==1.0.10 to my requirments.txt file also so that heroku installs the package. Here are my installed apps in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pwa', # 'embed_video', 'whitenoise.runserver_nostatic', 'courses.apps.CoursesConfig', 'accounts.apps.AccountsConfig', 'announcements.apps.AnnouncementsConfig', 'students.apps.StudentsConfig', 'home.apps.HomeConfig', 'event_calendar.apps.EventCalendarConfig', ] Here is my directory Not really sure what to do as I am not very experienced with heroku. -
Django migration from Foreign key to Integer field error occured
I'm facing an issue migrating my django models, when converting the foreign key to normal integer field. Here you are my code below. Old migration data type: bank_id = models.ForeignKey(Bank, related_name='bank', on_delete=models.CASCADE, blank=True,null=True) New migration data type: bank = models.IntegerField(default=0, null=True, blank=True) **The error that I got from the migration. return int(value) ValueError: invalid literal for int() with base 10: ''** Any idea, how I can convert the existing data in the table? -
How can I create admin-like look for the whole page in Django?
I am creating small web-application using django, which needs to have 4 different levels of access. I have created models and Admin page does 80% of what I would have expected (for most privileged user which is Admin), and I really like the default admin look of the page. I am unsure whether I should just extend Admin view, but I wish to use the default UI for all users (with small changes like different colors or navbar related to their level of access) - how can I do it? Can I use default templates/views of models and slightly change them/add new ones based on them without simply extending Admin view? I am new to web applications and I am currently stuck. Tl;dr how can I keep default UI for the whole page -
Form can't assign to function call
Flight funtion doesn't return from models in view. I changed models from null=True to nothing. Is the problem within my return code or is it something else? The thing is nothing gives an error other than views which is weird. def add_flight(request): if request.method == 'POST': form = FlightForm(request.POST) if form.is_valid(): a = Flight(departing_date=form.cleaned_data["departing_date"], deptAirport=form.cleaned_data["deptAirport"], arrAirport=form.cleaned_data["arrAirport"], duration=form.cleaned_data["departing_date"], airline=form.cleaned_data["airline"], price=form.cleaned_data["price"], deptCity=form.cleaned_data["deptCity"], arrCity=form.cleaned_data["arrCity"], deptHour=form.cleaned_data["deptHour"], , arrHour=form.cleaned_data["arrHour"]) a.save() #return HttpResponse("Success!") return HttpResponseRedirect('/flights/') else: form = FlightForm() return render(request, 'add_flight.html', {'form': form}) It can't return Flight model from models which looks like this class Flight(models.Model): departing_date = models.CharField(max_length=10) deptAirport = models.CharField(max_length=100) arrAirport = models.CharField(max_length=100) duration = models.CharField(max_length=5) airline = models.CharField(max_length=20) price = models.CharField(max_length=100) deptCity = models.CharField(max_length=100) arrCity = models.CharField(max_length=100) deptHour = models.CharField(max_length=4) arrHour = models.CharField(max_length=4) def __str__(self): return self.departing_date+" "+self.deptAirport+" "+self.arrAirport+" "+self.duration+" "\ +self.airline+" "+self.price+" "+self.deptCity+" "+self.arrCity+" "+self.deptHour+" "+self.arrHour Any suggestions? -
Django do not allow another like is user already liked post
I want to allow an user to be able to like an post only once. Here is my code so far: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.PositiveIntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) In views.py: def LikePostView(request, pk): post = get_object_or_404(Post, pk=pk) post.likes = post.likes+1 post.save() return render(request, 'blog/like_done.html') Code to like a post on frontend: <p class="content">{{ post.likes }} likes</p> {% if user.is_authenticated %} <a href='{% url "like_post" post.id %}'><i class="fa fa-thumbs-up" style="font-size:36px"></i></a> {% else %} <a onclick="alert('In order to like a post, you must be logged in!')" href='{% url "blog-home" %}'><i class="fa fa-thumbs-up" style="font-size:36px"></i></a> {% endif %} And like_done.html: {% extends "blog/base.html" %} {% block content %} <h2 class="alert alert-success">Post Liked Successfuly!</h2> <br> <a class="btn btn-success" href="{% url 'blog-home' %}">Go Back Home?</a> <br> {% endblock content %} So with all this, how would I make the user be allowed to only like a post once. I am only beginner, so please explain a little. -
Update dynamic choices when object is created in Django
I have a few different apps inside of my Django (3.1.1) project. Each of them contains at least one field that shows a dropdown of the objects below it. When I create a lower level object, the drop down lists don't reflect the new object until I stop and then restart the server. I just want to know how I could do this automatically. I've tried to override the save() function (see below), but it hasn't worked. Not sure if I'm doing it wrong, or I need to try something else. Additional (but related) question...how can I make this fix for when objects are deleted, too? Do I need to write in two separate fixes, or is there just one that I can do that will basically handle repopulating the dropdowns any time an object is either created or deleted? Thanks for any help! The code/pseudo code: NOTE: I'm slimming this down for simplicity (I hope). There are many fields in each app, but I'm just going to list the one that pertains to the dropdown. **PAGE APP** page_number = .... .... def save(self, *args, **kwargs): Book.pages = Library.pages = models.CharField(choices=create_pages_choices(), max_length=15, null=True) super(Page, self).save(*args, **kwargs) **BOOK APP** pages = … -
(class_='result_price') that's can be useful anytime?
soup = BeautifulSoup(data, 'html.parser') post_listings = soup.find_all('li', {'class': 'result-row'}) post_title = post_listings[0].find(class_='result-title').text post_url = post_listings[0].find('a').get('href') post_price = post_listings[0].find(class_='result_price').text -
Displaying form errors with Materializecss and Django
I'm using materializecss (django-materializecss-form) to display my forms. <!-- form.hmtl --> {% extends "market/base.html" %} {% block content %} {% load materializecss %} <form method="POST" enctype="multipart/form-data"> <!-- ... --> <div class="row"> {{ form.description|materializecss:'s12, icon=flag' }} {{ form.description.errors }} </div> <div class="row"> <label>Kategorie</label><br/> {{ form.category }} {{ form.category.errors }} </div> <!-- ... --> </form> The description works well. The »categories« are displayed in a grouped select field. Thus, I cannot use the filter |materializecss for this field. Otherwise the grouping would not work. # models.py class SmallAd(models.Model): # ... category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Kategorie') description = models.TextField(verbose_name='Beschreibung') # ... However, the main problem is that the errors ('field must be filled') are not displayed in those grouped select-fields as long as I do not use the materializecss-filter. But I need both the error-messages and the grouping. Has anybody a good idea to solve this? -
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?