Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Como obtener la row de la tabla en hbase shell
Quiero obtener la row de cada uno de los datos que estan ingresados tiene la estructura que se muestra a continuacion ROW COLUMN+CELL 1 column=datos_personales:documento, timestamp=1604669916960, value=16646015 Hize este codigo que me trae la row pero solo me trae la 1, y necesita que dependiendo de cada uno me traiga sea la 1 o 2 o 3 no se que haya mal en la consulta, muchas gracias def obteneridAuth(request): table = database.connection.table('users') exist_user = table.scan(filter="SingleColumnValueFilter ('datos_personales','cedula',=,'regexstring:^"+request.user.username+"$')") id_user=next(exist_user)[0] return id_user -
ERROR: Command errored out with exit status 1: Python When Installing pyautogui and any other programs
WEll I Get and Error Like this ERROR: Command errored out with exit status 1: command: 'C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui\setup.py'"'"'; file='"'"'C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Pranzal\AppData\Local\Temp\pip-pip-egg-info-s1_syjvk' cwd: C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui Complete output (28 lines): Traceback (most recent call last): File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources_init_.py", line 2848, in get_entry_map ep_map = self.ep_map File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources_init.py", line 2810, in getattr raise AttributeError(attr) AttributeError: _ep_map During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui\setup.py", line 18, in <module> setup( File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\__init__.py", line 152, in setup _install_setup_requires(attrs) File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\__init__.py", line 142, in _install_setup_requires dist = MinimalDistribution(attrs) File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\__init__.py", line 134, in __init__ distutils.core.Distribution.__init__(self, filtered) File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\dist.py", line 421, in __init__ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources\__init__.py", line 640, in <genexpr> for entry in dist.get_entry_map(group).values() File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources\__init__.py", line 2850, in get_entry_map ep_map = self._ep_map = EntryPoint.parse_map( File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources\__init__.py", line 2535, in parse_map raise ValueError("Entry points must be listed in groups") ValueError: Entry points must be listed in groups ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Losing user authentication after logging from a different app in the same django project
In my django project, I have two applications, coachingapp and account. My purpose is to be able to login from the admin application successfully and be directed to the index page under the coachingapp as authenticated. I am using Django 3.1.3 My views.py in the admin app: from django.shortcuts import render, redirect from .forms import LoginForm from django.contrib.auth import login, logout from django.http import HttpResponseRedirect from django.contrib import messages from .models import User user = None def login_site(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): data = form.cleaned_data global user user = authenticate_user(data['your_email'], data['your_password']) if user is not None: login(request, user) result = {'form': form} return HttpResponseRedirect("/", result) else: result = {'form': form} messages.error(request, 'incorrect email or password') else: result = {'form': form} messages.error(request, 'Your input seems invalid!') else: form = LoginForm() result = {'form': form} return render(request, "account/login.html", result) def authenticate_user(email, password): try: user = User.objects.get(email=email) except User.DoesNotExist: return None else: if user.check_password(password): return user return None Here is my views.py in the coachingapp: from __future__ import unicode_literals from django.http import JsonResponse from django.shortcuts import render from django.http import HttpResponseRedirect def index(request): if request.user.is_authenticated: return render(request, "coachingapp/index.html", {}) else: return HttpResponseRedirect("account/login_site") I am successfully authenticating in the … -
How to add an input integer to update the model field through form?
I have a model that holds an inventory value. I want to be able to add any integer value to that model field. It doesn't throw any errors but I get unexpected results when I post. For some reason I do not understand, the code is multiplying the number entered in the form by 2 and setting the result as the new inventory number. I have tried using both forms.Form and ModelForm for my form. The form I am using is also used to update the Panel description, so the text area for the description is pre-populated with the current Panel description. For example, if I have an inventory of 80 and I enter 3 in the input field and POST, the new inventory will be 6. That is obviously not what I expect to happen, I would like it to POST and make the new inventory 83. Models.py class Panel(models.Model): name = models.CharField('Name', max_length=50, default='') slug = models.SlugField(unique=True) description = models.TextField('Description', null=True, blank=True) date_created = models.DateTimeField('Date Created', auto_now_add=True, null=True) display = models.BooleanField(default=True) image = models.ImageField('Panel Image', null=True, blank=True) inventory = models.IntegerField('Inventory', null=True, default=0) def get_absolute_url(self): return reverse("model_detail", kwargs={"pk": self.pk}) def __str__(self): return f'{self.name}' def save(self, *args, **kwargs): if not … -
alpine.js pagination limit the pages
i have an array of numbers (from search results) and then the code for pagination. I want only the first 3 pages to be visible, but if i click on the 3 page, i want that the next page is visible and so on .... <template x-for="(page,index) in pages()" :key="index"> <button class="px-3 py-2 rounded focus:outline-none" :class="{ 'text-primary-500 border border-primary-500 text-white font-bold' : index === pageNumber, 'hidden' : index > visiblePages }" type="button" x-on:click="viewPage(index)"> <span x-text="index+1"></span> </button> </template> it is working, with the next button, i can go to page 4,6,7 etc. but in the pagination there is only standing 1,2,3. For me it's clear, because i set the class to hidden if the index is greater then 3. But i don't know how to change that if i click on next button AND the index is greater then 3 that there is standing 4, then 5, then 6 and so on. I hope you understand what i mean :) I took the code from: Alpine Toolbox but with this code the problem is, that if i have for example 100 Pages, there will be 1,2,3....100 pagination numbers and i don't want this. thanks for helping Greets Martin -
Access API key in javascript from django settings.py
I am trying to pass an API key for google places from my settings.py file to a JS script. Should I expect to be able to access the variable in the JS script this way, or is there a better approach? # settings.py api_key = 123456HYTYTY # views.py args['api_key'] = settings.api_key return render(request, 'template_example.html', args) # template.html {% block js %} <script src="https://maps.googleapis.com/maps/api/js?key={{ api_key }}&libraries=places" defer></script> {% endblock js %} -
Tip for optimization in signal processing
I have two task models and activities, what I am doing is that every time the user puts the process in the activities model in true, a count is made, what I want to do, it does it in the correct way and it is as I expect, but I feel that the solution I have is not the most optimal, I would like to know if there is any way to do what I have in a more optimal way. This my model: class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) type_task = models.ForeignKey(TypeTask, on_delete=models.CASCADE) task = models.CharField(max_length=50) description = models.TextField() state = models.BooleanField(default=False) porcentage = models.IntegerField(default=0) slug = models.SlugField(max_length=60, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.task class Activities(models.Model): name = models.CharField(max_length=50) process = models.BooleanField(default=False) task = models.ForeignKey(Task, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name This is my signal: @receiver(post_save, sender=Activities) def calculate_porcentage(sender, instance, *args, **kwargs): tasks = Task.objects.all() for task in tasks: activities = Activities.objects.filter(task=task).count() completed = Activities.objects.filter( task=task).filter(process=True).count() porcentage = (completed * 100) // activities instance.porcentage = porcentage -
Django django.core.files.File(file-like object) returns File('None')
I have a io.BytesIO object that I want to convert to a valid Django File object. My code is simple: ret_file = File(file_object) (Pdb) ret_file <File: None> (Pdb) file_object <_io.BytesIO object at 0x7ab3fa1d51d0> I can't figure out how to get this object as a valid File. Any help would be much appreciated. Thank you in advance -
Using Django-MPTT in Django-Filters to get children on filtering parent node
I have an MPTT model class, and want to use it in Django-Filter. My MPTT model is; class ProdCategory(MPTTModel): name = models.CharField(max_length=200, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = AutoSlugField(populate_from='name',slugify=slugify) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name The class is used as a foreign key in another "deal" model class as 'productCategory' My filter class in filters.py is: class DealFilter(django_filters.FilterSet): class Meta: model = deal fields = ['store', 'productCategory'] Finally, my view is: def filterdeals(request): deals = deal.objects.all() myFilter = DealFilter(request.GET, queryset = deals) deals = myFilter.qs args = { "deals": deals, "myFilter":myFilter,} return render(request, 'deals/filter.html', args) Now, since in MPTT, I want all the children selected on filtering the parent, I want to include this code for the same: deal.objects.filter(productCategory__in=ProdCategory.objects.get(pk=2).get_descendants(include_self=True)) But I don't know where to include this code- so that when the parent category ID is passed, I get all the children under it. TIA for your help -
Serving gzip content from Django TemapleView
I am using TemplateView to render my pages. Recently I started using webpack to compress my js files into a gzip format. I now want to modify my Template view to render the gzip file. Currently I'm setting the TemplateView's component field to <my_component>.js and I want to change it to <my_component>.js.gz. For that I need to set up the content-encoding header param of the response to 'gzip'. Is there a way to do it somehow in the TemplateView class? I dont want to change the class because I dont really want to deal with the HttpResponse builerplate. -
Configure batabase for production/project managment
My ultimate goal is to create a Django based (so with Python) web application to handle production activities (at work). In other word, something similar to project managment app, with different task for each project etc. But, before thinking about Django "world", I was thinking about how to define the underlying database. First of all let me explain what I mean. Let's assume that I have to produce object OBJ1. To do that I have to complete a certain number of tasks, say TSK1, TSK2,TSK3. The same for OBJ2, OBJ3 and so on... So, each "Object" has its own (different from object to object) sequence of tasks, with their own duration. Now I may have to produce 5 pieces for OBJ1, 40 for OBJ2, and so on, and every "instance" of OBJx could have different delivery date (tasks have different duration, from 1 hour to 7 days for example, it depends). I'd like to be able (at the end of the project) to add every OBJs to a page where I can update the tasks status, to control the progress and check for delay and so on. At the end... I'd like to be able to "handle": different project (obj) … -
Django Crispy Forms - Display List of Dictionaries
Take the following list of dictionaries as an example: {"host": "test-01", "service": "tomcat"}, {"host": "test-02", "service": "tomcat"}, {"host": "test-03", "service": "tomcat"}, {"host": "test-04", "service": "tomcat"}, {"host": "test-05", "service": "postgres"}, {"host": "test-06", "service": "tomcat"}, {"host": "test-07", "service": "tomcat"}] I essentially want to create a HTML message for each dictionary saying what service is going to be restarted on what server. However, I'm not sure what the best way of going about this is. I've tried the below to no avail: views.py def restart_es_services_confirm(request): systems = [{"host": "test-01", "service": "tomcat"}, {"host": "test-02", "service": "tomcat"}] form = ServicesConfirm(request=request) if request.method == 'POST': return HttpResponseRedirect('restart_services.html') else: form = ServicesConfirm(request=request) return render(request, 'restart_services_confirm.html', {'form': form}, {'systems': systems}) restart_services.py class ServicesConfirm(forms.Form): reconfirm = forms.BooleanField(required=True, label='I confirm these services can safely be restarted.',widget=forms.CheckboxInput(attrs={})) def __init__(self, *args, **kwargs): request = kwargs.pop("request") super().__init__(*args, **kwargs) systems = request.session['systems'] for system in systems: host = system['host'] service = system['service'] message = ("Restart " + service + " on " + host) self.helper = FormHelper() self.helper.add_input(Button('cancel', 'Cancel', css_class='button button--wide button--black', formvalidate='formnovalidate', onclick="window.location.href = '{}';".format(reverse('home')))) self.helper.add_input(Submit('deploy', 'Deploy', css_class='button button--wide button--white')) self.helper.form_method='POST' self.helper.layout = Layout( Fieldset( 'Confirmation', Row( Column('reconfirm', css_class='form-group col-md-14 mb-0') ) ) ) restart_services_confirm.html: <!doctype html> <html lang="en"> {% load static %} … -
Django - How to query a list inside of a filter method
I am new to Django and I want to query a list inside of an object. I have a list of Batches and each batch has a BatchComment list. Both of them has a User property. What I want to do is get batches where user has a comment and only get ones where the last comment is not made by the user. How can I achieve this? Currently I am retrieving batches that user has comment by Batch.objects.filter(comments__user=self.request.user) I want something like Batch.objects.filter(comments__user=self.request.user).filter(comments_last__user!=self.request.user) -
input_formats in Django ModelForm DateTimeInput throwing TypeError
I have seen a lot of questions on this and all the answers seem to be because input_formats was incorrectly being placed on the DateTimeField on the model and not on the form. Well, I'm trying to do this on the ModelForm and I'm still getting an error. Can anyone see where I may be going wrong here? models.py class Vacancy(models.Model): deadline = models.DateTimeField(blank=True, null=True) forms.py class CreateVacancyForm(ModelForm): class Meta: model = Vacancy fields = ["deadline"] widgets = { "deadline": forms.DateTimeInput(format='%d/%m/%Y %H:%M', input_formats=['%d/%m/%Y %H:%M'], attrs={ 'class': 'form-control' }) } The error: line 56, in Meta "deadline": forms.DateTimeInput(format='%d/%m/%Y %H:%M', TypeError: __init__() got an unexpected keyword argument 'input_formats' I am using Django version 3.1.1 -
How to handle 0,1 or more queryset results
How can i handle if queryset have to give me 0,1 or more results? Something like this i thought could work, but it didn't... class Board_dets_view (DetailView): template_name = 'board.html' model = Board def get_context_data(self, **kwargs): context = super(Board_dets_view, self).get_context_data(**kwargs) id_board = self.object.id #se get dà errore, uso filter, se da errore filter restituisco vuoto if not Column.object.filter(board_id=id_board): #se filter non funziona ho 0 o 1 risultati if not Column.object.get(board_id=id_board): # se get non funziona ho 0 risultati return context #restituisco vuoto #ho un risultato e proseguo if not Column.object.filter(board_id=id_board): id_column = Column.object.get(board_id=id_board) context['column_list'] = Column.object.get(board_id=id_board) context['card_list'] = Card.object.filter(column_id=id_column) return context if not Column.object.get(board_id=id_board): id_column = Column.object.filter(board_id=id_board) context['column_list'] = Column.object.filter(board_id=id_board) context['card_list'] = Card.object.filter(column_id=id_column) return context -
Django - retrieve api url from template and pass to views
I am using Cryptocompare.com api to load news from cryptocurrencies world. In the template I am looping through it show it on the home-page. I would like to add feature that if you click send button it will send an email to you with the link for the news you just clicked. What is the best way to do it? I tried that, but I dont know how to link the clicked element with the url in views. def home(request): # Grab Crypto News api_request = requests.get('https://min-api.cryptocompare.com/data/v2/news/?lang=EN') api = json.loads(api_request.content) return render(request, 'crypto/crypto_home.html', {'api': api}) def SendLink(request): if request.method == 'POST': subject = 'Link to crypto news' from_email = 'test@gmail.com' message = 'Hello {}, here is your link:'.format(request.user) to_email = [request.user.email] send_mail( subject, message, from_email, to_email ) return HttpResponseRedirect(reverse('crypto-home')) Template: {% for x in api.Data %} <div class='col-sm'> <div class="card"> <img class="card-img-top" src="{{ x.imageurl }}" alt="{{ x.source }}"> <div class="card-body"> <h5 class="card-title">{{x.title}}</h5> <p class="card-text">{{ x.body|safe }}.</p> <div class="btn-group btn-group-sm" role='group'> <a href="{{x.url}}" target="_blank" class="btn btn-primary">Read More</a> <form method="post" action="{% url 'send_link' %}"> {% csrf_token %} <button id="{{x.id}}" target="_blank" class="btn btn-primary">Send to e-mail</button> </form> </div> </div> </div> </div> {% endfor %} I would like to add link from template 'x.url' to … -
don´t create duplicated objects. django, python
I created a script to avoid creating duplicate objects but it still created the same objects when I run the command 3 times it creates them 3 times over and over again. I would like you to help me and know what is wrong with my code. from django.core.management.base import BaseCommand from jobs.models import Job import json from datetime import datetime import dateparser class Command(BaseCommand): help = 'Set up the database' def handle(self, *args: str, **options: str): with open('static/newdata.json', 'r') as handle: big_json = json.loads(handle.read()) for item in big_json: if len(item['description']) == 0: print('Not created. Description empty') continue dt = dateparser.parse(item['publication_date']) existing_job = Job.objects.filter( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], publication_date = dt, salary = item['salary'], city = item['city'], district = item['district'], job_url = item['job_url'], job_type = item['job_type'], ) if existing_job.exists() is True: print('This Job already exist') else: Job.objects.create( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], publication_date = dt, salary = item['salary'], city = item['city'], district = item['district'], job_url = item['job_url'], job_type = item['job_type'], ) self.stdout.write(self.style.SUCCESS('added jobs!')) -
Django: While condition in annotations
I got stuck in making a query in which I want to annotate a field and make use of while condition. PROJECT CONFIGURATION PYTHON = 3.9 Django = 3.1.3 My models: class Worker(models.Model): name = models.CharField('Worker Name', max_length=100, unique=True) joining_date = models.DateField('Joining Date', auto_now_add=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.name = self.name.title() super(Worker, self).save() def __str__(self): return self.name class Meta: db_table = 'workers_details' class Article(models.Model): name = models.CharField('Article Name', max_length=200, unique=True) date_created = models.DateField('Created Date', auto_now_add=True) def __str__(self): return str(self.name) + str(self.id) class Meta: db_table = 'articles' class ArticleDetail(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) date_created = models.DateField(auto_now_add=True) last_updated = models.DateField(auto_now=True) work_type = models.CharField('Type of Work', max_length=255) def __str__(self): return str(self.article.name) + " " + str(self.work_type) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.work_type = self.work_type.title() super(ArticleDetail, self).save() class Meta: db_table = 'article_details' class ArticleRate(models.Model): article_detail = models.ForeignKey(ArticleDetail, on_delete=models.CASCADE) effective_date = models.DateField("Effective Date") rate = models.FloatField("Rate") def __str__(self): return str(self.article_detail.article.name) + " " + str(self.article_detail.work_type) + " " + \ str(self.rate) class Meta: db_table = 'article_rate' class DailyRecord(models.Model): date = models.DateField() worker_name = models.ForeignKey(Worker, on_delete=models.PROTECT) rate = models.ForeignKey(ArticleRate, on_delete=models.PROTECT) pieces = models.IntegerField('No. Of Pieces') minutes_printing = models.FloatField('Screen Printing Time') def __str__(self): return str(self.date) + " " + str(self.worker_name.name) + " " + … -
how to run some web scrapping script in django webapp
i want to create a django webapp for electronic component selection tool. one of its functionality will be to show all products available. i have written script to do so. which works well in code editor. it shows output like this: (1, 'Automation and Control') (2, 'Accessories') (3, 'Controllers - Accessories') . . . i have recently started learning django.and i know how to create views, render html pages etc. what i am really struggling with is how to and where to use my script in the django webapp so that when user is directed to home page all the products will be shown code that i have written: import requests import bs4 res = requests.get("https://www.digikey.in/products/en") soup = bs4.BeautifulSoup(res.text,"lxml") base_url = "https://www.digikey.in" mydivs = soup.find_all("a", {"class": "flymenu__item-title"}) name_link = {} count = 1 for i in mydivs: name = i.getText() link = i.get('href') name_link[name] = link count = 1 name_num = {} for i in name_link.keys(): name = i name_num[count] = name count += 1 for pair in name_num.items(): print(pair) what i expect is where to put this code in django app so that when user visits http://127.0.0.1:8000/ output shown as above will be shown to user -
Django test render_to_string() without request
I want to write a test for my function: def render_email_body(ticket, action_type, comment): return render_to_string( action_to_body_template[action_type], { "issue_key": ticket.get_pk(), "comment": comment }, ) Basically I want to check if generated text comes from templates/emails/bodies/some_file.html (action_to_body_template[action_type] points to the location of the file). However assertTemplateUsed function takes a request as a parameter. So my question is how can I check which template was used, without a request. -
Why does WebSocket onmessage event not work
When I send data to the WebSocket nothing happens and messages don't appear in the div elements. I don't know where is a problem: in consumer class or in javascript. Here is my javascript: {% extends 'base.html'%} {% block title %}Chat room for '{{ course.title }}'{% endblock %} {% block content %} <div id = 'chat'> </div> <div id = 'chat-input'> <input id = 'chat-message-input' type = "text"> <input id = 'chat-message-submit' type = "submit" value = "Send"> </div> {% endblock %} {% block domready %} //creating url to connect to websocket var url = 'ws://' + window.location.host + '/ws/chat/room/' + '{{ course.id }}/'; var chatSocket = new WebSocket(url); // this func is called every time a message recieved through the WebSocket chatSocket.onopen = function(){ chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data.message; console.log('message') // accessing the chat div element and appending a div element with the message var $chat = $('#chat'); $chat.append('<div class = 'message'>' + message + '</div>'); // scroll to show all messages $chat.scrollTop($chat[0].scrollHeight); // scrollHeight is used to get a hight value of the given element console.log('OK'); }; chatSocket.onclose = function(e){ console.error('Chat socket closed unexpectedly'); }; var $input = $('#chat-message-input'); var $submit … -
Testing django mail and attachment return empty
I'm trying to test mails with attachment, I'm attaching the files something like this: # snippet of send_pdf_mail mail = EmailMessage( subject=subject, body=message, from_email=from_email, to=recipient_list, ) dynamic_template_data.update({'subject': subject}) mail.content_subtype = 'html' mail.dynamic_template_data = dynamic_template_data mail.template_id = dynamic_template_id if attachment: attachment.open() mail.attach(basename(attachment.name), attachment.read(), guess_type(attachment.name)[0]) attachment.close() return mail.send(fail_silently=False) then my test is something like this: f = open('tests/test.pdf', 'rb') user.pdf.save('test.pdf', File(f)) f.close() send_pdf_mail(user) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to[0], user.email) But when I try to check if there are attachment via: print(mail.outbox[0].attachments) It returns an empty list so I'm not sure why but I tested the code and I can confirm that this indeed includes an attachment when sending an e-mail. -
Django wizard forms and dynamic formset creation
Usually, in a wizard, we declare forms or formsets in static way, for example with something like: form_class=formset_factory(MyForm, min_num=1, extra=5) # let's say this is step '4' But now, what if I need data from step 3, to know how to define the min_num or extra value for the formset of step 4? I was thinking of doing such thing in the get_form() method: def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) # .... elif step == '4': step3_data = self.storage.get_step_data('3') # ... here I would parse step 3 data, to be able to define: computed_step_4_min_num = 5 computed_step_4_extra = 10 # And here I would need to call formset_factory(min_num=computed_step_4_min_num, extra=computed_step_4_extra), # but how? This is obviously not the right place for this call. While it's easy to edit form fields attributes in the get_form() method, I did not find a way to define the right number of forms of a formset, in a dynamic way. I read documentation but I could have missed it. Thanks for your help. -
Can i make HTML forms in Django without using django forms API and Model Forms
If yes, what the pros and corns if no, what the pros and corns Actually, I want to build HTML forms without the Django Form API and ModelForm -
Creating Two Custom Singin Forms using django_allauth
I am creating a small system that has two users, both of these users need singup forms. To allow social accounts and ease of use i have used django_allauth. But i ran into a problem of creating two custom signin forms with different fields. i have used multiple stackoverflow answers but unfortunately none have helped if anything they are now adding to the confusion ... Multiple user type sign up with django-allauth Multiple signup, registration forms using django-allauth I find it hard to believe that this is not a use case that comes up a lot, someone must have done this before. My current code has 2 custom signup forms, 2 custom sign-up views and two custom URLs where the forms should be rendered. But they are both using the same form and I have no idea why. can anyone shed any light on the situation? from .models import GraduateUserProfile from django import forms from allauth.account.forms import SignupForm import datetime def year_choices(): return [(r, r) for r in range(2015, datetime.date.today().year + 1)] def current_year(): return datetime.date.today().year class GraduateUserSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(GraduateUserSignupForm, self).__init__(*args, **kwargs) self.fields['first_name'] = forms.CharField(required=True) self.fields['last_name'] = forms.CharField(required=True) self.fields['phone_number'] = forms.CharField(required=True) self.fields['degree_course_name'] = forms.CharField(required=True) self.fields['graduation_year'] = forms.TypedChoiceField(coerce=int, …