Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test Django-request before deployment?
Just installed Django-requests modules. However, from the documentation, it was not clear to me where all the request data is stored or how to test that this package is working. Can someone help me understand how to test that this package is capturing all requests? -
after submit the form, I get an 500 error
after submit a form I get a 500 error and enabled debug mode for django. it shows that Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused Exception Location: /usr/lib/python3.6/socket.py in create_connection, line 713 I am trying to build a django web end to manage(add/update/delete) the ftp users for our ftp(backend mysql).whenever I click submit button. it works on mysql(user info can be updated on mysql), but after clicking submit buttom, it always give me 500 error. how to fix this problem. anyone have any idea? Thank you <img id="top" src="/static/form/top.png" alt=""> <div id="form_container"> <h1><a>Create Publisher Account</a></h1> <form id="form_166666" class="appnitro" enctype="multipart/form-data" method="post" action=""> {% csrf_token %} <div class="form_description"> {% if saved %} <h2>Publisher Account</h2> <p>Account created successfully</p> </div> <ul > <li> <p>The new account has been successfully created.</p> </li> <li class="section_break"> <p> Return to <a href="/publish/publisher/add/">creation page</a>. </a> </li> {% else %} <h2>Publisher Account</h2> <p>Fill in the details below, followed by clicking 'submit' to create a new FTP account for a publisher</p> </div> <ul > {% for field in form %} <li id="li_1" > {{ field.label_tag }} <div> {{ field }} {{ field.errors }} </div> </li> {% endfor %} <li class="buttons"> <input type="hidden" name="form_id" value="166666" /> <input id="saveForm" class="button_text" type="submit" … -
Differentiate between 'account types' in Django
Thanks in advance if you're reading this... I'm a High School student working on a web application using Django, to help students find internships, and facilitate parents posting internship offers -- a sort of marketplace if you will. I'm trying to create a profile/account page for the users but I need a way to differentiate between whether the account logged in is a Student or Employer so that I can use views.py to generate a page appropriate to their account. In models.py, I have two different profile types which can be associated with a user account (handled by django.contrib.auth), see below for reference. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') class Meta: verbose_name = 'Student Profile' def __str__(self): return f"{self.user.username}'s Profile" class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.CharField(max_length=100, default='Unspecified') class Meta: verbose_name = 'Employer/Parent Profile' def __str__(self): return f"{self.user.username}'s Profile" In my views.py page, I'm trying to create a view for the account/profile that can detect whether the currently logged-in user's profile is linked to either the 'Student' or 'Parent' model and serve a page accordingly. I've tried a very rudimentary approach, as below, but unsurprisingly it's not working. def account(request): … -
Run a code on server side several times and use results on html render
I want to run a code which does web scraping and want result to be rendered on html page. On each user request, code in my view function generates data and shows results on page. Everything works fine but I suspect that this is the wrong way to implement my task. If many users will continuously request the page it will lead to server overload from which I am web scraping. def my_function(request): url = 'https://www.some_url.com' source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, "html.parser") result = [] for link in soup.find_all('div', {'id': 'some_id'}): for link_inside in link.find_all('span', {'class': 'some_text'}): a = link_inside.text.strip() result.append(a) context = {'result': result} return render(request, 'myweb.html', context) is it possible to run the code on server side, say 12 times in a day, so I can use those results on rendering. 1) I don't want to keep or save results on my database 2) If I need to keep results on my database is it possible to erase each time and keep updated. -
How to make a correct password encryption in django users?
I would like to learn how to use JSON web-token authorization in Django. I am a newby in django, so I find several tutorials and followed them EXACTLY step by step. I have user model in my app: class User(AbstractUser): username = models.CharField(max_length=10, unique=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) Also I have a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'email', 'username', 'first_name', 'last_name', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = User(**validated_data) user.username = validated_data.get('username') user.set_password(password) user.save() return user please, take a look at user.set_password(password) here. Then I have a api endpoint for creation a token, another endpoint for handling POST request for my users. Nothing special here. The problem is that JWT authorization works not as I expected: Problem description: I. Encryption of user password. I send JSON to POST method of my api endpoint for user creation Expected result: test user is created and password is stored in encrypted way pbkdf2_sha256$150000$mE9jeTnJdBds$X6VtRY0HKM4o4by4PzWNxtgKb8NL1mZg4W5M+y4Ohb0= Actual result: test user is created and password is stored in non-encrypted way. 123456 II. Obtain token issue Pre-conditions: I create a superuser via … -
Django Populate Form with User
My question is fairly straightforward, what is the best method for populating user information for onto a form? I currently use .save(commit=False) and then populate it manually. But is there an already built in mechanism in Django to do this automatically? Or is this as good as it gets? Below is a snippet of what I have in my views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import ContactsForm from django.contrib import messages def home(request): return render(request, 'mainapp/home.html') def about(request): return render(request, 'mainapp/about.html') @login_required def newapp(request): context = {'form': ContactsForm} if request.method == "POST": form = ContactsForm(request.POST) if form.is_valid(): instance = form.save(commit = False) # https://www.youtube.com/watch?v=2h57cqFRcqg instance.user = request.user instance.save() messages.success(request, "Saved new contact!") return redirect('home') #render(request, 'mainapp/home.html', {'form': form}) return render(request, 'mainapp/newapp.html', context) From models.py from django.contrib.auth.models import User from django.db import models class Contacts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length = 100) email = models.CharField(max_length = 100, default='something-{}@gmail.com'.format(rand())) age = models.IntegerField(default = random.randint(a=22, b=45)) class Meta: verbose_name_plural = "Contacts" -
Running WSGI web server on a port (without using IIS)
Opening up a port for http request using WSGI (code is in Python+Django) on windows 10 - does not work for http requests coming from another machine I have a python+django+mongodb site which works great when I run it through VS and now I would like to publish it. My IIS set up with web.config with fastCGI gone bonkers and I am too frustrated to pursue it for the time being. Now I decided to run a WSGI server on a port. So here is what I did. I started my app from command line by running my manage.py like this... C:\Users\<myname>\AppData\Local\Continuum\anaconda3\python.exe manage.py runserver --noreload --settings=myapp.settings And it starts the server and I can visit the site at http://localhost:8000 and everything works great - LOCALLY. But with my machine IP x.y.z.w - I cannot access it from another machine by visiting http://x.y.z.w:8000 Why can't my server listens to the port 8000 from another machine on the SAME network? What do I have to do to allow this? I am on Windows 10 -
How to show an alert on the success url
I want to display a message that form has been successfully submitted when the user gets redirected to success url but I cannot find a solution to do it. Please help.Thanks! views class FeedbackCreate(CreateView): model = Feedback form_class = FeedbackForm template_name = 'feedback_form.html' success_url = '/qworky/dash/' def form_valid(self, form): self.object = form.save(commit=False) self.object.premises = Premises.objects.get(userprofile__user=self.request.user) self.object.client = UserProfile.objects.get(user=self.request.user) return super(FeedbackCreate, self).form_valid(form) -
How to use widgets in Django Crisp Forms
I am using Django Crispy forms and using the FormHelper. Now i want that one of the fields should use widgets. Actually, i want to populate date picker in the field using the widgets. forms.py class DeviceFilterFormHelper(FormHelper): # form_class = "form form-inline" form_id = "Device-search-form" form_method = "GET" form_tag = True html5_required = True layout = Layout( Div( Div('name', css_class="col-md-6"), Div('location', css_class="col-md-6"), css_class='row' ), Div( Div('phone_number', css_class="col-md-6"), Div('updated_date', css_class="col-md-6"), css_class='row' ), FormActions( Submit("submit", ("Search"), css_class="col-md-5"), css_class="col-8 text-right align-self-center", ), ) Below is the widget along with its attributes which i want to use in the formHelper. updated_date = forms.DateInput(attrs={ 'required': True, 'class': 'date-time-picker', 'data-options': '{"format":"Y-m-d H:i", "timepicker":"true"}' }), I just can't figure out how will i be using the widget. -
Python Django - Associating a OneToOneField on users. IntegrityError NOT NULL constraint failed
I'm making a website (obviously) with Django and I have a problem with when I create users. I want to associate my users with a model, called a Class, and the Class contains multiple users. And I assume I need to use models.OneToOneField() to associate one class with multiple users. But when I, for example, create a superuser in the terminal, I instantly get an IntegrityError when I have typed the last bit of required information and pressed enter. I know you could just set null=True in the OneToOneField but then the user isn't associated with a class. Basically, I just want a model called a Class to have multiple users associated with it, and every Class have different Keys/authentication (as shown in models.py) to do different things on my website. Full traceback (after trying to create superuser): Traceback (most recent call last): File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: users_user.parent_class_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\core\management\__init__.py", … -
How to differentiate account types in Django?
Thanks in advance if you're reading this... I'm a High School student working on a web application using Django, to help students find internships, and facilitate parents posting internship offers -- a sort of marketplace if you will. I'm trying to create a profile/account page for the users but I need a way to differentiate between whether the account logged in is a Student or Employer so that I can use views.py to generate a page appropriate to their account. In models.py, I have two different profile types which can be associated with a user account (handled by django.contrib.auth), see below for reference. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') class Meta: verbose_name = 'Student Profile' def __str__(self): return f"{self.user.username}'s Profile" class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.CharField(max_length=100, default='Unspecified') class Meta: verbose_name = 'Employer/Parent Profile' def __str__(self): return f"{self.user.username}'s Profile" In my views.py page, I'm trying to create a view for the account/profile that can detect whether the currently logged-in user's profile is linked to either the 'Student' or 'Parent' model and serve a page accordingly. I've tried a very rudimentary approach, as below, but unsurprisingly it's not working. def account(request): … -
View to Download FileField From Django
I have files which are saved to the MEDIA_ROOT - and I am displaying the file paths as URLs in a table in my UI. I would like for these files to download when the user clicks the link in the table. However, when that happens I get an error because I don't have a URL or View defined to handle this I suppose. Problem is, I'm not really sure where to start - any suggestions. Below is my model, and the .html which displays the table and the link. models.py class Orders(models.Model): ... models.FileField(upload_to='web_unit', null=True, blank=True) ... def __str__(self): return self.reference index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> .... </thead> <tbody> {% for orders in orders %} <tr> <td> <!-- Update book buttons --> <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' orders.pk %}"> <span class="fa fa-pencil"></span> </button> </td> .... <td><a href="{{ orders.order_file }}">Download</a></td> #this is the link </tr> {% endfor %} </tbody> </table> When the link in the table is clicked - I'd like for the file to be downloaded - I need help on how to define the URL and the View to make this … -
Django: How to limit TimeField to hours and minutes only (comparison issue)
I'm developping a web api using django, I have a TimeField that stores hours:minutes:seconds, since it will be compared to a hours:minutes (without seconds) coming from the mobile app, the comparison will always fail. here is a comparison without seconds which is returnning an empty QuerySet: >>> journey = Journey \ ... .objects \ ... .filter((Q(route__departStation=1) | Q(route__stop__station_id=1)), ... (Q(route__arrivalStation=1) | Q(route__stop__station_id=1)), ... route__departDate="2019-07-31", route__departTime="10:57") >>> journey <QuerySet []> and here is when I add seconds to the comparison: >>> journey = Journey \ ... .objects \ ... .filter((Q(route__departStation=1) | Q(route__stop__station_id=1)), ... (Q(route__arrivalStation=1) | Q(route__stop__station_id=1)), route__departDate="2019-07-31", route__departTime="10:57:05") >>> journey <QuerySet [<Journey: Journey object (1)>]> so please, how can I prevent the seconds from being saved to the database from this TimeField(), or at least how can I limit the comparison to hours and minutes only. -
Unable to load staticfiles after deploying django app on aws-ec2
I am a beginner in aws and I am trying to deploy a django app on aws-ec2. I have set-up gunicorn application server and nginx web server and app loads but without static files. I have followed many answers on stackoverflow but I am unable to fix my problem. I tried with both root and alias but they didn't work. The project structure is as follows:- /home/ubuntu/myskillhut/ django.conf(nginx configuration file) server { ... location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myskillhut/app.sock; } location /static/ { autoindex on; alias /home/ubuntu/myskillhut/static/; } } settings.py ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"), ) ... -
models.CASCADE not working correctly in DeleteView
models.CASCADE does not seem to function correctly when I try to delete a parent object in the delete view. I have two models. ExceptionReport and ExceptionReportHistroy. Users can create a report and if conditions are met, a history object is created. Users can delete a report and on deletion, all associated history objects should be deleted but when a user tries to delete, I get this error: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`lp`.`reports_exceptionreporthistory`, CONSTRAINT `reports_exceptionrep_report_id_99f21d10_fk_lp_except` FOREIGN KEY (`report_id`) REFERENCES `lp_exception_reports` (`id`))') I have no idea why since the on_delete=models.CASCADE Models: class ExceptionReports(models.Model): from_field = models.CharField(max_length=100, blank=True) emails = EmailListField(max_length=800) description = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) ... class ExceptionReportHistory(models.Model): created_date = models.DateTimeField(default=now) report = models.ForeignKey(ExceptionReports, on_delete=models.CASCADE) message = models.TextField(blank=True) ... View: class ExceptionReportDeleteView(LoginRequiredMixin, DeleteView): model = ExceptionReports template_name = "reports/delete.html" success_url = reverse_lazy('reports:exceptionreport_list') success_message = "Exception Report deleted successfully." URL: path('exceptionreports/', include([ path('', login_required(views.ExceptionReportListView.as_view()), name='exceptionreport_list'), path('add/', login_required(views.ExceptionReportCreateView.as_view()), name='exceptionreport_create'), path('<int:pk>/', include([ path('update/', login_required(views.ExceptionReportUpdateView.as_view()), name='exceptionreport-update'), path('delete/', login_required(views.ExceptionReportDeleteView.as_view()), name='exceptionreport-delete'), ])), ])), In the delete view, users should be prompted associated history objects that would also be deleted but that doesn't happen instead I get an IntegrityError -
Error when adding many-to-many-field on Post
I have an app within my project called posts, where inside their in the models.py, I have two models: Post and Like. I want to add a many-to-many-field on the post that references the Like model. I have executed makemigrations and migrate, however I am getting this error: NameError: name 'Like' is not defined models.py: class Post(models.Model): file = models.ImageField(upload_to='images/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(Like) def __str__(self): return self.user.username def summary_pretty(self): return self.summary[:50] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=False) -
Creage aggregate query with filtering in django
I have the following table/model. I am trying to figure out how to convert the SQL query into Django 1.11 syntax. In particular, I am having difficulty adding additional filter parameter into Django's When. http://sqlfiddle.com/#!9/8c6974/26 Here is the SQL create/populate: create table Activity ( Id INT AUTO_INCREMENT, username varchar(50), course_id varchar(50), activity_type varchar(50), activity_action varchar(50), times INT, date_event DATETIME, PRIMARY KEY(id) ); INSERT INTO Activity (username, course_id, activity_type, activity_action, times, date_event) VALUES ( 'john', '123', 'video', 'viewed', 2, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'attempted', 11, str_to_date('02-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'attempted', 22, str_to_date('03-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'attempted', 33, str_to_date('02-07-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'solved', 4, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'solved', 5, str_to_date('01-01-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'solved', 6, str_to_date('01-02-2019', '%d-%m-%Y')), ( 'adam', '123', 'video', 'viewed', 2, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'attempted', 11, str_to_date('02-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'attempted', 22, str_to_date('03-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'attempted', 33, str_to_date('02-07-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'solved', 4, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'solved', 5, str_to_date('01-01-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'solved', 6, str_to_date('01-02-2019', '%d-%m-%Y')), ( 'meg', '123', 'discussion', 'asked', 6, str_to_date('03-02-2019', '%d-%m-%Y')), ( 'meg', '123', 'discussion', 'asked', 6, str_to_date('03-02-2019', '%d-%m-%Y')) … -
i have go an error in django 2.2 templatetags {% load post_tag%}
TemplateSyntaxError at / 'post_tag' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils i18n l10n log static staticfiles tz i have this error in django 2.2 -
python - logging: How to access handler from config file
I am trying to use logging in Django Application. I want to predifine my formatters and handlers in config file and later use different handlers at different times as per the need. Currently i am using the following logger config in my settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'format1': { 'format': '[%(duration).3f] %(statement)s', }, 'format2': { 'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s' } }, 'handlers': { 'console1': { 'level': 'DEBUG', 'formatter': 'format1', 'class': 'logging.StreamHandler', }, 'console2': { 'class': 'logging.StreamHandler', 'formatter': 'format2', 'level': 'DEBUG', } } } Is there a way i can use the handlers specified in the settings.py file like: import logging def someview(request) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler("name of the handler from confi file i.e console1 or console2") #I tried # logger.addHandler('console1') it says # Attribute Error - 'str' object has no attribute 'level' # if record.levelno >= hdlr.level: # /usr/lib64/python3.7/logging/__init__.py in callHandlers, line 1590 # So how to use the handler mentioned in the config file -
Django's session-based model - id value in settings.py?
I am learning to build a product cart app for an online shop. But while I was reading other's app, I found something I couldn't understand. settings.py> CART_ID = 'cart_in_session' cart.py> from decimal import Decimal from django.conf import settings from shop.models import Product from coupon.models import Coupon class Kart(object): def __init__(self, request): self.session = request.session kart = self.session.get(settings.CART_ID) if not kart: kart = self.session[settings.CART_ID] = {} self.kart = kart I couldn't get this part of code snippet: if not kart: kart = self.session[settings.CART_ID] = {} It has two "=" symbol and I am wondering if it's for assignment and if it's really an assignment, then why it sets CART_ID's value ("cart_in_session" for its matched key CART_ID) to {} -
Error while saving date in MySQL using Django
I need to save date and time in database (MySQL). I am using Django. The jQuery datetimePicker gets populated but when i click the save button of form, it gives me an error that (1048, "Column 'updated_date' cannot be null") However, if you see below the updated dated do get posted I just can't find any reason why it is not saving the data. Forms.py updated_date = forms.DateTimeField(input_formats=["%Y-%m-%d"], widget=forms.TextInput(attrs= { 'required': True, 'class':'date-time-picker', 'data-options':'{"theme":"dark","format":"Y-m-d", "timepicker":"false"}' })) Model.py class Devices(models.Model): name = models.CharField (max_length=50, null=False, blank=False, unique= True) phone_number = models.CharField (max_length=20, blank=True, unique=True, verbose_name='PHONE NUMBER') location = models.ForeignKey(Location, on_delete=models.DO_NOTHING, null=False, blank=False) status = models.IntegerField(blank=False, default='1') ip_address = models.CharField(max_length=15, null=False, blank=False, unique=True, verbose_name='IP Address') power_status = models.IntegerField(blank=True, default='0') created_date = models.DateTimeField(default=timezone.now(), blank=False) created_by = models.IntegerField(blank=False) updated_date = models.DateField(blank=False) update_by = models.IntegerField(blank=True) def __str__(self): return self.name The data type in MySQL database is datetime. I have even changed it varchar as well but still it is not working. -
Django Heroku deployment URLconf error. Page not found (404)
I am a newbie to Django and trying to deploy my Django app on Heroku. I followed a tutorial and did everything, but when I was finally ready to deploy my app, I get the error "Page not found." I have tried removing the include() around my admin.site.urls because it worked for someone else, but it didn't work for me. this is my urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from profiles.views import delete urlpatterns = [ path(r'^profiles/', include('profiles.urls')), path(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) this is my settings.py file: import os import django_heroku import django os.environ['DJANGO_SETTINGS_MODULE'] = 'firstDjango.settings' from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY="bb33e5a618aa4f6e549b8207ad1d8fa7cd8d1015e13c8780" DEBUG = True ALLOWED_HOSTS = ['ewuradjango.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party #own # 'pages' 'profiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'firstDjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'firstDjango.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = … -
How can I optimize loops within a Django template?
I have a database setup where I have the following schema: The main model is the Group. Under each group are an arbitrary number of Rules. Each Rule contains an arbitrary number of Regex's and Contacts. I'm displaying this whole set up under the main page so it looks something like this: Group A - Rule A - Regex 1, Contact 1, Contact 2 - Regex 2, Regex 3, Contact 3 - Rule B - Regex 5, Regex 6, Regex 6, Contact 4 - Regex 7, Contact 7, Contact 6 Group B - ... The db query itself is not terribly complex. It's basically: for group in groups: r = Rule.objects.filter(group=group) rules[group]= r But the template rendering is what is slowing things down. It's taking about 7 seconds to render the template because of the number of nested loops: {% for group, rules in rules.items %} {% for rule in rules %} {% for regex in rule.regexes.all %} {{regex.name}} {{regex.type}} {{...}} {% endfor %} {% for contacts in rule.contacts.all %} {{contacts.name}} {{contacts.email}} {{...}} {% endfor %} {% endfor %} {% endfor %} There's obviously more HTML in here but even without it, this rendering takes about 3-4 seconds (full template … -
How to create a dropdown menu in django with selections from created model objects?
I just want to create a dropdown menu with values from formerly created objects (instruments). In this case objects in the Instrument class. I read all the other posts about dropdowns in Django, but most of them address the creation of a new object or something with fixed choices. Though I want to select one from the available objects and then further process it. I don't want to create a new object and I need dynamic choices. forms.py # forms.py from django import forms from .models import Instrument class CreateForm(forms.Form): favorite_fruit = forms.ModelChoiceField(queryset = Instrument.objects.all()) models.py # models.py from django.db import models # Create your models here. class Instrument(models.Model): name = models.CharField(max_length=20, unique=True) description = models.TextField(default='') output_root = models.CharField(max_length=1000, default='') methods_root = models.CharField(max_length=1000, default='') def __str__(self): return self.name html template <!-- create.html --!> {% extends 'base.html' %} {% block content %} <h2>Create new worklist</h2> <form method="POST" class="create-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} -
Registration screen with 3 different user types
Well, I have the following registration screen and I have to basically have 3 types of users: Teacher, Licensing and Other. Here is a link for the image because i don't have 10 points of reputation: https://i.stack.imgur.com/PqXO1.png So far what I have in the models I made using AbstractBaseUser, I have only the normal user information and wanted to inherit from this User that I have these two other fields: The Teacher and licensing it with the specific fields I want. Here's my account model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Usuário deve ter um email") user = self.model( email=self.normalize_email(email) ) user.staff = is_staff user.admin = is_admin user.active = is_active user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, blank=True, null=True, verbose_name='Usuário') first_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Nome') last_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Sobrenome') active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS …