Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make a multiple type users in django?
I am Building an app for a Charity and I need to make a system with different forms for six different user types. the six types are : patients(with the ability to work or not), founders & managers, regular users, volunteers, Financial & work sponsors. patients form has : name, the date of injury, injury percentage, age, gender and some other stuff other users have unique fields like patients for themselves. for now I just want to make the forms and add users from the admin page. should I make six individual forms and inherit from user creation form? if so, how to separate them in the admin page? Can I use one authentication for all of them? I am so confused! could you please help me to make a multiple user sign up forms! I have no idea about the code!!! thanks for the responses -
I have a Jupyter notebook / SciKit model for NBA predictions I want to publish online
Honestly not sure how to frame this as effectively as possible. I built an NBA prediction model that outputs results of matches as well as probabilities of victory. Basically, it inputs certain stats about both teams and outputs the likelihood of each team winning. I built this on a local Jupyter Notebook, and I run one notebook to compile today's schedule and stats into a csv, and turn this csv in a panda df and run it through my model. I know the NBA season has been postponed but I wanted to build this website anyways, where basically I wanted to publish my predictions for friends and others to see. There are 2 ways I see this being done but correct me if I'm wrong: 1. Where I run the model locally and update a database with these predictions and my website will pull the data from this database. 2. Ideally, I would like the model to be hosted online and run automatically every day and execute the scripts that I would run locally to compile daily predictions without my input. Basically I am looking for help on what type of infrastructure I should actually use and what I need … -
Django queryset with partial nested lists
I have two models : class Project(models.Model): name = models.CharField(max_length=255) client = models.ForeignKey(client, on_delete=models.CASCADE) class Client(model.Model): name = models.CharFiled(max_length=255) Assume my data is : Client table - [{id:1,name:client1}, {id:2, name:client2} Project table - [{id:1, name: project1, client:1}, {id:2, name: project2, client:1}, {id:3, name: projects, client:2}] a Client.objects.all() QuerySet will return two objects, client1 and client2 which client 1 has 2 projects and client2 have only 1. I am trying to order a QuerySet by a project name, but per Client object. doing so this way : clients = Client.objects.order_by("project__name") as Expected the result will provide 3 clients object, 2 for client1 and one for client 2. However, my problem is that each client object contains all the projects and not only the specific ordered one. I am trying to filter for each client object, even if the client is the same only the requested ordered projects. I can theoretically do that manually after receiving the queryset, but I assume there is a way to do it because the request does know which project specifically cause the creation of a new row in the queryset. -
How to run the packaged application from django's polls tutorial?
https://docs.djangoproject.com/en/3.0/intro/reusable-apps/ After it's packaged, the documentation says that 'With luck, your Django project should now work correctly again. Run the server again to confirm this.'. In this tutorial, to start the server, do this: python manage.py runserver But after this is packaged and installed to the user directory, it has been moved out of the project, and 'manage.py' isn't available. How to run the server and test the newly installed package? This may be a silly question, but the doc does lack a key sentence to tell how to start the server to run the installed package. -
Override Django's ManyToManyField with Custom fields and Access It
I have created ManyToManyPatchedField by overriding class ManyToManyField. In the new class, I have added a new column called created (Datetime Field). I did this by overriding function contribute_to_class and create_many_to_many_intermediary_model to add a new column created. The patched Django function looks like this. def create_many_to_many_intermediary_patched_model(field, klass): """ Override function create_many_to_many_intermediary_model in django.db.models.fields.related to add new columns created and foreign key to Comments table """ from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = '%s_%s' % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = 'to_%s' % to from_ = 'from_%s' % from_ meta = type(str('Meta'), (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': (from_, to), 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, 'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to}, 'apps': field.model._meta.apps, }) # Construct and return the new class. return type(str(name), (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey( klass, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), # Custom created field 'created': models.DateTimeField(auto_now_add=True) }) When I try to access the row using model1.model2.through.objects.all().values(), it returns … -
django MultiValueDictKeyError and RuntimeError in saving a form's data in database
I am trying it very hard but I didn't find what I am missing. I have made a form that contains fields like the first name, last name, address, city, state, zip and one Image file from the user. But I am getting this error when I was trying to post data by views. MultiValueDictKeyError at /submit_your_task 'image' Request Method: POST Request URL: http://127.0.0.1:8000/submit_your_task Django Version: 2.2.4 Exception Type: MultiValueDictKeyError Exception Value: 'image' and this is my views.py for that form def submit_your_task(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] address = request.POST['address'] phone = request.POST['phone'] city = request.POST['city'] state = request.POST['state'] zip = request.POST['zip'] image = request.FILES['image'] fs = FileSystemStorage() file = fs.save(image.name, image) url = fs.url(file) submit_task = SubmitYourTask(first_name=first_name, last_name=last_name, address=address, phone=phone, city=city, state=state, zip=zip, image=url) submit_task.save() return render(request, 'submit_task.html') and this is urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home-page'), path('about/', views.about_us, name='about'), path('signup/', views.signup, name='signup'), path('submit_your_task/', views.submit_your_task, name='submit_your_task'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And when I put the slash after 'submit_your_task' it gives me RuntimeError RuntimeError at /submit_your_task You called this URL via POST, but the … -
Different lines does not appear in context in Django
If I have code like hello_worlds = 'hello Earth \n hello Mars' context = { 'hellos':hello_worlds } return render(request, 'home.html', context) and home.html is {{hellos}} It displays as hello Earth hello Mars not hello Earth hello Mars I'm using Django 2.1.5 and python 3.8 is there a way to have it display like the second one? -
jQuery String Matching Django Generated String
I have a script that highlights certain blocks of text on a page generated by Django. The script works fine until the block of text contains an apostrophe. It won't match in that case. I've tried various combinations of filters, escaping, etc. but can't seem to get it working. Below is my code. jQuery in template: <script> $(document).ready(function(){ // Displays highlights if any exist {% for highlight in agenda.highlights.all %} $( "div.card-body div.mb-3:contains('{{ agenda.agenda_text|hl_slice:highlight }}')" ).css( "background-color", "#FFFF00" ).attr("id", "{{ highlight.id }}"); {% endfor %} }); </script> Django "hl_slice" custom filter @register.filter @stringfilter def hl_slice(agenda_text, hl): """ Returns the highlighted portion of the agenda text. """ try: hl_text = strip_tags(agenda_text[hl.start:hl.end]) return hl_text except (ValueError, TypeError): return hl # Fail silently. Text blocks in template (generates HTML divs containing text) {{ agenda.agenda_text|safe }} Here is an example of text that breaks the match: "K. 20-378 Notification of City Manager's and Assistant City Manager's execution of Professional Consultant Agreements and Amendments to an Agreement, as well as Public Construction Contracts not subject to the Competitive Bid Act, with a Contract values of less than $25,000" If I take out the apostrophes, the text will match, so I know it has something to … -
Center bootstrap toggle navbar
**Hi, I have struggled all day to make my navbar center on the page without any luck. I have used bootstrap to create the navbar. I would be extremely happy if someone could help me out.** URL <!DOCTYPE html> <html lang="en"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- Required meta tags --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-info d-flex justify-content-center"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse h3" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> </div> </nav> <div class="jumbotron jumbotron-fluid bg-info text-white text-center""> <div class="container"> <h1 class="display-4">c.magelssen</h1> <p class="lead">A resource on psychology, teaching, skiing and coding.</p> </div> </div> </div> -
Pass data from template to django's views.py
Right now i'm working on the pagination of the data table at my django's project. And i'm trying to let the user put how many registers are displayed per page, but i'm having troubles passing the number at the selector that i'm using to views.py (where the pagination is), my question is: How to pass the selected number to views.py so it updates the registers? this is my code: Template's Selector: <form action="" method="POST"> <select class="selector" id="estado" name="estado" onchange="post()" style="border-color: #C9C9C9; color:black; height: 25px; width:100px; position:absolute; margin-top:-32px; margin-left:230px;"> <option selected style="color:black;">5</option> <option style="color:black;">10</option> <option style="color:black;">25</option> <option style="color:black;">50</option> <option style="color:black;">100</option> </select> </form> Views.py: if request.method == 'POST': inicial = { 'paginas' : 5, } num = paginaForm(initial = inicial).fields['paginas'] else: num = 5 riesgos = Riesgos.objects.all() #Paginación paginator = Paginator(riesgos, num) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] context = {'riesgos':riesgos, 'page_range':page_range, 'items':items} return render(request,'restapi/listar_riesgo.html', context) Models.py class Paginas(models.Model): paginas = models.IntegerField(primary_key= True) Forms.py: class paginaForm(forms.ModelForm): class Meta: … -
Static files path loading inconsistency with bootstrap files in Django
{% load static %} <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"/> <link rel="stylesheet" href="{% static "pages/css/main.css" %}"/> <!-- body of page --> <script src="{% static "pages/js/jquery-3.4.1.min.js" %}"></script> <script src="{% static "js/bootstrap.bundle.min.js" %}"></script> <script src="{% static "pages/js/all.js" %}"></script> <script src="{% static "pages/js/bootstrap.js" %}"></script> <script src="{% static "pages/js/main.js" %}"></script> This is in django, the first line <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"/> and <script src="{% static "js/bootstrap.bundle.min.js" %}"></script> reference starts from the Child folder, where as all the other static files are loaded from the App folder; which is the parent. Can someone please elaborate this inconsistency in loading static files. -
Dynamic Tab names in Tabholder in Django-crispy-forms
I wondering is there any chance to use "dynamic" names for Tabs. Like in next example Tab names are hardcoded 'First Tab' and 'Second Tab' in ModelForm. I have dynamic titles (head1, 2 etc.) for every tabs and I am using values from database for titles. I like to use same text dynamically in tab names. Tab('First Tab', HTML("""<h4>{{ head1.0 }}</h4>"""), 'field_name_1', Div('field_name_2') ), Tab('Second Tab', HTML("""<h4>{{ head2.0 }}</h4>"""), Field('field_name_3', css_class="extra") ) I would like to add same dynamic title texts to tab names also like in next example, but I have not found solutions. Tab({{ head1.0 }}, HTML("""<h4>{{ head1.0 }}</h4>"""), 'field_name_1', Div('field_name_2') ), Tab({{ head2.0 }}, HTML("""<h4>{{ head2.0 }}</h4>"""), Field('field_name_3', css_class="extra") ) -
Amazon S3 Image not displaying
I'm implementing the Amazon S3 on an application I am about to deploy. I have this challenge. When I upload an image, it doesn't display on the site but if I open the image in a new tab, it displays properly. Please what do I do? This is my models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) # img = Image.open(self.image.path) # if img.height > 300 or img.width > 300: # output_size = (300, 300) # img.thumbnail(output_size) # img.save(self.image.path) This is what I added in the settings.py file AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '********' AWS_STORAGE_BUCKET_NAME = '********' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' This is my views.py file def profile(request): #if request.user.is_verified(): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) And this is the profile.html template {% … -
Can'not launch django installed inside docker
I am using Docker to launch my app which imports django. I want to do it inside my git repository. My Dockerfile looks like FROM python:3 WORKDIR /configurator CMD virtualenv -p python3.8 venv CMD . venv/bin/activate CMD pip install -U setuptools pip CMD pip install django COPY . /configurator/ CMD cd cconfigurator/ ENTRYPOINT /configurator/cconfigurator/manage.py runserver 8000 And I see an error: docker run configurator Traceback (most recent call last): File "/configurator/cconfigurator/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/configurator/cconfigurator/manage.py", line 21, in <module> main() File "/configurator/cconfigurator/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? What am I doing wrong? -
Using an external API in Django
I'm trying to use an external API to grab data for my project to show on the template. service.py def get_data(title, url, description, body, datePublished): url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI' params = {"autoCorrect": "true", "pageNumber": "1", "pageSize": "10", "q": "police", "safeSearch": "true" } r = requests.get(url, params=params) data = r.json() article_data = {'data': data['value']} return article_data Then I show it on views.py ... import service class IndexData(TemplateView): def get(self, request): article_data = service.get_data.all() return render(request, 'pages/home.html', article_data) but I'm getting ModuleNotFoundError: No module named 'service' Did i miss something? -
How to build this complex form in Django with multiple models?
How should I build this complex form in Django? In particular, what I would like to accomplish is to be able to send the indented information making clear that it is inside and related to the parent option. In the example, I would like to send the information that the Antivirus within Malware is checked and that Malware - Antivirus has the criticality specified in the dropdown. Malware is from class Theat, Antivirus is from class Control and Malware-Antivirus-High is from class Requirement. And everything while creating a Subcategory. -
Why does my website take so long to load to browser?
So I have added a https to a simple website ( goenigmamusic.com ) built with django and you can only connect to it with a good internet connnection. The ssl certificate was done on aws, as well as the deployment. I have a metro pcs internet connection on my phone, I use it to test my website load time. Whats interesting is that, I can load a website like cartoonnetwork.com with a decent internet connection to my browswer, but goenigmamusic.com can't even load the website to my browswer, but when connected to good wifi? Why? -
Sending user-dependent scheduled emails with celery and django?
I'd like for my web-app to send weekly / monthly emails to the users - how would I limit celery to only send scheduled emails to the users that "opt-in"? I installed django-celery-beat and I can configure a cron job in the admin interface, but not only to specific users -
Getting "Method Not Allowed: /users/update_contact/"
This my javascript function intended to update my database. However, I get two errors: Method Not Allowed: /users/update_contact/" SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data function update_contact (){ url = "{% url 'users:update_contact' %}"; git_profile = prompt("enter git profile name") phone = prompt("enter phone number") email = prompt("enter email address") const contact = { "git_profile" : git_profile, "phone_number" : phone, "email" : email }; var stringify_contact = JSON.stringify(contact); const options = { method: 'POST', body: JSON.parse(stringify_contact), mode: 'same-origin', dataType: 'json', headers : { 'content-Type' : 'application/json', 'X-CSRFToken': csrftoken, } } fetch(url, options) .then(res => res.json()) .then(res => console.log(res)) } -
Django: Display database information to match the form? ValueError: .. didn't return an HttpResponse object. It returned None instead
I am trying to query the database to display results from the form. Once I select the form drop-down fields for my wanted query e.g. Ford C-Max 2019 1.2 Petrol 1500 , from which I coded for now to display results (regardless of Make & Model as I only have one atm) , then instead of showing me the table with matched results I get this error: Request Method: POST Request URL: http://127.0.0.1:8000/data/ Django Version: 3.0.3 Exception Type: ValueError Exception Value: The view app.views.data didn't return an HttpResponse object. It returned None instead. However I do have that result in the database table named ford_cmax (ignore the average & entered columns) average entered year liter fuel mileage 9701 2020-04-08 20:59:45 2019 1.2 Petrol 1500 I did not have this problem before, the table showed all results fine before I did the tweaking for filters. My code: views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import FormView from django.db.models import Q from .models import Average, Query from .forms import QueryForm class QueryMakeModel(FormView): template_name = 'QueryMakeModel.html' success_url = '/data/' form_class = QueryForm def form_valid(self, form): return HttpResponse("Sweet.") def index(request): if request.method == 'POST': FormSite = QueryForm(request.POST) if FormSite.is_valid(): pass … -
Django the fastest way to do Query get list of items in row from table
In my app I need to do fast Query but I don't know which is faster materials = Material.objects.only('name') Or do filter this in view materials = Material.objects.all() And then use for loop to show list of items from 'name' row I think that first is better or there is better way to do this? It cant be done with filter() because it need to show all of fields in this row. -
Pass a file path as a URL parameter in Django
I'm using Django to create a webapp. When a user press on a certain button, it needs to pass a file path as parameter and a string parameter to one of my views. I can't simply use the parameter in the URL since the path contains several '/'. The way I have it setup right now is as follows: parameters.py ''' class FilePathConverter: regex = '^[/]' def to_python(self, value): value=str(value) return value.replace("?", "/") def to_url(self, value): value=str(value) return value.replace("?", "/") urls.py from django.urls import path from . import views from django.contrib import admin from django.views import generic from django.urls import path, register_converter from . import converters, views register_converter(converters.FilePathConverter, 'filepath') urlpatterns = [ path('', views.index, name='webpanel-index'), path('controlserver/<str:server_path>/<str:control>', views.index, name='controlserver'), ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Server from django.contrib.auth.decorators import login_required import subprocess def controlserver(request, server_path, control): if request.POST: subprocess.call(['bash', server_path, control]) return render(request, 'index.html') However, with this method, I get this error: Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$'] -
Problems in multiple page form
I created a function for creating Course object.Form works but i don't know how to create Course object here.How to do that? views.py class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) def done(self, form_list, **kwargs): data = {k: v for form in form_list for k, v in form.cleaned_data.items()} instance = Course.objects.create(**data) return render(self.request, 'courses/done.html',{'form_data': [form.cleaned_data for form in form_list],}) urls.py path('create_course/',FormWizardView.as_view([CourseForm1,CourseForm2.CourseForm3,CourseForm4]),name='create_course'), -
I want request.POST[variable name] to be executed only if the variable name exists in the input of template
def sendorder(request): items = MenuModel.objects.all() if request.method == 'POST': for item in items: if request.POST['item'+str(item.id)]: print(request.POST['item'+str(item.id)]) return I have some inputs in templates with name item2,item3 etc etc, but this view counts right from the beginning item1 which gives error as no input with name item1 exists. I want to bypass if no such input name exists. -
Prefech many to many relation for one class instance
I want to limit the queries for a detail view. I want to access multiple many to many fields for one class instance. It seems prefetch_related doesn't work with get. JobInstance = Job.objects.get(pk=id).prefetch_related('cities').prefetch_related('experience_level')