Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter Issue Many to Many
I am having a problem where my chained filter using many to many lookups are not performing as I expected. Here are the pertinent details: views.py def cs_edit_result(request, ctype=None, survey_id=None): #if POST request resume answering survey answers from a selected customer survey. if request.method == 'GET': sid = Survey.objects.get(pk=survey_id) if request.method == 'POST': sid = Survey.objects.get(pk=survey_id) form = CustomerSurveyForm(request.POST, instance=sid) #filter placeholders to only form data from customer survey: if form.is_valid(): cs_result = form.save() answers = SurveyAnswers.objects.filter(surveyid=sid.id) for x in answers: x.status=False x.save() print(form) citype = form.cleaned_data['institution_type'] cproducts = form.cleaned_data['products'] cpurchases = form.cleaned_data['purchase'] cservices = form.cleaned_data['services'] colb = form.cleaned_data['olb_vendor'] cph1 = SurveyAnswers.objects.filter(surveyid=cs_result).filter( Q(placeholder__purchase__in=cpurchases), Q(placeholder__institution_type__in=citype), Q(placeholder__olb_vendor__in=colb), models.py class PlaceHolder(models.Model): output_choices = [ ('link','Link'), ('plain text', 'Plain Text'), ('html', 'HTML') ] purchase = models.ManyToManyField(Purchase, related_name='purchase_place') institution_type = models.ManyToManyField(InstitutionType, related_name='itype_place') products = models.ManyToManyField(Product,blank=True, related_name='products_place') services = models.ManyToManyField(Service,blank=True, related_name='services_place') olb_vendor = models.ManyToManyField(OLB_Vendor,blank=True, related_name='olb_place') output_type = models.ManyToManyField(Output_Type) question = models.TextField(null=True, verbose_name = 'question/title') silvercloud_placeholder = models.CharField(max_length=50) output_type = models.CharField( max_length=100, choices= output_choices, default='Plain Text') answer = models.TextField(blank=True,null=True, verbose_name='url/answer') def __str__(self): return self.silvercloud_placeholder class Survey(models.Model): customer = models.CharField(max_length=50) purchase = models.ManyToManyField(Purchase) institution_type = models.ManyToManyField(InstitutionType) products = models.ManyToManyField(Product) services = models.ManyToManyField(Service,blank=True) olb_vendor = models.ManyToManyField(OLB_Vendor) def __str__(self): return ('{} Survey {}'.format(self.customer, str(self.id))) class SurveyAnswers(models.Model): #contributor = admin. surveyid … -
Django UniqueConstraint to check if value is unique in model property
I have two models: Header and TroopsType, which is used in OneToOneField in Header. What I am trying to achieve is to check if Header's name is unique, but not only in Header's name field, but also in TroopsType's one. That's because if you choose some value in troops_type, then name field is not required and it should, so to speak, inherit that name from TroopsType object to not duplicate values by copying it. Of course, if you keep troops_type NULL, then Header's name is required. How would you do so? To clearify my train of thought, I attach my current code which I am trying to modify - currently I just copy the name. models.py: class TroopsType(models.Model): name = models.CharField(max_length=32, unique=True) unit = models.ForeignKey(Unit, on_delete=models.RESTRICT) def __str__(self): return self.name class Header(models.Model): name = models.CharField(max_length=32, blank=True, unique=True) troops_type = models.OneToOneField( TroopsType, on_delete=models.CASCADE, blank=True, null=True ) data_type = models.ManyToManyField(DataType) class Meta: constraints = [ models.CheckConstraint( check=(~models.Q(name="")), name="%(app_label)s_%(class)s_required_name", ), ] def __str__(self): return self.name admin.py: class HeaderAdminForm(forms.ModelForm): class Meta: model = Header fields = "__all__" def clean(self): troops_type = self.cleaned_data["troops_type"] if troops_type: self.cleaned_data["name"] = troops_type.name elif not self.cleaned_data["name"]: raise forms.ValidationError("No name or troops type.") super().clean() @admin.register(Header) class HeaderAdmin(admin.ModelAdmin): form = HeaderAdminForm -
django-crispy-forms with jinja2 FormHelper support
This an expansion on an old question that does not fully answer my question (django crispy forms with jinja2). I am using django-crispy-forms with jinja2 and have already figured out how to get these two to work together using the answer provided in that link. What you lose when doing that is all support for FormHelper and Layout. Has anybody figured out a way to get this functionality with Jinja2? -
IntegrityError at /quizmaker/ (1048, "Column 'id_id' cannot be null")
I am trying to make quiz making application, since am new to django am unable to build the logic for saving foreign key field in database table. Someone please help me for the same. models.py In models.py , class quiztitle is for title of the quiz and id(foreign key,User model) of user who created that quiz. class question is for question along with 4 options and the correct answer. Quizid(foreign key,quiztitle model) and id(foreign key,User model) class answer is for the answer submitted by user who take the quiz. from django.db import models from django.contrib.auth.models import User class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) id= models.ForeignKey(User, on_delete=models.CASCADE) class question(models.Model): Qid = models.AutoField(primary_key=True) id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.ForeignKey(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] views.py from django.shortcuts import render,redirect,HttpResponseRedirect from .models import question ,quiztitle from django.contrib import messages from django.contrib.auth import … -
Django Annotation Aggregation Speed
I'm using the following annotation to generate a count of related objects in a database: challenges = Challenge.objects.annotate( solve_count=Count('solves', filter=Q(solves__correct=True)), unlock_time_surpassed=Case( When(release_time__lte=timezone.now(), then=Value(True)), default=Value(False), output_field=models.BooleanField(), ), votes_positive=Count("votes", filter=Q(votes__positive=True), distinct=True), votes_negative=Count("votes", filter=Q(votes__positive=False), distinct=True), ) The query this generates takes around 2000ms to execute with 1000 Challenges and 1 million Solves. if I replace solve_count=Count('solves', filter=Q(solves__correct=True)), with solve_count=Value(0, output_field=models.IntegerField()), the time spent on queries goes from 2000ms to 50ms (but obviously the solve count is lost in the process) Is there anything I can do to increase the performance of the Count operation? -
Can't database cache be used in django celery?
I know that a typical memory base cache is not available in the celery. But can't we also use database cache? And When I use DatabaseCache in tasks, cache value not stored in database, but that the code run normally. Is memory cache used instead of database cache by force? -
My django login form isn't working, says 'request' has no atrribute 'method'
When I try to login on my django site, I get this error: AttributeError at /login/ 'User' object has no attribute 'method' What is the problem? I'm fairly sure it was working yesterday, and now it isn't. This is my login view: from django import forms from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect class LoginForm (forms.Form): username = forms.CharField() password = forms.CharField() def login (request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): # username = request.POST['username'] # password = request.POST['password'] username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(user) return redirect ("/login/success") form = LoginForm(request.POST) else: form = LoginForm(request.POST) return render (request, 'login.html', {'form':form}) -
how can use Yes, No filter in django
In template when i select any category it just show the last category which i added. After select any category it should show the that category but it show last added category by default Template {% block content %} <label> <select name="SelectCategory" > <option disabled="disabled" value="True" selected="{{ selectedCategory|yesno:"yeah, no, maybe" }}"> Select Category</option> {% for category in categories %} <option value="{{ category.id }}" selected="{% if category.id == selectedCategory %} {% endif %}"> {{ category.name }} </option> {% endfor %} </select> </label> {% endblock %} -
UpdateView that creates or increments existing instance
I have a model that keeps track how much items have been "bought" at a certain value. For example, one could think of items as stocks, value as the price they have been bought at. class Inventory(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() value = models.PositiveIntegerField() class Meta: db_table = 'app_version' constraints = [ models.UniqueConstraint(fields=['item', 'value'], name='unique valued items') ] Now, I'm trying to write a class-based Create/UpdateView in which one simply declares which item has been bought at what price. Then, the view should either create a new instance or increment an existing instance's quantity. I already figured out that an UpdateView might be the best start as I can overwrite the get_object method to have this "create or update" behaviour. However, I'm not sure how to do the incrementing. Perhaps I'm also completely on the wrong track and there is a much simpler solution I am missing here. It would be great to get some ideas and input on how to approach this problem. Thank you so much! -
Just getting the status code but not the data, but in postman it does
I want to send an error message through data when some errors occurs in API, here is the API code: @api_view(['GET']) def RespuestaListView(request, idQuestion): try: question = Question.objects.get(pk=idQuestion) except Question.DoesNotExist: return Response(data={'error': 'That question does not exist'}, status=status.HTTP_404_NOT_FOUND) try: answers= Answer.objects.filter(question=question).select_related() except: return Response(data={'error': 'It can't be done'}, status=status.HTTP_409_CONFLICT) if (answers.count() == 0): return Response(data={'error': 'There is no answers for that questions'}, status=status.HTTP_204_NO_CONTENT) res = [] for answers in answers: res.append(AnswerSerializer(answer).data) return Response(data=res, status=status.HTTP_200_OK) If I call this from postman, it receives the error messages in data: Please ignore the spanish call But when I try to do it from a function in reactjs, when one of the handled errors occurs it just does not work, and I just get the status code. -
How to make a GraphQL api request from Django application?
I would like to know how to retreive data using the GraphQl api service and NOT to create the API. -
I am unable to fetch partial data from related table in django
One order have many order items and if i exclude one of its order items, then it will exclude all other order items of that order id. Can somebody please tell me why? Here is order-id = 8056313100 and two order-items that have ids = 8056313101, 8056313102. Here is View.py order = Order.objects.distinct().filter(orderitem__status=request.data['status']).exclude(orderitem__order_item_id=8056313102) serializer = ListOrderSerializer(order, many=True) return Response(serializer.data) Serializer.py class ListOrderSerializer(serializers.ModelSerializer): order_items = ListOrderItemSerializer(many=True, read_only=True) class Meta: model = Order exclude = ('id',) Order-item-id = 8056313101 will also exclude. Please help me. -
Spyne/Django: Add reversed OneToOne field to response
I'm looking to make use of spyne + django to provide a soap api. In django I have two related models with a one to one relation between them. # models.py class MainThing(): number = models.CharField(max_length=32) # plus other CharFields here class RelatedThing(): number = models.CharField(max_length=32) main = models.OneToOneField('MainThing', on_delete=models.CASCADE) I then have a "service" that connects spyne to django: # service.py from .models import MainThing as MainThingModel class MainThing(DjangoComplexModel): class Attributes(DjangoComplexModel.Attributes): django_model = MainThingModel class MainThingService(DjangoService): @rpc(primitive.String, _returns=MainThing) def retrieveThing(ctx, number): return MainThingModel.objects.get(number=number) api = Application(services=[MainThingService], tns='http://a.tns.com/', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) Calling retrieveThing will give a response that includes all the fields from MainThing, but not the OneToOne from RelatedThing. I would like to include the "relatedthing" number in the retrieveThing response. Is there a way to do this? -
Getting None type value from ManytoMany Field in django rest framework
I cannot retrieve answer choice id in ManytoMany field in serializers list or retrieve instead I got quiz.Choice.None and I understand why is that, but if I remove answer = serializers.CharField() this line from serializer. It raised an error when creating Question: { "answer": [ "Incorrect type. Expected pk value, received str." ] } I cannot pass answer from frontend, I expected to retrieve "answer": [2,3] instead of None and I also know that if I remove answer = serializers.CharField() this line from serializer. It solves the problem, But it raises another problem that I cannot pass an answer choice id that is not even created yet. What is the best solution for this type of problem? I also tried answer validations to an empty array. But that's not working even. { "id": 5, "label": "Question 1", "answer": "quiz.Choice.None", "explanation": "New Added fhfd", "mode": 1, "subtopic": 2, "choice": [ { "id": 5, "option": "option 6 Edited New One", "question": 5 }, { "id": 6, "option": "option 5 Hllloo Sakib", "question": 5 } ] } My Model: # Question Mode MODE = ((0, "Easy"), (1, "Medium"), (2, "Hard")) class Question(models.Model): """Question Model""" label = models.CharField(max_length=1024) answer = models.ManyToManyField("Choice", related_name="quesans", blank=True) explanation … -
AttributeError: 'MovieSerializer' object has no attribute 'id' + Serialization
The perfect scenario would be to use the RatingSerializer inside the MovieSerializer but since it is below the actual mvserializer code, i cannot use it. Therefore, I started to serialize the rating object using json.dumps() and it looks very ugly after serialization. serializers.py class MovieSerializer(serializers.ModelSerializer): id = 15414 director = PersonSerializer() rating = serializers.SerializerMethodField() # I want to use here RatingSerializer() def get_rating(self, obj): r = list(Rating.objects.filter(movie_id=self.id).values())[0] r['rating'] = float(r['rating']) return json.dumps(r) class Meta: model = Movie fields = ['id', 'title', 'director', 'rating'] class RatingSerializer(serializers.ModelSerializer): movie = MovieSerializer() class Meta: model = Rating fields = ['id', 'movie', 'rating', 'votes'] result, the rating field is serialized very bad { "id": 16906, "title": "Frivolinas", "director": { "id": 2014, "name": "Iron Eyes Cody", "birth": 1907 }, "rating": "{\"id\": 1, \"movie_id\": 15414, \"rating\": 5.4, \"votes\": 12}" }, is there a way I can use RatingSerializer inside MovieSerializer? Doing this way (my way), i also cannot find the actual id in the get_rating method, i have hard coded it. -
geopy returning "Civitas Vaticana" string instead of actual city name in django
I am using geopy in django. here I am printing this dictionary from geopy and I need only city name from this dictionary: {'city': 'Singapore', 'continent_code': 'AS', 'continent_name': 'Asia', 'country_code': 'SG', 'country_name': 'Singapore', 'dma_code': None, 'is_in_european_union': False, 'latitude': 1.3024, 'longitude': 103.7857, 'postal_code': '13', 'region': None, 'time_zone': 'Asia/Singapore'} here is my code for getting city name: #views.py from geopy import Photon from .utils import get_geo def calculate_distance_view(request): distance = None destination = None obj = get_object_or_404(Measurement, id=1) form = MesurementModelForm(request.POST or None) geolocator = Photon(user_agent='measurements') ip = '185.252.221.75' country,city,lat,lon = get_geo(ip) print('location country', country) print('location city', city) print('location lat, lan ', lat,lon) location = geolocator.geocode(city) print("###",location) result I am getting: location country {'country_code': 'SG', 'country_name': 'Singapore'} location city {'city': 'Singapore', 'continent_code': 'AS', 'continent_name': 'Asia', 'country_code': 'SG', 'country_name': 'Singapore', 'dma_code': None, 'is_in_european_union': False, 'latitude': 1.3024, 'longitude': 103.7857, 'postal_code': '13', 'region': None, 'time_zone': 'Asia/Singapore'} location lat, lan 1.3024 103.7857 ### Civitas Vaticana why I am getting "Civitas Vaticana" as city name instead of Singapore. I am not seeing any kind of string like "Civitas Vaticana" in my city dictionary. how to get city name? anyone please help -
How to send data through a form for processing and prevent the page from refreshing?
I am working on my first django project and I encountered a problem that I have no idea how to solve it. I have tried various code samples but unsuccessfully. I got stuck with the following problem: I have a form which looks like the following: <form action="{% url 'cart-add' %}" method="GET" id="myform"> {% csrf_token %} <label> <input type="hidden" name="{{ product.pk }}"> <input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1"> <button type="submit" value="">Add to chart</button> </label> </form> When I hit the submit button, the handler, by default, throw me to the cart page, where data is being proccessed. For a better user experience, I want when somebody click "add to cart" button, to not be thrown to another page. For this, I have tried several JQuery and javascript code snippets that I found on internet. It is still not working properly. $(document).ready(function () { $('#myform').on('submit', function (e) { e.preventDefault(); $.ajax({ url: "https://localhost:8080/product_details/" + {{product.pk}}, type: "GET", data: $(this).serialize(), success: function (data) { $("#myform").html(data); }, error: function (jXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); }); The above code is the final result, but it is still not working. NOTE: When I look into page source on browser, the following script … -
How to make id (primary key) of new created objects start from some value?
I have an existing django model in my project, and it's already in production database (PostgreSQL) and has records in it. And what I basically want is to set id (autoincrement pk) of new created objects to have at least 5 digits and start from 5. So for example if I have last record in database with id 1924 I want my next object to have id 51925 (last id + 1 + 50000). So it will be like this: older objects ... 1921 1922 1923 1924 # last in production 51925 # next object to be created must autoincrement from 50001 + previous id 51926 51927 .... and so on Is it possible and what is the best way to do it? thanks -
Uploading an Image returns 400 error using an Django api
I'm trying to upload an image from using fetch after I appended it to formdata const fd = new FormData(); fd.append("image", this.state.offerimg); console.log(fb) const requestOptions = { method: "POST", headers: { "Content-Type": "multipart/form-data", }, body: fd, }; FormData console log Django api: Im trying to store it in firebase storage and Im receiving a bad request, also I'm trying to print the file and its not printing. class AddOfferView(APIView): parser_classes = (MultiPartParser, FormParser,) permission_classes = [AllowAny] def post(self, request): image = request.FILES['image'] print(image) image = storage.child("images/image.PNG" ).put(image) return Response({'userDoc': image}, status=status.HTTP_200_OK) System check identified no issues (0 silenced). April 07, 2021 - 16:30:25 Django version 3.1.7, using settings 'loyalty_app_cms.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Bad Request: /api/add-offer [07/Apr/2021 16:30:34] "POST /api/add-offer HTTP/1.1" 400 104 [07/Apr/2021 16:40:11] "GET /add-products HTTP/1.1" 200 3032 [07/Apr/2021 16:40:11] "GET /static/js/2.2a4e2c0c.chunk.js HTTP/1.1" 304 0 [07/Apr/2021 16:40:11] "GET /static/css/main.22590eba.chunk.css HTTP/1.1" 304 0 [07/Apr/2021 16:40:11] "GET /static/js/main.7dc050bc.chunk.js HTTP/1.1" 304 0 [07/Apr/2021 16:40:13] "GET /manifest.json HTTP/1.1" 200 3032 [07/Apr/2021 16:40:14] "GET /static/css/main.22590eba.chunk.css.map HTTP/1.1" 200 2437 [07/Apr/2021 16:40:14] "GET /static/js/main.7dc050bc.chunk.js.map HTTP/1.1" 200 57177 [07/Apr/2021 16:40:14] "GET /static/js/2.2a4e2c0c.chunk.js.map HTTP/1.1" 200 1544716 Bad Request: /api/add-offer [07/Apr/2021 16:40:25] "POST /api/add-offer HTTP/1.1" 400 104 -
Converting IntegerField to ForeignKey from recovered database in Django
I'm working with a MySQL database that I connected to my django project (using python manage.py inspectdb > app/models.py) but it's not reading the relationships correctly. The ForeignKeys are IntegerFields so I cannot use the handy Django ORM lookup. Here's an example: class ChileStudents(models.Model): """ simplified version of the model """ otec = models.IntegerField(blank=True, null=True) # Here's the issue # More stuff goes here updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'chile_students' class Otecs(models.Model): """ Also a simplified version """ name = models.CharField(max_length=45, blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'otecs' As shown in the example above, the IntegerField points to the OTEC id, this is a simple one-to-many relationship. I tried converting the field into a ForeignKey like this: otec = models.ForeignKey('Otecs', on_delete=models.SET_NULL,blank=True, null=True, db_column="otec_id") But when migrating it just sets the column otec_id to NULL. Is there any way I can "convert" the field into a ForeingKey? -
Python - How to retrieve data with Django Restframework from firebase database (not the SQL db) and send to a client?
I have a Django rest API and I can perfectly fetch data from a my database to a flutter client app. But I would like to fetch data from firebase database to the client via the API. In other words I would like to send data in firebase database via my Django restframework API to the Flutter app. And I don't want to send data from my actual db SQL lite. I'm new to python and django This is what I tried so far.. views.py from rest_framework import generics from myapi import models from .serializers import ApiSerializer class ListTodo(generics.ListCreateAPIView): queryset = models.Myapi.objects.all() serializer_class = ApiSerializer class DetailTodo(generics.RetrieveUpdateDestroyAPIView): queryset = models.Myapi.objects.all() serializer_class = ApiSerializer serializer.py from rest_framework import serializers from myapi import models class ApiSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'topic', 'guides' ) model = models.Myapi models.py from django.db import models # Create your models here. class Myapi(models.Model): topic = models.CharField(max_length=200) guides = models.TextField() def __str__(self): return self.topic urls.py from django.urls import path from .views import ListTodo, DetailTodo urlpatterns = [ path('', ListTodo.as_view()), path('<int:pk>/', DetailTodo.as_view()) ] This code here retrieve a list of users that I would like to send throu API to the Flutter client app users = db.child("users").get() … -
drf ModelViewset does not validate Unique Constraint failed when unique_together is used
I am using djangorestframework==3.12.1 Here is how my code looks like:- models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=14, decimal_places=2) description = models.TextField(blank=True, null=True) def __str__(self): return self.name class Meta: unique_together = ( ("name", "user"), ) serializers.py class ProductSerializer(serializers.ModelSerializer): """serializer for Product objects.""" class Meta: model = models.Product fields = '__all__' read_only_fields = ['user',] views.py class ProductViewset(viewsets.ModelViewSet): queryset = models.Product.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = serializers.ProductSerializer Expected Behavior The validators on the Modelserializers must raise an exception as Product with this Name and User already exists. Actual Behavior IntegrityError at /api/v1/product/ UNIQUE constraint failed: projectapp_product.name, projectapp_product.user_id How do I fix this? -
In PDF, font-face appears to be loading from URL, but is not displayed
My Django app uses WeasyPrint to generate PDFs on demand. I am using WeasyPrint 52.4 and Django 3.2. I have been using system fonts, which has been working great. Now I'm trying to use local fonts. For now, I'm loading static assets through localhost, pointing to Django's static server, so I can watch the requests come in and make sure the right things are being loaded. Here is how WeasyPrint is being called: font_config = weasyprint.fonts.FontConfiguration() css = weasyprint.CSS(url='http://localhost:8000/static/kits/static/report.css', font_config=font_config) return weasyprint.HTML( string='<h1>Hello world</h1>', encoding='utf-8', ).write_pdf( stylesheets=[css], font_config=font_config, ) Here is my CSS: @font-face { font-family: 'foobar'; src: url(http://localhost:8000/static/Oxygen-Regular.ttf) format('truetype'); font-weight: 400; } @font-face { font-family: 'foobar'; src: url(http://localhost:8000/static/Oxygen-Bold.ttf) format('truetype'); font-weight: 700; } :root { font-family: 'foobar', sans-serif; color: red; } The text is correctly colored red, so I know the CSS is being loaded. I can see from my server logs that the requests for the fonts are successful, which indicates to me that WeasyPrint is fetching the fonts correctly: 2021-04-07 09:57:32,147 INFO "GET /static/mycss.css HTTP/1.1" 200 5748 2021-04-07 09:57:32,193 INFO "GET /static/Oxygen-Regular.ttf HTTP/1.1" 200 46440 2021-04-07 09:57:32,200 INFO "GET /static/Oxygen-Bold.ttf HTTP/1.1" 200 47096 But the PDF is showing the fallback sans-serif font. What am I missing? -
How to format dinamically generated HTML with django
Im trying to create a sheet of labels to print out with a QR code a logo and phone number, the QR codes are generated sepparatly from an xlsx file and they work. my issue is formatting them in the HTML. Im not sure how to change the for loop so it creates a row for each time an image is loaded onto the label. heres the html part of the code. {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>labels</title> <style> </style> </head> <link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}"/> <table width="150" cellpadding="2" cellspacing="1"> <tr> {% for item in list_qr_images %} <img src="{% static 'inc.png' %}" align="center"/> <img src="{{ item }}" align="center"> <p style="text-align:left">(718) 280-0000</p> {% endfor %} </tr> <tr></tr> </table> </br> </html> -
Celery: How to access class-based task methods from other task?
I have implemented a class-based task that is executed periodically (celery beat) but I want to run another task (which is not periodic) after an event and call the method of the mentioned periodic task. I searched in the documentation but I didn't find. So I tried it myself and managed to solve it in the following way: class MyTaskClass(Task): def a(self): ... @shared_task(base=MyTaskClass) def periodic_task(): ... @shared_task def task(): periodic_task.a() Is this method acceptable, and is there a better one?