Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx redirecting subdomain calls to a different VPS
I have a site that has been up and running for awhile. I use an nginx proxy to point at my Django app inside of some Docker containers. I want to add a subdomain of "test" to point at a different DigitalOcean droplet, so that I can run pre-production code. On the main domain, I have an A record set for test.example.com to the secondary VPS. I also have an A record for www.example.com for the main VPS. However, whenever I type in http://test.example.com it does a hard 301 redirect back to https://example.com. I have to imagine there is something in my main nginx.conf, but I can't figure it out. My nginx.conf for the 1st main server (www.example.com) is: server { listen 80; server_name example.com www.example.com; return 301 https://example.com$request_uri; } server { listen 80; server_name test.example.com; } server { listen 443; server_name example; charset utf-8; ssl on; ssl_certificate /etc/nginx/example_com_cert_chain.crt; ssl_certificate_key /etc/nginx/example.key; client_max_body_size 4G; location ~ /input.php$ { return 301 http://example.com/$1; } location /media { alias /code/media/; } location /static { alias /code/static/; } location ~ /.git/ { deny all; } location ~ /cgi/ { deny all; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For … -
502 bad gateway django elastic beanstalk
I got the django app deployed with elastic beanstalk on aws, I setup postgresql for it as well to work with one on aws. Unfortunately, following https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I am getting 502 bad gateway after eb open I'm not really getting any errors, my app runs on local. I'm using the debug server, I also managed to run it on waitress. I was reading the oceans of info online and the only thing I can think of - do I need to actually deploy to a production server locally or can I just use EC2 for that? I'm learning about AWS as I go, so sorry if I'm not understanding something here :) Thank you! -
Capture values for dinamic inputs in Django
Currently I´m working in a LMS based on chamilo with Django. Now, I´m facing a problem with the form from quiz exercises, because not all exercises have the same number of questions. My problem is how to get the data. Here is my actual code forms.py class Ejercicios(forms.Form): c_id = forms.CharField() lp_id = forms.CharField() item_id = forms.CharField() item_viewId = forms.CharField() exe_id = forms.CharField() time = forms.CharField() total = forms.CharField() views.py (main part for the forms) def post(self, request, *args, **kwargs): print(request) try: form = Ejercicios(request.POST) if request.method == 'POST': if form.is_valid(): user_id = self.request.session.get('user_id') username = self.request.session.get('username') apiKey = self.request.session.get('apiKeyUser') c_id = form.cleaned_data.get("c_id") lp_id = form.cleaned_data.get("lp_id") itemId = form.cleaned_data.get("item_id") item_viewId = form.cleaned_data.get("item_viewId") exe_id = form.cleaned_data.get("exe_id") time = form.cleaned_data.get("time") total = 0 return redirect('core:home') else: return redirect('core:home') except: return redirect('core:home') My main problem is how to fill the variable total with different number of values because the exercises have different number of questions Template $('#quiz_start').click(function () { $('#quiz_start').hide(); var sec = 0; function pad(val) { return val > 9 ? val : "0" + val; } setInterval( function(){ $("#time").attr("value", pad(++sec)); }, 1000); $('#exercise_form').append( '<input type="hidden" name="c_id" value="'+link['c_id']+'">' + '<input type="hidden" name="lp_id" value="'+link['lp_id']+'">' + '<input type="hidden" name="item_id" value="'+link['lp_item_id']+'">' + '<input type="hidden" name="item_viewId" … -
Django-allauth and cookiecutter add buttons for social acc login
By default django allauth shows added social media login options in a list: <div class="socialaccount_ballot"> <ul class="socialaccount_providers"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </ul> <div class="login-or">{% trans 'or' %}</div> </div> I want to add good looking buttons for google/twitter/etc. but I cannot find provider_list.html anywhere in my project. I know that this template exist in allauth's repo Does anyone know how I add these buttons? -
Django import-export ManyToManyWidget fields appearing blank in export
I have the following models and M2M relationships: class Market(models.Model): marketname = models.CharField(max_length=500) market_id = models.CharField(max_length=100, blank=True) def __str__(self): return self.marketname class TeamMember(models.Model): firstname = models.CharField(max_length=100, default= "First Name") lastname = models.CharField(max_length=100, default= "Last Name") email = models.EmailField(max_length=254) def __str__(self): return self.email class EmailReport(models.Model): name = models.CharField(max_length=1000) recipients = models.ManyToManyField('team.TeamMember', related_name="teamrecipients") frequency = models.CharField(max_length=1000, blank= True) markets = models.ManyToManyField('opportunities.Market', blank=True) def __str__(self): return self.name The following is my admin.py for the EmailReport registration. class EmailReportResource(resources.ModelResource): recipients = fields.Field(widget=ManyToManyWidget(TeamMember, field="email")) markets = fields.Field(widget=ManyToManyWidget(Market, field='marketname')) class Meta: model = EmailReport fields = ['id', 'name', 'recipients', 'markets'] class EmailReportAdmin(ImportExportModelAdmin): resource_class = EmailReportResource admin.site.register(EmailReport, EmailReportAdmin) I am able to export- and all char fields export normally- however, my M2M fields all appear blank. Can anyone please point out my mistake? Thank you so much! -
Filtering dates in a calendar in Django,
I am trying to filter my object in such a way that the link to it displays on the correct date displayed in the calendar, I am using a date field in my model, the problem is that in an earlier model where I used DataTimeFiled everything works correctly and the link to the object details displays on a given date in the calendar. this is my models.py file class HomeworkersEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_day = models.DateField(auto_now_add=False, auto_now=False, auto_created=False) end_day = models.DateField(auto_now_add=False, auto_now=False, auto_created=False) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('sytoapp:homeworkers_event-detail', args=(self.id,)) @property def get_html_url(self): url = reverse('sytoapp:homeworkers_event-detail', args=(self.id,)) return f'<a href="{url}"> {self.user} </a>' class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField(auto_now_add=False, auto_now=False, auto_created=False) end_time = models.DateTimeField(auto_now_add=False, auto_now=False, auto_created=False) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('sytoapp:event-detail', args=(self.id,)) @property def get_html_url(self): url = reverse('sytoapp:event-detail', args=(self.id,)) return f'<a href="{url}"> {self.user} </a>' Calendar displaying events where I used DateTimeFiled works flawlessly Here is the code on how to filter it in the calendar def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' def formatmonth(self, request, withyear=True, ): current_user … -
How to add auto number column in the tables?
I am learning Django and my first project I am doing a To do application. My idea is that I put the content from the database(models.py) into tables in html ,but also on the side of the table I wanna put a auto number column that which is added in the number of items in table. I tried to do that function with count() function in views.py, but the problem is that when i add a new item in the table the number item column is the same in the number in first row, and second, etc... This is a screenshot of the page to understand it easily This is views.py: from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from .models import * from .models import __str__ # Create your views here. def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) def add_todo(request): current_date = timezone.now() new_item= todo(content = request.POST["content"]) new_item.save() return redirect('/') def delete_todo(request, todo_id): item_to_delete = todo.objects.get(id=todo_id) item_to_delete.delete() return redirect('/') This is home.html: <div class="container"> <div class="jumbotron"> <div style="background-color: #0d2e72;" class="card"> <div class="card-header" style="border: none;"> <p style="font-size: 25px; text-align: center; color: white;">TASKS TO DO</p> </div> … -
Multiple ChartJS scripts are not working at the same time
When I am using a Single Chart in ChartJS, it works well but whenever I use more than a Chart, only the last chart works, the others don't longer display. I am not sure of what the problem might actually be as I have checked the console and terminal if I would get any error or so so as to debuy it. index.html {% block content %} <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> # The Script for the first chart <script> // Driver Status var config = { type: 'doughnut', data: { datasets: [{ data: [{{pending}},{{hired}},{{terminated}}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', ], label: 'Population' }], labels: ['pending', 'hired', 'terminated'] }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> # The Script for the Second chart <script> // EVR STATUS var config2 = { type: 'doughnut', data: { datasets: [{ data: [{{done}},{{partial}},{{not_started}}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, … -
How to send CSV to Django Usaing API REST?
How can I send a 220,000-line CSV file to Django using the Rest Framework API? Thank you. -
On Windows 10 Django is not installing properly under the project folder - unable to find manage.py
I am a new developer. I'm following instructions from to Django for Beginners book. When I run C:\Users\User\Desktop\HelloWorld>pipenv install django~=3.1.0 The message I got: Installation Succeeded When I typed C:\Users\User\Desktop\HelloWorld>pipenv shell I got the following result: (User-jBUq-HwN) C:\Users\User> However, in the book the result looks like: (helloworld) $ From the book on page 34. When I try to run the server: (User-jBUq-HwN) C:\Users\User\Desktop\HelloWorld>python manage.py runserver C:\Users\User\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory Any reasons why it can't find manage.py? -
Only show objects where the total ammounts of rows of a subquery is less than a certain value in django queryset
I'm trying to generate a list of a certain model where only the instances from another query. So Here's my models: class Waiter(models.Model): id = models.AutoField(primary_key=True) waiter = models.CharField(max_length=200) class Service(models.Model): id = models.AutoField(primary_key=True) arrival = models.DateTimeField(auto_now_add=True) exit = models.DateTimeField(null=True, blank=True) waiter = models.ForeignKey('Waiter', on_delete=models.CASCADE) article = models.ForeignKey('Table', on_delete=models.CASCADE) total_ammount= models.DecimalField(max_digits=15, decimal_places=2) class Table(models.Model): id = models.AutoField(primary_key=True) table_no = models.CharField(max_length=200) The idea is there can only be four waiters assigned at a service at a single time. How can I filter the results of waiters based on weather they have less than four services at a single time? Thank you in advance :) -
How to update context in an inherited base class?
I am trying to reuse context code in my Django views but the context variable goes missing when I try to move the code around. Here is one that works, with the get_context_data in the class itself: # Works. Views that inherit from FirstContentCreateView # have 'smurf' in the context class FirstContentCreateView(CreateView): model = None form_class = None template_name = None # ..... other stuff here .... def get_context_data(self, **kwargs): """ An override of the default get_context_data method that adds a smurf to the context. """ context = { 'smurf': "Jokey Smurf" } context.update(kwargs) return super().get_context_data(**context) class SmurfyView(FirstContentCreateView): # Works! This view has 'smurf' in the context pass But if I move get_context_data to another base view and dual class, that does not work: class BaseSmurfView(View): """ Moved get_context_data from FirstContentCreateView into here so I can use it elsewhere. That's the only change. """ def get_context_data(self, **kwargs): """ An override of the default get_context_data method that adds a smurf to the context. """ context = { 'smurf': "Jokey Smurf" } context.update(kwargs) return super().get_context_data(**context) class SecondContentCreateView(CreateView, BaseSmurfView): """ This is just like FirstContentCreateView, but instead of having get_context_data in here, it is now coming from BaseSmurfView. Supposedly. """ model = None … -
Django admin page not showing contents in admin_app_description.html
I'm working on upgrading an existing Django project, the source code includes files like application/templates/auth/admin_app_description.html, the contents of which will show up on Django's admin page as introductions beside the item. However, after upgrading to Python 3, the admin page no longer shows the introductions although the admin_app_description.html files still exist in repository. I hope to show the contents, and any hints will be highly appreciated. -
Django Context rendering - django.template.base.VariableDoesNotExist: Failed lookup for key
I am facing an issue to render Django Context Dictionary. I have tried multiple options but could not able to render the context. In the debug logs I am seeing error for "VariableDoesNotExit". Here is my sample code: Views.py def KpiEngine(request): if request.method == "POST": form = KpiEngineForm(request.POST) if form.is_valid(): report_group = form.cleaned_data['report_group'] domain = form.cleaned_data['domain'] report_type = form.cleaned_data['report_type'] report_sub_type = form.cleaned_data['sub_report_type'] report_period = form.cleaned_data['report_period'] my_context = {"a":1} return render(request,'core_pmapp/kpitool.html',{'form':form},my_context) else: my_context = {"a":1} return render(request,'core_pmapp/kpitool.html',{'form':form},my_context) else: context = {} form = KpiEngineForm() return render(request,'core_pmapp/kpitool.html',{'form':form}) Here is my template: <div class="container p-0"> <div class="card bg-light"> <div class="card-header p-4"> KPI Engine</div> {% if a == 1 %} <div class="card-body h-200 col-5 p-4 ml-2"> <p> Report Generation is in progress</p> <p> It might take few minutes .....</p> </div> {% else %} <div class="card-body col-5 p-4 ml-2"> <form action="" method="GET,POST"> {% csrf_token %} <div class="row"> <div class="col-4 p-2"> Report Group </div> <div class="col-8 p-2"> {{ form.report_group }} </div> <div class="col-4 p-2"> Domain </div> <div class="col-8 p-2"> {{ form.domain }} </div> <div class="col-4 p-2"> Report Type </div> <div class="col-8 p-2"> {{ form.report_type }} </div> <div class="col-4 p-2"> Report Sub Type </div> <div class="col-8 p-2"> {{ form.sub_report_type }} </div> <div class="col-4 p-2"> Report Period </div> … -
How Default random image in ImageField
I have a Post model, and I want to add a random photo from the static directory when creating a new post. In the static directory, I have a folder with images. And a media folder where upload images. ├───media | └───post_photo | ├───static | └───random_post_images └───img1.jpg └───img2.jpg .... I have a function that takes a random image from a random_post_images and puts a default photo of the post def rand_img(): lst_arr = os.listdir(path = 'static/random_post_images') return 'random_post_images/' + random.choice(lst_arr) class Profile(models.Model): .... image = models.ImageField(default=rand_img, upload_to='post_photo') .... settings.py file STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') main urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I open a photo in admin django: Page dont find media/..... Can u help me?? -
Django - pass a list of results when querying using filter
In my FollowingPageView function, I'm trying to filter posts based on the logged in user's list of user's he/she is following. You'll see the Profile model has a "following" field that captures the names of users the Profile owner is following. What I'm trying to do in my view is capture these names of the users in "following" then pass them to Post.objects.filter(created_by=user_list), but I will only get the last user in that list in this case. How can I iterate over the "user_list" Queryset and pass that to Post.objects.filter in order to return the posts from each user in that list? In this case, I should have two users in the Queryset [<User: winter>, <User: daisy>]. models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) website = models.CharField(max_length=225, null=True, blank=True) follower = models.ManyToManyField(User, blank=True, related_name="followed_user") # user following this profile following = models.ManyToManyField(User, blank=True, related_name="following_user") # profile user that follows this profile def __str__(self): return f"{self.user}'s' profile id is {self.id}" def following_users(self): for username in self.following: return username def get_absolute_url(self): return reverse("network:profile-detail", args=[str(self.id)]) class Post(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50) body = models.TextField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name="posts") def __str__(self): return … -
Problem with delete functional for comments on djnago
I am confused. I made a button delete function for posts and it works, after I duplicated it for comments and I get an error Reverse for 'comments' with no arguments not found. 1 pattern(s) tried: ['posts/comments/(?P[0-9]+)/$'] Can anyone explain what the problem is, I have reviewed it many times and do not see the difference views.py def delete_post(request, id): delete_post = get_object_or_404(Article, id=id) if request.method == 'POST': delete_post.delete() return redirect('/my_account') context = { 'delete_post': delete_post} return render(request, 'posts/delete_post.html', context) def delete_com(request, id): delete_com = get_object_or_404(Comments, id=id) if request.method == 'POST': delete_com.delete() return redirect('/comments') context = { 'delete_com': delete_com} return render(request, 'posts/delete_com.html', context) ursl.py path('delete_post/<int:id>/', views.delete_post, name='delete_post'), path('delete_com/<int:id>/', views.delete_com, name='delete_com'), html <form action="{% url 'delete_com' %}" method="POST"> <p><h5>are you sure to delete {{delete_com|safe}}?</h5></p> <input type="submit" value="Yes" /> {% csrf_token %} <a href="{% url 'comments' %}">cancel</a> </form> <form action="{% url 'delete_post' delete_post.id %}" method="POST"> <p><h5>are you sure to delete {{delete_post|safe}}?</h5></p> <input type="submit" value="Yes" /> {% csrf_token %} <a href="{% url 'account' %}">cancel</a> </form> -
Is it possible to create a dynamic form (add new fields in runtime) with CreateView in Django?
I'm building a form that allows the user to add the different features of a product, and I also want it to be a dynamic form so the user can put whatever categories he want in it. Something like, Form: Name: shirt Description: ... Categorie1: Color: Red Categorie2: Sleeve: short Categorie3: ... Add new categorie Save The problem is that I'm using CreateView for this page and don't know how to convert my form into a dynamic one. There's a way for doing this? or it's better to make it with a function view instead of CreateView? Here's my code, view: class ProductCreateView(CreateView): template_name = "product_create.html" form_class = ProductModelForm queryset = Product.objects.all() def form_valid(self, form): return super().form_valid(form) model: class Product(models.Model): title = models.CharField(max_length = 120) description = models.TextField() image = models.FileField(upload_to="products/images/") price = models.IntegerField() active = models.BooleanField(default = True) categorie = models.CharField(max_lenght = 50, default = '') def get_absolute_url(self): return reverse("products:product-detail", kwargs={"id": self.id}) def delete(self, *args, **kwargs): self.image.delete() super().delete(*args,**kwargs) form: class ProductModelForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'image', 'price', 'active', 'categorie' ] Thank you in advance! -
My django paginator does not return any output
i have two paginators: the first one is in my articles page and the second is in a page that classifies the articles based on their categories. the first one is working well but when I go to articles for a specified category I see my pageinator is not working. I appreciate in advance; #views.py from django.core.paginator import Paginator from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from .models import Article, Category # Create your views here. def home(request): context = { "articles": Article.objects.published() } return render(request, 'website/home.html', context) def detail(request, slug): context = { "article": get_object_or_404(Article.objects.published(), slug=slug) } return render(request, 'website/detail.html', context) def article(request, page=1): articles_list = Article.objects.published() paginator = Paginator(articles_list, 1) articles = paginator.get_page(page) context = { "articles": articles, "category": Category.objects.filter(status=True) } return render(request, 'website/article.html', context) def category(request, slug, page_cat=1): cat = get_object_or_404(Category, slug=slug, status=True) articles_cat = cat.articles.filter(status='Published') paginator_cat = Paginator(articles_cat, 1) cat_articles = paginator_cat.get_page(page_cat) context = { "category": cat_articles } return render(request, 'website/category.html', context) ######My category.html file <div class="blog-pagination"> <ul class="justify-content-center"> {% if cat_articles.has_previous %} <li><a href="{% url 'website:category' cat_articles.previous_page_number %}"> <i class="icofont-rounded-left" ></i></a></li> {% endif %} <li><a href="#">1</a></li> <li class="#"><a href="#">2</a></li> <li><a href="#">3</a></li> {% if cat_articles.has_next %} <li><a href="{% url 'website:category' cat_articles.next_page_number %}"> … -
Template results of modelformset_factory to separate forms:
When I use modelformset_factory it renders a page with all fields together and with the same name. However, I'd like to have each repeated form with a different title. This is how my page looks when the form is repeated two times (the form has three fields): Instead, I'd like it to look like this (sorry for the shabby edit): So, the idea is to create a "box" per form set with a title that changes depending on the number of form sets used. The code of this app: views from django.shortcuts import render from django.shortcuts import redirect from parameters.models import Parameters from .forms import RawAttributesForm from .models import Attributes from django.forms import modelformset_factory #modelformset dependiendo del número de atributos def attributes_create_view(request): param = Parameters.objects.latest('id') atrib = modelformset_factory(Attributes, fields=('attribute_code', 'attribute_name', 'attribute_levels'), extra=param.atr_n, widgets={}) form = atrib(queryset=Attributes.objects.none()) if request.method == "POST": form_atrib = form(request.POST, request.FILES) print(form_atrib) if form_atrib.is_valid(): form_atrib.save() return redirect('../home') context = { "param" : param, "form": form } return render(request, "atrib_set.html", context) models from django.db import models # Create your models here. class Attributes(models.Model): attribute_code = models.IntegerField(default=None) attribute_name = models.CharField(max_length=50) attribute_levels = models.IntegerField(default=None) forms from django import forms from .models import Attributes from extra_views import FormSetView from django.utils.translation import … -
how to change django crispy forms login error?
How can I change the error that django crispy forms displays when a user fails to enter username and password? This is the image that currently appears to me when I go to make a wrong login, I would like to replace the internal writing and in addition I would like to center it This is my login view This is forms.py file: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import MyUser ######### FORM PER LA REGISTRAZIONE DELL'UTENTE FINALE ######### class FormRegistrazione(UserCreationForm): username = forms.CharField(max_length=30, label="Nome Utente", required=True, widget=forms.TextInput(attrs={'placeholder': 'Pablitos123', 'class': 'text-left'})) first_name = forms.CharField(max_length=30, label="Nome", required=True, widget=forms.TextInput(attrs={'placeholder': 'Mario', 'class': 'text-left'})) last_name = forms.CharField(max_length=30, label="Cognome", required=True, widget=forms.TextInput(attrs={'placeholder': 'Rossi', 'class': 'text-left'})) email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput(attrs={'placeholder': 'esempio@esempio.it', 'class': 'text-left'})) password1 = forms.CharField(max_length=30, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Inserisci la tua password', 'class': 'text-left'})) password2 = forms.CharField(max_length=30, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Inserisci nuovamente la tua password', 'class': 'text-left'})) indirizzo = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Via/Piazza Roma, 25', 'class': 'text-left'})) citta = forms.CharField(max_length=50, label="Città", required=True, widget=forms.TextInput(attrs={'placeholder': 'Roma', 'class': 'text-left'})) CAP = forms.CharField(max_length=5, label="CAP", required=True, widget=forms.TextInput(attrs={'placeholder': '56123', 'class': 'text-left'})) ######### FUNZIONE PER CANCELLARE GLI help_text DAL FORM ######### def __init__(self, *args, **kwargs): super(FormRegistrazione, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None ######### CAMPI DEL … -
Sort By Descending Date Django
models.py class Record(models.Model): date = models.DateTimeField() .... class Balance(models.Model): record = models.ForeignKey(Record) .... views.py balances = Balance.objects.filter(record__date__week=current_week).order_by("-record") this will order the balance entries based on when the records were created not on the date from Record. How can I sort these queries for Balance based on Record Date. -
Django dynamic creation of table in database
I'm trying to find a way to dynamically create table in database (SQLite3). What I'm trying to do is to get file from user and based on rows in file create table with the same amount of columns. Everything I found is from 6-10 years so it doesn't work anymore. -
Generic Formset with M2M Field not saving Entry correctly
After a long struggle I found out how to design my code but it is still faulty. The model Form is has a (Sub)Formset that is created over modelformset_factory. SinglePrescriptionFormset = modelformset_factory( PrescriptionLine, form=PrescriptionLineForm, fields='__all__', extra=0, can_delete=True) The model Form itself is as follows: class PrescriptionForm(forms.ModelForm): class Meta: model = Prescription exclude = ['handed_out', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('patient'), Field('note'), HTML('<hr class="style2">'), Fieldset('Drugs', Formset('line_prescription')), HTML('<hr class="style1">'), ButtonHolder(Submit('submit', 'save')), ) ) def clean(self, *args, **kwargs): return super().clean(*args, **kwargs) and the Create View is designed like this: class PrescriptionCreate(generic.CreateView): model = Prescription template_name = 'doc_aide/write_prescription4.html' form_class = PrescriptionForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: context['line_prescription'] = SinglePrescriptionFormset( self.request.POST) else: context['line_prescription'] = SinglePrescriptionFormset() context['form'].fields['patient'].initial = Patient.objects.get( pk=self.kwargs['patient']) return context def form_valid(self, form): context = self.get_context_data() prescriptionlines = context['line_prescription'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if prescriptionlines.is_valid(): prescriptionlines.instance = self.object prescriptionlines.save() return super().form_valid(form) def form_invalid(self, form): print('Form invalid') print(form.errors) return super().form_invalid(form) def get_success_url(self): return reverse('doc_aide:prescription_detail', kwargs={'pk': self.object.pk}) The problem now is that when I save one prescription the subformset data is changed from previous saves. I need … -
Uploading multiple webcam images to Django servers
I am creating a form, which takes the following data from the user: 'name', 'email', 'mobile_no', 'photo', 'id_proof'. Out of these, the simple text type data can easily be sent over the network to the server using POST method.However, the fields, photo and id_proof will be uploading images, and these images will be captured by the webcam of the user. A normal Form could be used, but the problem is that 1 page can have n number of such forms.Eg. if a page has 4 forms of such type, there will be 8 images to be uploaded. Hence, I can't even send the data over the server and then convert it to a file, as it will simply reduce the efficiency of the system as n increases.How can I convert the images into a file, and then send it over so that my Django application saves these images? I referred to this question: How to send captured webcam image and save to server via input field, but this provides solution only for sending a single image file and nothing else.