Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter objects before deadline
I have a list of jobs. I want to display only the jobs whose deadline of application has not been crossed yet compared to today's date. in my model.py, I have a model for Job. It has a field called job_deadline which is a DateField. How do I get all the jobs which are active? It should be something like Jobs.objects.filter(job_deadline > date.today()). But this does not work -
Saving Model with Generic Relation throws Exception when saving inside transaction atomic
I have this model where i save fees that should billed at a later stage. Since several Models could generate fees I set up a Generic Relation. class Fee(models.Model): content_type = models.ForeignKey(ContentType, blank=True, null=True, related_name='fees', on_delete=models.CASCADE) object_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) content_object = GenericForeignKey() class FeeType(models.IntegerChoices): SALES_CREDIT = 1, 'Sales Credit' MANAGEMENT = 2, 'Management Fee' BROKERAGE = 3, 'Brokerage Fee' PLATFORM = 4, 'Platform Fee' MARKETING = 5, 'Marketing Fee' DISCOUNT = 6, 'Discount' NOFEE = 99, 'No Fee' fee_type = models.IntegerField(choices=FeeType.choices) fee_date = models.DateField(auto_now_add=True) due_date = models.DateField(editable=False) creditor = models.ForeignKey('users.Company', on_delete=models.CASCADE, related_name='fee_credit') debitor = models.ForeignKey('users.Company', on_delete=models.CASCADE, related_name='fee_debit') quantity = models.PositiveBigIntegerField() rate = models.DecimalField(max_digits=10, decimal_places=4) class RateType(models.IntegerChoices): PERCENTAGE = 1, 'Percentage' NOMINAL = 2, 'Nominal' rate_type = models.IntegerField(choices=RateType.choices, default=1) taxes_due = models.BooleanField(default=True) including_taxes = models.BooleanField(default=True) tax_rate = models.DecimalField(max_digits=4, decimal_places=2) total_amount = models.DecimalField(max_digits=12, decimal_places=2, editable=False) total_taxes = models.DecimalField(max_digits=12, decimal_places=2, editable=False) total_amount_incl_taxes = models.DecimalField(max_digits=12, decimal_places=2, editable=False) billed = models.BooleanField(default=False) paid = models.BooleanField(default=False) And I have a function living in a celery task that prepares the data to be saved into said model: @shared_task def log_fee(model, fee_type, creditor_pk, debitor_pk, quantity, rate_type, rate=None, taxes_due=True, including_taxes=True, tax_rate=None, fee_date=None): from fees.models import Fee from users.models import Company logger.info(f'{model} {fee_type} {creditor_pk} {debitor_pk} {quantity} {rate_type} {rate} {taxes_due} … -
What tech stack to use for a project using multiple API I/O processes in background?
I am unable to decide what technology would be better to use for my project. The project has the following purpose. I will be using a 3rd party API service for 2 major purpose Creating, updating, and deleting events. Fetching past changes made. So at any point in time, I can start a new service, that will be creating new events for me by loading data from an excel file and, this service would now be running in the background (also having the functionality to pause/stop the service at any time). Multiple such services of creation from different excel files will run simultaneously in the background. Similar to the above service, I will create a fetch service to fetch data in regular intervals indefinitely and dump that data in an excel file. Again, this service will also run in the background and can be paused/stopped. Multiple such services will also run in the background. Now, for the project, I have 2 questions regarding what Tech Stack I should use. Should I go for a Django based web app or should I go for NodeJs based webapp? If I choose Django, what are the ways I can achieve concurrency and parallelism? … -
Django and Django channels
I have one django project, which uses django channels as well. Now I want to separate django channels into a separate project. Means, one applicaton will have two django projects, Django for http request. (Django http) Django for websocket request. (Django async) But, the problem is, if I separated both of these projects, How django async project will use models?? Note:- I want common database between both projects. -
Como hacer para que el admin de Django me cargue un combo-box , según uno anterior [closed]
Tengo estos modelos en la clase geolocalizacion. @admin.register(DivisionTerritorial) class DivisionTerritorialAdmin(BaseImportExportModelAdmin): """ Administrador modelo DivisionTerritorial """ search_fields = ['nombre'] list_filter = ['municipio', 'tipo_division'] list_display = ['nombre', 'tipo_division', 'municipio', 'fecha_creacion', 'fecha_modificacion', 'fecha_eliminacion'] readonly_fields = [ 'creado_por', 'fecha_creacion', 'ip_creacion', 'modificado_por', 'fecha_modificacion', 'ip_modificacion', 'eliminado_por', 'fecha_eliminacion', 'ip_eliminacion' ] resource_class = DivisionTerritorialResource fieldsets = ( ( None, { 'classes': ('suit-tab suit-tab-general',), 'fields': ( 'nombre', 'tipo_division', 'municipio', 'fecha_creacion', 'fecha_modificacion', 'fecha_eliminacion' ) } ), ) inlines = [BarrioInline,] suit_form_tabs = ( ('general', _('Divisiones territoriales')), ('Barrio', _('Barrio')), ) @admin.register(Barrio) class BarrioAdmin(BaseImportExportModelAdmin): """ Administrador modelo Barrio """ search_fields = ['nombre'] list_filter = ['municipio', 'zona_ubicacion'] suit_list_filter_horizontal = ('municipio', 'zona_ubicacion') list_display = ['nombre', 'municipio', 'division_territorial', 'zona_ubicacion', 'latitud', 'longitud', 'fecha_creacion', 'fecha_modificacion', 'fecha_eliminacion'] fields = ['nombre', 'zona_ubicacion', 'municipio', 'division_territorial', 'latitud', 'longitud', 'fecha_creacion', 'fecha_modificacion','fecha_eliminacion'] readonly_fields = [ 'creado_por', 'fecha_creacion', 'ip_creacion', 'modificado_por', 'fecha_modificacion', 'ip_modificacion', 'eliminado_por', 'fecha_eliminacion', 'ip_eliminacion' ] raw_id_fields = ['municipio'] resource_class = BarrioResource Estan unidos por una Fk y necesito que cuando los llame en otro modelo estos aparezcan segun la fk anterior. enter image description here Entonces necesito que si elijo un Departamento en la siguiente casilla me liste los municipios pertenecientes a ese departamento. Vi en todo lado que se podría realizar con Ajax pero no se como usarlo aquí en el admin, … -
my form sends GET instead of POST, i have created a form which get input and i would like to send it to the database
i asked this question but was not properly asked. i'm working on my e-commerce project using django. i created form which should take input and update it into the database but unfortunately it is not sending any data to the database and although i specified the action to POST but i'm getting GET and POST together in my terminal here is the result i get: [16/Jun/2021 18:09:23] "POST /cart/addcomment/1 HTTP/1.1" 302 0 [16/Jun/2021 18:09:23] "GET /en/cart/addcomment/1 HTTP/1.1" 302 0 URL: /media/product_images/iphone-compare-models-202010_GEO_US_eDOyoqO.jpeg URL: /media/product_images/iphone-compare-models-202010_GEO_US_eDOyoqO.jpeg [16/Jun/2021 18:09:23] "GET /en/cart/shop/iphone-12-pro/? **models.py:** class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50, blank=True) comment = models.CharField(max_length=250, blank=True) rate = models.IntegerField(default=1) ip = models.CharField(max_length=20, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject **views.py:** def addcomment(request, id): url = request.META.get('HTTP_REFERER') # get last url # return HttpResponse(url) if request.method == 'POST': # check post form = CommentForm(request.POST) if form.is_valid(): data = Comment() # create relation with model data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.rate = form.cleaned_data['rate'] data.ip = request.META.get('REMOTE_ADDR') data. product_id = id current_user = request.user data.user_id = current_user.id data.save() # save data to table … -
How i can create a delete button in django python?
I'm new to Django and i try my best to resolve this problem. So i try to create a delete button on my template. I create my view and i create my url but it doesn't work. So here my views : def book_delete(request, pk): book = get_object_or_404(Book, pk=pk) if request.method == 'POST': book.delete() return redirect('/') return render(request, "livre/newbook_form.html", {'form': book}) My urls from . import views from django.conf.urls import url urlpatterns = [ url(r'^livre/(?P<pk>[0-9]+)/$', views.book_delete, name='book_delete') ] My template <form action="liste" method="POST">{% csrf_token %} <table> <th>Titre</th><th>Auteur</th><th>Nombre de pages</th><th>Supprimer</th> {% for Book in Book %} <tr> <td>{{ Book.title }}</td> <td>{{ Book.author }}</td> <td>{{ Book.num_pages }}</td> <td> <form action="{% url 'book_delete' Book.id %}" method="POST"> {% csrf_token %} <input type="button" value="{{Book.id}}"/> </form> </td> </tr> {% endfor %} </table> </form> I don't know why it doesn't work. Can you help me ? -
Alguna de convertir estas querys a json? [closed]
estoy buscando alguna manera de hacer que mi codigo al momento de enviar un "GET" con postman me devuelva algunas querys que tengo en la BD pero en forma de archivo json, Alguna idea? Muchas gracias! dejo parte del codigo... import json from typing import Container from website.serializer import ProductoSerializer from django.http import HttpResponse from django.core.serializers import serialize from django.shortcuts import render from django.http.response import HttpResponseRedirect, HttpResponse, JsonResponse from django.views.generic import CreateView, UpdateView, DeleteView, ListView, TemplateView from django.urls import reverse_lazy from .models import Cliente, Producto from django import forms from django.views import generic from rest_framework.parsers import JSONParser from django.views.decorators.csrf import csrf_exempt from rest_framework import status from django.core.serializers import serialize # Create your views here. def home(request): return render(request, 'website/home.html') def clientes(request): return render(request, 'website/clientes.html') # vista instrumentos def producto(request): return render(request, 'website/producto.html') def otros(request): return render(request, 'website/otros.html') class ClienteCreate(CreateView): model = Cliente #form_class = clientes fields = '__all__' template_name = 'website/cliente_form.html' success_url = reverse_lazy('clientes_list') class ClienteUpdate(UpdateView): model = Cliente #fields = ['nombre','telefono','email','direccion','usuario','contrasenia'] fields = '__all__' success_url = reverse_lazy('clientes_list') class ClienteDelete(DeleteView): model = Cliente success_url = reverse_lazy('clientes_list') class ClienteDetailView(generic.DetailView): model = Cliente class ClienteListView(generic.ListView): model = Cliente template_name = 'website/clientes_list.html' #Producto CRUD class ProductoCreate(CreateView): model = Producto fields = '__all__' template_name … -
disabling/enabling a field in Django form depending on a value of another field in the same form
Asking a beginner's question. I have a ModelForm object with a quite large number of fields. I want some of these fields to assume to be editable or not editable, based on a value of some other field (in the same form): For example: split_words = forms.BooleanField() split_words_min_length = forms.IntegerField(min_value=1,max_value=140) I would like split_words_min_length field to be disabled (or not displayed), if split_words is set to False (unchecked). What would be a clean way how to achieve this? -
Displaying one value and sending another to backend with HTML <select> and <option> tags
I'm making a note-taking web app. The rich text editor includes a drop-down menu containing the names of each of the user's notebooks, so that the user can choose where the note will go. So far so good. The problem is that, in theory, the user could name two notebooks the same thing. So when the user chooses a notebook, the frontend ultimately needs to send the ID slug associated with that specific notebook to the backend, so that Django can choose which notebook to associate the note with without ambiguity. The problem is that I don't know how to make the HTML <select> and <option> tags do what I want them to. I tried putting in one value between the HTML tags (so that it's displayed) and passing the ID as the tag's value attribute, but this doesn't seem to work: setNotebooks(notebookList.map(item => { return ( <option value={item.notebook_id}> {item.name} </option> ); When I set notebooks in the way I showed above, it comes back as undefined. In the example, notebookList is an array of objects containing each notebook's attributes. I tried wrapping each <option> tag in the <select> one in a higher-order component with its own state that would … -
Django static files not working for other templates except index
I am developing an agency web app with django templates & static files. But I am having trouble with loading static files on pages other than index. Here's my folder heirarchy. Again, I am having no problems loading static files on my index page. Here's code of my additional page services.html (one I am trying to load static files on): {% extends 'base.html' %} {% load static %} {% block content %} ... ... ... {% endblock %} My base.html is working totally fine with the homepage index.html. I've included this on my settings.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') And, my views.py and urls.py files are working fine too. Also my CSS file is correctly linked to the services.html file. I can tell this from the inspection. Here's the error list shown on inspection. Help will be appreciated. Thank you. -
Django ORM - INNER JOIN to a GROUP BY subquery on the same table
I've got a table that looks something like this (I've omitted some columns): ID Key_ID Project_ID other columns 1 1 123456 a 2 1 123456 b 3 2 123456 c 4 2 123456 d 5 3 654321 e 6 3 654321 f 7 4 654321 g 8 4 654321 h Using Django ORM, I would need to get the equivalent of this query: SELECT * FROM table AS t INNER JOIN ( SELECT MAX(ID) AS max_ID FROM table GROUP BY Key_ID WHERE Proeject_ID = 123456 ) AS sub_query ON t.ID = sub_query.max_ID I've tried some aggregate and annotate combinations but I don't seem to be able to achieve the GROUP BY in the subquery. If I could do that I could then try to use a .filter(id__in=<subuery_result> so effectively use a SELECT ... WHERE ID IN <subquery_result although the INNER JOIN would be ideal as the subquery result could be quite large. -
Is it possible to use lambda layers with zappa?
I want to deploy my wagtail (which is a CMS based on django) project onto an AWS lambda function. The best option seems to be using zappa. Wagtail needs opencv installed to support all the features. As you might know, just running pip install opencv-python is not enough because opencv needs some os level packages to be installed. So before running pip install opencv-python one has to install some packages on the Amazon Linux in which the lambda environment is running. (yum install ...) The only solution that came to my mind is using lambda layers to properly install opencv. But I'm not sure whether it's possible to use lambda layers with projects deployed by zappa. Any kind of help and sharing experiences would be really appreciated! -
After running the server in django, I am getting the KeyError: 'django'
I am not fluent in Django,been doing for over 3 months now, BUT I have never seen such error. Please if someone can help me out of this situation. I am doing the short_url module, bt befoe that i have pip installed shorturls , then i created an app shorturls. Again , i have to delte the app shorturls. And after that i have been facing this issue. Following is my full traceback of the error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\backends\django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\shorturls\templatetags\shorturl.py", line 5, in <module> from django.core import urlresolvers ImportError: cannot import name 'urlresolvers' from 'django.core' (C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
Download page as JSON in Django
I have a view which returns a formatted JSON object. It takes a list of words (labeled "forms" and "lemmas" for this project), formats them into a nice dictionary object and outputs a json page which can then be saved by the user. views.py def search_view(request): """ The app revolves around this view, which is also the homepage. """ context = {} if request.method == 'GET': return render(request, 'search.html', context) if request.method == 'POST': checked_A = {} checked_B = {} # All lemma keys are of the form {lemma}@{group}. # All form keys are of the form {lemma}@{group}@{form}. # The "@" symbol will not appear in any other key. # Split the key_data into two parts, the lemma/group part # and the form part. The form part is either [] or [form] for key in request.POST: if "@" not in key: continue key_data = key.split("@") (lemma, group), form = key_data[:2], key_data[2:] if group == "A": if checked_A.get(lemma): checked_A[lemma].extend(form) else: checked_A[lemma] = list(form) if group == "B": if checked_B.get(lemma): checked_B[lemma].extend(form) else: checked_B[lemma] = list(form) context['query_A'] = checked_A context['query_B'] = checked_B return JsonResponse(context, status=200) # <-- the only important part Is there a way to create a button which will download this … -
TypeError at / can only concatenate str (not "builtin_function_or_method") to str
Thank you for your time. I was working on django rest framework documentation, and only with Localhost "http://127.0.0.1:8000/" URL I get this error. TypeError at / can only concatenate str (not "builtin_function_or_method") to str I have attached Views.py, snippets/url.py and snippets/serializers.py views.py from snippets.permissions import IsOwnerOrReadOnly from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from rest_framework import generics, permissions from django.contrib.auth.models import User from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import renderers from rest_framework.reverse import reverse @api_view(['GET'] def api_root(request, fromat=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'snippets': reverse('snippet-list', request=request, format=format) }) class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = [renderers.StaticHTMLRenderer] def get(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(owner=self.request.user) class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer snippets/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = format_suffix_patterns([ path('', views.api_root), path('snippets/', views.SnippetList.as_view(), name='snippet-list'), path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'), path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet- highlight'), path('users/', views.UserList.as_view(), name='user-list'), path('users/<int:pk>/', views.UserDetail.as_view(), name='user-detail') ]) serializer.py from rest_framework import serializer from snippets.models import Snippet, … -
Radio buttons written with Django templates are not displayed
I am learning Django from documentation. I'm on part 4. There is a code like this (detail.html): <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form> Here are views.py: from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.shortcuts import render, get_object_or_404 from django.http import Http404 from django.urls import reverse from .models import Question, Choice def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) Everything is displayed except for the radiobutton. How to fix it? Python 3.6.3 Django 3.2.4 -
Django file upload : TypeError: a bytes-like object is required, not 'TemporaryUploadedFile'
I want to make a post create view. There are various functions to write an article, and there is a file upload function in particular. So, I use Multipartparser and override create function in serializer. like below: create instance first. save the file on the created instance. but when I save, the error occur: TypeError: a bytes-like object is required, not 'TemporaryUploadedFile' but don't know how to convert 'TemporaryUploadedFile' to 'a bytes-like object'. api_view> class PostCreate(generics.CreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer parser_classes = (MultiPartParser,) def post(self, request, *args, **kwargs): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer> class PostSerializer(serializers.ModelSerializer): post_files = serializers.FileField(required=False) def create(self, request): print("@@@@@request") print(request) post_files = request.pop("post_files") print("@@@ post_files.path : " + post_files.temporary_file_path()) print("@@@ post_files.name : " + str(post_files)) instance = Post.objects.create(**request) instance.post_files.save(str(post_files), ContentFile(files), save=True) return instance -
How to format date and time in Django?
I am trying to record the creation time, date of input data into a sqllite in Django in the format Jan 1, 2021, 8:21 a.m. So far I can get the time to work doing the following in models.py: class Listing(models.Model): time = models.TimeField(auto_now_add=True) def __str__(self): return f"({ ({self.time}))" with my html: {% block body %} <div> <p> Started: {{listing.time}}</p> </div> {% endblock %} I've tried to add this to the models.py date = models.DateField() But then I get an error when I try to migrate: listing without a default; we can't do that (the datatabase needs something to populate existing rows). I've tried to populate the datefield with a number, and now anytime I migrate I get stuck with this error: TypeError: expected string or bytes-like object Thanks for your help -
Django - CSS not styling HTML page
I am creating a simple dashboard page for my Django web application. I have a simple HTML file, but it is not getting styled by my CSS file. I have {% load static %} at the top of my HTML file and link the 2 files with this code: <link rel="stylesheet" href="{% static 'dashboardstyles.css' %}"> Can someone please help me resolve this problem? I have included the HTML and CSS code below. Thank you! HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GoodDeed - Dashboard</title> <link rel="stylesheet" href="{% static 'dashboardstyles.css' %}"> </head> <body> <!-- end row --> <div class="frame"> <div class="center"> <div class="profile"> <div class="image"> <div class="circle-1"></div> <div class="circle-2"></div> <img src="https://images-na.ssl-images-amazon.com/images/I/51e6kpkyuIL._AC_SL1200_.jpg" width="70" height="70" alt="Image"> </div> <div class="name">{{ user.get_full_name }}</div> <div class="job"> {{ user.get_username }}</div> <div class="actions"> <button class="btn">Events</button> <button class="btn">News</button> </div> </div> <!--Add points and stuff later--> <div class="stats"> <div class="box"> <span class="value">0</span> <span class="parameter">Points</span> </div> <div class="box"> <span class="value">0</span> <span class="parameter">Donations</span> </div> <div class="box"> <span class="value">0</span> <span class="parameter">People Helped</span> </div> </div> </div> </div> </body> </html> CSS: @import url(https://fonts.googleapis.com/css?family=Open+Sans:600,300); body{ background:#DCDCDC; } .frame { position: absolute; top: 50%; left: 50%; width: 400px; height: 400px; margin-top: -200px; margin-left: -200px; border-radius: … -
Migrating content down a level in wagtail streamfield
I've got a wagtail page model with an existing streamfield. The streamfield has now changed format and I'd like the text content to migrated down a level into a streamblock. The initial model (simplified): class ProjectPage(Page): description = StreamField( [ ("text", blocks.RichTextBlock()), ("image", ImageBlock()), ] ) The new model (also simplified): class ProjectPage(Page): description = StreamField( [ ( "section", blocks.StreamBlock( [ ("text", blocks.RichTextBlock()), ("image", ImageBlock()), ] ), ) ], ) Currently, the image blocks are empty, so only the text item needs migrating. I tried looping through pages and doing old_data = page.description.raw_data then using that to make the new content [{'type': 'section', 'value': old_data}]. If I page.save() and get the value for page.description.raw_data, I see the new content, but the admin still shows the old values. I'm guessing this is linked to revisions vs published versions but I can't figure out how to fix this. Any pointers would be welcome! -
Saving a Base64 string representing an image on Django database
I'm fairly new to Django and I'm looking for the best way to store Base64 images on my Dajango db/server. My goal is to be able to send batches of images through http request, therefore it would make sense to send them as encoded Base64 images, I may end up rendering them on a webpage but they will primarily be sent to a desktop application in batches. After looking through several other posts it looks like there are three approaches and I'm not sure what best fits my needs. Store Base64 string in model TextField Store Base64 string in FileField Store an image in an image field and convert it to Base64 when needed My concern with option 1 is that storing large textfields in the db will hinder performance, however like I said I'm new so I really don't have any idea. Option 2 seems to make sense to me as this is similar to how django handles images, by storing them else and just referencing the location in the db. However, I'm not sure if this is simply because sqlite does not support fields of this type. I also see the potential for additional overhead, having to open … -
django model many to many not working with charfield as primary key
I'm trying to accomplish a many to many relationship between my models where one table has a charfield as a primary key. The manage.py makemigrations works just fine, but running manage.py migrate crashes with: django.db.utils.OperationalError: (3780, "Referencing column 'articleCategory_id' and referenced column 'ArticleCategory_id' in foreign key constraint 'item_overview_articl_articleCategory_id_da76142b_fk_item_over' are incompatible.") Here is model 1: class Advertisement(models.Model): advertisement_id = models.IntegerField(primary_key=True) advertisement_startDate = models.DateTimeField() advertisement_endDate = models.DateTimeField() advertisement_isDefault = models.BooleanField() advertisement_image = models.ImageField(upload_to='banners/') advertisement_categories = models.ManyToManyField(ArticleCategory, related_name='ArticleAdvertisements') and model 2 class ArticleCategory(models.Model): ArticleCategory_id = models.CharField(primary_key=True, max_length=10) ArticleCategory_value = models.CharField(max_length=50) ArticleCategory_parent = models.ForeignKey("self", on_delete=models.PROTECT, null=True) ArticleCategory_type = models.ForeignKey(ArticleType, on_delete=models.PROTECT, null=False) Thanks in advance for the help! I've been stuck in this for way to long now :) -
Django listing matching query does not exist, but the page renders correctly and error displays only in terminal
I'm having a problem with Django models. I'm trying to compare value(price) stored in a listing model, but I can't because it is recognized as None, but it clearly displays on webpage with no errors. models.py: class listing(models.Model): Title = models.CharField(max_length=50) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) Description = models.CharField(max_length=300) price = models.DecimalField(max_digits=6, null=True, decimal_places=2) category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories") def __str__(self): return f"{self.Title}" views.py: def listing_page(request, listing_id): item=listing.objects.get(Title=listing_id) (Here terminal throws error: auctions.models.listing.DoesNotExist) price=item.price bids=bid.objects.filter(listing=item) form=bidForm(request.POST or None) if request.method == "POST": if form.is_valid(): if price < form: instance = form.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect(reverse('index')) return render(request, "auctions/listing.html", {"listing":item, "form":form, "bids":bids}) Full error Traceback: Internal Server Error: /favicon.ico Traceback (most recent call last): File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\levan\Downloads\commerce (2)\commerce\auctions\views.py", line 39, in listing_page item=listing.objects.get(Title=listing_id) File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( auctions.models.listing.DoesNotExist: listing matching query does not exist. Help would be greatly appreciated :) -
Django exporting datetime to cvs file
I am rendering a queryset to a template and csv. models.One2OneInfoLog.objects.filter(one_2_one_info=pk).values_list(Lower('name'), 'location', 'created').order_by('created') in the template view I get a created value: 16-06-2021, 10:58 in cvs file I get: 2021-06-16 08:58:27.780570+00:00 It seems its writing the timestamp in the csv file by deducting 2 hours. Is their some way to correct it? And can I change the formatting to match the template view.