Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not import 'art_project.schema.schema' for Graphene setting 'SCHEMA'. ImportError: cannot import name 'DjangoFilterConnectionField'
I am using graphene.django, but i have some problems to connect to graphiql. All the files : project schema.py : import graphene import art_app.customers.schema as customer class Query(customer.Query, graphene.ObjectType): pass class Mutation(customer.Mutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) app queries.py : import graphene from graphene import relay, ObjectType from graphene_django.filter import DjangoFilterConnectionField from .types.nodes import CustomerUserNode class CustomerUserQuery(ObjectType): customer_user = relay.Node.Field(CustomerUserNode) all_customer_users = DjangoFilterConnectionField(CustomerUserNode) class Query( CustomerUserQuery, graphene.ObjectType, ): pass app mutations; create.py: import graphene from graphene import relay from ...models import CustomerUserModel from ..types.inputs import CustomerUserCreateInput from ..types.nodes import CustomerUserNode class CreateCustomerUser(relay.ClientIDMutation): class Input: new_customer_details = graphene.Field(CustomerUserCreateInput) created_customer_details = graphene.Field(CustomerUserNode) @classmethod def mutate_and_get_payload(cls, root, info, **input): created_customer_details = CustomerUserModel.objects.create(**input.get("new_customer_details")) file = info.context.FILES['image'] created_customer_details.image = file return CreateCustomer(created_customer_details=created_customer_details) delete.py : import graphene from graphene import relay from ...models import CustomerUserModel from ..types.inputs import CustomerUserCreateInput from ..types.nodes import CustomerUserNode from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from graphql import GraphQLError class DeleteCustomerUser(relay.ClientIDMutation): class Input: id = graphene.ID(required=True) deleted_customer_details = graphene.Field(CustomerUserNode) @classmethod def mutate_and_get_payload(cls, root, info, id): deleted_customer_details = get_object_or_404(CustomerUserModel, id=id) if deleted_customer_details.is_active: deleted_customer_details.is_active = False deleted_customer_details.save() else: raise GraphQLError("This user is not active!") return DeleteCustomerUser(deleted_customer_details=deleted_customer_details) nodes.py: from graphene import relay from graphene_django import DjangoObjectType from ...models import CustomerUserModel class CustomerUserNode(DjangoObjectType): … -
none none on Django
I'm trying to get the id of another class using the filter and I'm not getting it because none appears. below the method used def total(self): soma = Venda.objects.filter(id=self.id).aggregate(total=Sum('item__qtde', flat = True)) return soma['total'] result enter image description here Below the complete class class Manifesto(models.Model): data_venda = models.DateField(default=timezone.now) carro = models.ForeignKey(Carro, on_delete=models.CASCADE) usuario = models.ForeignKey(User, on_delete=models.CASCADE) # venda = models.ForeignKey(Venda, on_delete=models.CASCADE, default=None, null=True, blank=True) #agencia = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True) #class Meta: # ordering = ["venda"] def imprimir(self): return mark_safe("<a target='_blank' href='%s'>Imprimir</a>" % self.get_absolute_url()) imprimir.allow_tags = True def get_absolute_url(self): return reverse('manifesto_detail', args=[self.pk, ]) #sem essa função não aparece as variaveis def get_manifesto(self): return Manifesto.objects.get(pk=self.pk) def total(self): soma = Venda.objects.filter(id=self.id).aggregate(total=Sum('item__qtde', flat = True)) return soma['total'] -
Any documentation for Django firebase email verification web backend [closed]
Firebase has some features like email verification and password recovery link. So I'm new to this, so I was wondering whether these features should be handled in frontend or backend. Plus if it needs to be handled in backend,is there any documentation which shows how to use the firebase email verification codes in Django Thanks! -
How to handle a token key in a website made with django, django-rest-auth, and react?
First of all, I am pretty new to working with Rest APIs and tokens, I have learned the basics of Django and React and I've kinda made some projects using those, so I'm giving a shot at making a website with both of them. Since, registering is simple with django-rest-auth, it's been handled with just POSTING the user data. However, when making a login, the token was returned and I simply do not know how to handle it. I have searched many articles about tokens, but they were all about JWT which returns an access token and a refresh token. However, django-rest-auth returns a single token and I saved it inside a cookie using a 'universal-cookie' in React. Since I'm making an e-commerce website, and I do want to add some functionality to the website by enabling the users to change their email, last name, first name and username, I do need to know the username of the account as it is unique. So, I am wondering if it would be alright and a good practice to save the username inside a cookie, again using a universal-cookie. It'd also be appreciated if someone shows me a good article about "what … -
Dynamically delete and add forms to inline formset (single printed fields) in django
I wanna have a button to add a new form, as well as I wish a delete button, that deletes a selected form. I can add forms by now, but the added ones don't become submitted. I wanna be able to delete them with ajax, so they do not refresh the whole page too. How can I do this? I got the following code currently: template <tr class="item"> <td> {% render_field forms.service name="service" class="" required="" %} </td> <td> {% render_field forms.unit name="unit" class="" required="" %} </td> <td> <a href="javascript:void(0)" id="inline-sex" data-type="select" data-pk="1" data-value="" data-title="Select sex" class="editable editable-click editable-open" style="color: rgb(152, 166, 173); display: none;">not selected</a> {% render_field forms.quantity name="quantity" class="" required="" %} </td> <td> {% render_field forms.unit_price name="unit_price" class="" required="" %} </td> <td> {% render_field forms.vat_rule name="vat_rule" class="" required="" %} </td> <td></td> {% if formset.can_delete %} <td>{{forms.DELETE}}</td> {% endif %} </tr> {% endfor %} <tr> <td colspan="4"> <input type="button" value="Add More" id="add_more" /> </td> </tr> <tr class="total"> <td colspan="3"></td> <td>Total: $385.00</td> </tr> <script> $("#add_more").click(function () { cloneMore("tr.item:last", "service"); }); function cloneMore(selector, type) { let newElement = $(selector).clone(true); let total = $("#id_" + type + "-TOTAL_FORMS").val(); newElement.find(":input").each(function () { let name = $(this) .attr("name") .replace("-" + (total - 1) + "-", … -
Django AsyncWebsocketConsumer with ws: and wss: protocol
I'm working on an application that requires me to send data packets to and from server. I'm using AsyncWebsocketConsumer in Django and WebSocket in JavaScript to create a socket connection. The problem I'm facing is that my application works with ws: protocol but when I switch to wss:, the requests don't appear on the server at all. Here are more relevant details about my project: myproject/settings.py ASGI_APPLICATION = 'myproject.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } myproject/routing.py application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) chat/routing.py websocket_urlpatterns = [ re_path(r'ws/(?P<room_name>\S+)/$', consumers.ChatConsumer), ] chat/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() # ... more code ... # some self.send() statements to send data over Socket JavaScript ... wsPath = "wss://" + window.location.hostname + ":8000/ws/" + roomName + "/"; webSocket = new WebSocket(wsPath); webSocket.onopen = ... When I use ws: instead of wss: in above JavaScript code, I see following in my server: WebSocket HANDSHAKING /ws/<room-name>/ [127.0.0.1:44450] WebSocket CONNECT /ws/<room-name>/ [127.0.0.1:44450] but I see no WebSocket requests when I use wss: I'm running python manage.py runserver. I suspected that it had something to do with SSL certificate, so … -
Writing custom middleware in Django 2.2, control not coming to __call__() method at all
I'm trying to create custom middleware within Django 2.2 application Below is my settings file : MIDDLEWARE = [ 'html_template.middleware.CorsMiddleware' ] and my middleware code is: class CorsMiddleware: def __init__(self, get_response): import ipdb; ipdb.set_trace() self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): import ipdb; ipdb.set_trace() # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Now according to Django 2.2 documentation https://docs.djangoproject.com/en/2.2/topics/http/middleware/ __call__() method should be executed every time a request hits the server, but the weird part is even though the __init__() method is executed but the control never reaches the __call__() method. Any thoughts? -
Accessing a database table using docx in python
Ihave a django db table called my_defect_table in database table i have an item which is a float, it is called number_in_table. I am trying to use docx module in order to access this table and generate a word document with this number. Main.py import docx import docx2pdf from docx2pdf import convert from django.http import FileResponse from django.shortcuts import render from site1app.models import my_defect_table def making_a_doc_function(request): doc = docx.Document() doc.add_heading(my_defect_table.number_in_table) doc.save('thisisdoc.docx') #converting the generated docx into a pdf file convert("thisisdoc.docx", "output.pdf") generated_doc = open('output.pdf', 'rb') response = {"generated_doc": FileResponse(generated_doc)} return render(request, 'doc.html', response) the problem is that when i am trying to access my_defect_table.number_in_table it is not reading the values. i just get an error that says 'DeferredAttribute' object is not iterable. I know that my document generation works because when i swap my_defect_table.number_in_table for just text "hello", a document is generated with "hello" as the heading. Any ideas where im going wrong? -
Change a model object value with javascript
So I have a model that has a FloatField, also I have a javascript code, what I need is to change the value of the Floatfield with +1 everytime you click in a button, the problem is that I had no idea of how to make it, here is my model: class ProfileImage(models.Model): """ Profile model """ user = models.OneToOneField( verbose_name=_('User'), to=settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE ) avatar = models.ImageField(upload_to='profile_image') notifications = models.FloatField(default='0') I need to give +1 to notifications object evertime a function in js is doing, how can I do this? -
return render(request, "product/products.html", {"products":products, "n_pages":n_pages}) ^ SyntaxError: 'return' outside function Django
I'm working on a showcase site in Django, and I wanted to include a paging system in the product list, but I ran into this error. views.py class articoloList(request): products = Product.objects.all paginator = Paginator(prodotti, 15) page = request.GET.get("pagina") n_pages = paginator.get_page(page) return render(request, "product/products.html", {"products":products, "n_pages":n_pages}) models.py class Product(models.Model): name = models.CharField(max_length=120) img = models.ManyToManyField(Immagine) description = models.TextField() category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE) marchio = models.ForeignKey(Marchio, related_name="marchi", on_delete=models.CASCADE) price = models.PositiveIntegerField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name + " " + self.date def get_absolute_url(self): return reverse("product_detail", kwargs={"pk":self.pk}) Thanks in advance! :) -
Django different models versions on the same data
Currently I'm working on some Django + Postgres project. There I currently have 2 branches: dev and master. Usually as soon as I finish developing and testing a new feature (I develop this part of the project on my own, no other developers involved) I merge dev into master and then upload it onto the production server (dev was uploaded and tested on the test server before, of course). And that's it. That WAS it. Now my boss wants me to use beta versions, like an extra layer between master and dev. So, now when I want to merge dev into master first I should merge it into new beta branch. Then beta is uploaded onto the master server but under its own sub-domain, like beta.some.site.com. Some trusted users will have access to this subdomain and will be able to use the new unstable features. However, if they discover some blocking bug they can switch back to the stable version (some.site.com, without beta prefix). Then, after some significant time and trusted user reviews beta gets merged into master. Our main goal with such move is to decrease the amount of hotfixes we usually do after introducing another version to the … -
cant run Django-Responsive2
after following django-responsive2 documentation , I get this error : File "C:\Users\Adminstrator\Desktop\project\project\settings.py", line 147, in 'verbose_name': ('Small screens'), NameError: name '' is not defined thnx in advance -
Extend User Model in Django and Update Profile data?
I want to update user and its profile simultaneously. Model Creation of extra profile fields #Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=15) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Model Form Creation of User Model from django.contrib.auth.models import User #form class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2", "first_name", "last_name"] user profile fields form creation #Form class UserProfileForm(ModelForm): class Meta: model = Profile exclude = ('user',) fields = ['phone_number'] View Created of both returning both User and Profile form #view def register(response): if response.method == "POST": user_form = RegisterForm(response.POST) profile_form = UserProfileForm( response.POST) if user_form.is_valid() and profile_form.is_valid(): user_form.save() redirect("somewhere") else: user_form = RegisterForm() profile_form = UserProfileForm() return render(response, "register/register.html", {"form": user_form, "profile": profile_form}) Html Template for both forms #template <form> {{ form.as_p }} {{ profile.as_p }} </form> -
Django Admin Form, Set the default value of readonly Field (User Foreign Key Field )
I'm currently working on a multi-vendor eCommerce site, in the model every item has a user, I want to save a User (read-only and item foreign key) while adding an item, I don't want to show the user field and if I use readonly_fields so my user will be null, how can I achieve that, Please help me ADMIN.PY class ItemAdd(admin.ModelAdmin): list_display = ['name', 'price','minimum_order','status'] list_display_links = ['name', 'price','minimum_order',] search_fields = ['name', 'description'] ordering = ('-price',) list_filter = ['price', 'status', 'category'] list_per_page = 25 list_editable = ['status',] def get_form(self, request, obj=None, **kwargs): form = super(ItemAdd, self).get_form(request, obj, **kwargs) form.base_fields['user'].initial = request.user return form def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) -
django-storages aws s3 costs reduction and calculation
i would like to calculate and reduce my costs for my file storage on s3. I have deploy my django app to elastic beanstalk in Europa (Frankfurt) eu-central-1. At the moment i use a t2.micro ec2 instance, a db.t2.micro PostgreSQL database and a additional standard s3 bucket beside the standard bucket from elastic beanstalk. I think the cost for the ec2 and the database are easy manageable because after the free tier i would like to use reserved instances. But the s3 costs make me worry. Users can upload and download files to my application. My django application use django-storages to manage the files but i don't know what happened in the background and for what i must pay. For example i have a storage class and a model with a file field named export: class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' custom_domain = False class Document(models.Model): name = models.CharField(max_length=255) ... class FileDocument(models.Model): document = models.ForeignKey('documents.Document', on_delete=models.CASCADE, related_name="files") file = models.FileField(storage=PrivateMediaStorage()) ... - - Upload I store files thats a user upload like this: document = Document.objects.get(...) files = request.FILES.getlist('files[]') if files: for file in files: try: file_obj = FileDocument.objects.get(name=file.name, document=document) file_obj.file.save(file.name, file) file_obj.save() except FileDocument.DoesNotExist: file_obj = FileDocument() … -
Getting Error when trying to Generate password reset email link in django using firebase SDK
email = 'user@example.com' link = auth.generate_password_reset_link(email, action_code_settings) # Construct password reset email from a template embedding the link, and send # using a custom SMTP server. send_custom_email(email, link) So I'm using this code from https://firebase.google.com/docs/auth/admin/email-action-links#python in django and I'm getting this error: NameError: name 'send_custom_email' is not defined And nothing is mentioned in the documentation. So if anyone knows the solutions it would be great. -
Pipfile not showing all installed packages
I am using pipenv as the virtual environment in a Django project. I installed the Django third-party package django-allauth-2fa via pipenv install django-allauth-2fa==0.8. In the package's docs regarding its installation it says: note that this will install Django, django-allauth, django-otp, qrcode and all of their requirements. After successfull installation I wanted to check if this is in fact the case, however my Pipfile did not show any new installation besides django-allauth-2fa. I double checked with pip freeze from within the virtual environment shell and got a list back, in which all the package's dependencies were indeed listed (qrcode, django-otp, etc.) My question is hence: Do I have a misunderstanding about how the Pipfile works? I assumed that the file shows all the packages that are installed in my virtual environment. Or are only those shown that were installed via the pipenv install <package> command but not those that were installed alongside packages installed via pipenv install <package>? -
Add PK from foreign attribute in a djtables 2 accessor
I have two data models, company and conteact_person. They are linked in a m2m variant: models.py: class ContactPerson(models.Model): first_name = models.CharField('first name', max_length=120) last_name = models.CharField('last name', max_length=120) @property def contact_name(self): return f"""{self.last_name} {self.first_name}""" class Customer(models.Model): name = models.CharField('company name', max_length=120) contact_persons = models.ManyToManyField(ContactPerson, blank=True, null=True) @property def contacts(self): return ', '.join([x.contact_name for x in self.contact_persons.all()]) tables.py: class CustomerTable(django_tables2.Table): name = django_tables2.LinkColumn("customer-detail", args=[django_tables2.A("pk")]) contacts = django_tables2.LinkColumn("contact-detail", args=[django_tables2.A("pk")], accessor="contacts", verbose_name="contacts") class Meta: model = Customer sequence = ("name", "contacts") What I want is that every name is linked to it's contact detail, but obviously args=[django_tables2.A("pk")] holds the PK of customer. How would I achieve to get the correct pks for contact_person into contacts? I thought about generating a dict in the models method like [{"name": "bart", "id": 1}, {"name": "Rita", "id": 2},]. But sure there is a smoother way? views.py: class CustomerListView(SingleTableView): model = Customer context_object_name = 'customer' table_class = CustomerTable template_name = "customerlist.html" def get_queryset(self): qs = super(CustomerListView, self).get_queryset() return list(qs) -
Can't get Cookiecutter-Django to issue certificates with let's encrypt and Traefik please look at the error
I deployed cookiecutter django to digitalocean and pointed my domain at it and when I run the server I get this: traefik_1 | time="2020-08-10T04:07:32Z" level=error msg="Unable to obtain ACME certificate for domains \"example.com\": unable to generate a certificate for the domains [example.com]: acme: Error -> One or more domains had a problem:\n[example.com] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://example.com/.well-known/acme-challenge/rLtIcAGYE4rBY3iUjbIm9p5XUqZBosTV_qJp8nPoBxw [2606:2800:220:1:248:1893:25c8:1946]: \"<!doctype html>\\n<html>\\n<head>\\n <title>Example Domain</title>\\n\\n <meta charset=\\\"utf-8\\\" />\\n <meta http-equiv=\\\"Content-type\", url: \n" routerName=flower-secure-router rule="Host(`example.com`)" providerName=letsencrypt.acme traefik_1 | time="2020-08-10T04:07:33Z" level=error msg="Unable to obtain ACME certificate for domains \"example.com,www.example.com\": unable to generate a certificate for the domains [example.com www.example.com]: acme: Error -> One or more domains had a problem:\n[example.com] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://example.com/.well-known/acme-challenge/rLtIcAGYE4rBY3iUjbIm9p5XUqZBosTV_qJp8nPoBxw [2606:2800:220:1:248:1893:25c8:1946]: \"<!doctype html>\\n<html>\\n<head>\\n <title>Example Domain</title>\\n\\n <meta charset=\\\"utf-8\\\" />\\n <meta http-equiv=\\\"Content-type\", url: \n[www.example.com] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://www.example.com/.well-known/acme-challenge/dhSnRKK6iV_EdanHIF2HJ1xoGEf0MaAS-49R7zEmR0U [2606:2800:220:1:248:1893:25c8:1946]: \"<!doctype html>\\n<html>\\n<head>\\n <title>Example Domain</title>\\n\\n <meta charset=\\\"utf-8\\\" />\\n <meta http-equiv=\\\"Content-type\", url: \n" providerName=letsencrypt.acme routerName=web-secure-router rule="Host(`example.com`) || Host(`www.example.com`)" I noticed my traefik.yml file has "example.com" in it but Im not sure what to change to my domain. Does anyone have any idea how to resolve this? traefik.yml: level: INFO entryPoints: web: # http address: ":80" web-secure: # https address: ":443" … -
Is there any way to add CSS/JS files dynamically in Django templates?
Actually I am trying to implement a content delivery application in Django to support my SASS based application with dynamic style sheets and Javascript files. I searched a lot but wasn't able to find a single solution for this. In a nutshell, I simply want to implement an application in which views fetch the CSS/JS files and then use the URLs of these views in a Django template (HTML) so that the response of those views as the content of a CSS/js file could include in the Django template. I would be very grateful if someone helps me with this problem. I am stuck on this and not able to proceed further with my project. It sucks a lot. Thanks a lot in advance. -
Why is my login route not working in django 3?
Hey I am trying to learn Django from Corey schafer tutorials on youtube. Everything well until i reached seventh tutorial titled Login and Logout system. Now the error is that I can login from admin but when I try to login from my login page, it shows 404 error. Its really is frustrating cause none of the users i have created can login this way. When I am logging in with fake username and password instead of telling me it does not match I see this error Request Method: GET Request URL: http://127.0.0.1:8000/login/POST?csrfmiddlewaretoken=fMzOvSO7a9H2Hm7QD13Tc3omSIZCtDA8DUQQLrUicmaKVbptEZghSu36afTIqnO6&username=gfahgfhgfhga&password=cafchccha What can the problem be??? -
How to save initial object to database that has a self reference in Django
Let's say I have a custom Django model User with a self-reference: Class User(models.Model) name=models.CharField(max_length=80) . . . user_created = models.ForeignKey( 'self', on_delete=models.PROTECT, ) As you can see, I want the user_created field to have a NOT NULL constraint. Not surprisingly, if I try to create the first ever user without a user_created reference like so... User.create(name='Bob') <-- Remember I'm the first ever user in the DB I get: django.db.utils.IntegrityError: null value in column "user_created" violates not-null constraint I get why Django throws this error. I have declared a NOT NULL CONSTRAINT for the user_created field, but I can't provide anything because no other user currently exists in the database. I have previously dealt with this by first creating a User object, and then applying the Not Null constraint, which works fine except when I run tests. When I run tests Django creates a new database and there is no way for me to supply the first user to that test database. I worked around this by creating a CustomTestRunner(DiscoverRunner) that drops the constraint before the test database is created, which also works fine. However, I was wondering if anyone else out there ran into this problem and found a … -
Password mismatch in Django production
My Django app works fine in development server but once I push it to production on heroku, user registration is giving password mismatch error. Could this be problem with heroku itself or my code(but I don't think so since it work well on my local machine) -
Django-recaptcha always showing "This field is required." even-tough it is there
I am trying to use Recaptcha v3 in one of my projects. Unfortunately the form.valid_date() method fails all the time with "This field is required.". Running django-recaptcha. forms.py looks like this: class AccountForm(forms.ModelForm): # adding some default validators phone = forms.CharField(validators=[MinLengthValidator(10)], error_messages={'invalid':_("Please add a valid phone number.")}) terms = forms.BooleanField() captcha = ReCaptchaField( public_key=settings.RECAPTCHA_PUBLIC_KEY, private_key=settings.RECAPTCHA_PRIVATE_KEY, widget=ReCaptchaV3( attrs={ 'required_score': 0.85, } ) ) class Meta: model = Account fields = ['phone', 'terms'] def clean_phone(self): data = self.cleaned_data['phone'] if not validate_phone(data): raise forms.ValidationError(_("Please add a valid phone number. ")) return data def clean_terms(self): data = self.cleaned_data['terms'] if not True: raise forms.ValidationError(_("Please accept the T&Cs")) return data views.py looks like this: def register_web(request: object) -> object: key = request.GET.get('key', '') merchant = request.GET.get('merchant', '') if request.method == 'POST': print(form.is_valid()) print(form.errors) if form.is_valid(): phone = phone_filter(str(request.POST.get('phone')).replace(' ', '')) name = request.POST.get('name', '') confirmationForm = ConfirmationForm() return render(request, 'registerWebConfirmation.html', {'context':context }) else: return render(request, 'registerWeb.html', {'form': form}) else: return render(request, 'registerWeb.html', {'form': form}) The print in the views.py states: False <ul class="errorlist"><li>captcha<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Any ideas are welcome. -
Is it possible to generate PDF with StreamingHttpResponse as it's possible to do so with CSV for large dataset?
I have a large dataset that I have to generate CSV and PDF for. With CSV, I use this guide: https://docs.djangoproject.com/en/3.1/howto/outputting-csv/ import csv from django.http import StreamingHttpResponse class Echo: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def some_streaming_csv_view(request): """A view that streams a large CSV file.""" # Generate a sequence of rows. The range is based on the maximum number of # rows that can be handled by a single sheet in most spreadsheet # applications. rows = (["Row {}".format(idx), str(idx)] for idx in range(65536)) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in rows), content_type="text/csv") response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' return response It works great. However, I can't find anything that can be done for PDF. Can it? I use render_to_pdf as well as I use a template for PDF.