Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django to show status of running os command
I am using django to create an app which will take the targets from the text file and then will launch the Nmap scan against the hosts specified. Everything is working fine with the only problem being showing status of the running command on browser's screen.Since I am running the command with os.system(command), I can get the output at terminal from where I have launched the runserver command. But, I am just wondering if there is any way to redirect the output to the web browsers screen. -
ImportError: No module named weather_Core_Engine.weather_DB_Handler
I'm trying to build a project on python using Django on pythinanywhere. I'm not familiar at all with Django so any hints it's more than welcome. I created a Django app called profiles and there i created some db models. so far so good. I'm using sqlite3 and I managed to migrate the db and to correctly start my project. now I have modified the file models.py but while running the migration using the command: "python ./manage.py makemigrations" I have the following issue: "16:11 ~/Mico_Weather_BackTrace $ python ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 353, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res … -
django is adding characters to my URL
When people visit my website, django is sometimes randomly adding characters to my URL. (It happens intermittently) name_of_url.com gets re-routed to something like name_of_url.com/KiRkZ/ name_of_url.com/section gets re-routed to something like name_of_url.com/KiRkZ/section Is there a way to remove these characters? It is causing a 404 error for the visitors it happens to. -
Display latest "commentator" username in forum app [Django]
I am creating a forum app, and want to display latest commentator's username(as seen in screenshot): But I have some gaps in information, here is my code so far: Models class Forum(models.Model): """ Forum Model """ forum_author = models.ForeignKey( Profile, related_name='user_forums', null=True, blank=True, on_delete=models.CASCADE ) forum_title = models.CharField( max_length=225, verbose_name=u'Thread Title', blank=False, null=False ) forum_category = models.ForeignKey( 'Category', verbose_name=u'Thread Category', ) forum_content = MarkdownxField() class Comment(models.Model): """ Comment Model """ forum = models.ForeignKey( 'Forum', related_name='forum_comments' ) comment_author = models.ForeignKey( Profile, related_name='user_comments', null=True, blank=True, on_delete=models.CASCADE ) comment_content = MarkdownxField() created_date = models.DateTimeField( default=datetime.datetime.now, ) Forum list views - display all threads ... from app_forum.models import Forum, Comment def forum_list_view(request): forum_list = Forum.objects.all().order_by("-misc_created") return render(request, 'app_forum/forum_list.html' {'forum_list': forum_list}) My single thread views : def forum_single_view(request, pk): forum = get_object_or_404(Forum, pk=pk) forum_comments = Comment.objects.filter(forum=forum.id) paginator = Paginator(forum_comments, 10) page = request.GET.get('page', 1) try: forum_comments = paginator.page(page) except PageNotAnInteger: forum_comments = paginator.page(1) except EmptyPage: forum_comments = paginator.page(paginator.num_pages) return render(request, 'app_forum/forum_single.html', {'forum': forum, 'forum_comments': forum_comments}) -
Flake8 check on lowercase function will skip some inherited function
I use flake8 as code violation check, but I find a strange thing about the lowercase function name check. The function name like setUp won't be reported, I guess it may be the reason of this function is inherited from django TestCase class. from django.contrib.auth.models import User from django.test import TestCase class BaseTestCase(TestCase): def setUp(self): self.admin = User.objects.create_superuser( 'admin-user-name', 'admin_email@test.com', 'password') def loginNormalUser(self): self.client.login(username='neo', password='fake_password') Because the other function with the name loginNormalUser in the CamelCase, flake8 report this function. $ flake8 helpers.py helpers.py:10:9: N802 function name should be lowercase There is a related issue about the lowercase check here: flake8 doesn't report mixed-case function names, so I already install pep8-naming. -
Django forms won't render (No reverse match)
I'm trying to make a form with Django 1.10 to create a comment on a Task object. When I want to open the form, there is no field and when I try to submit, I got this error : NoReverseMatch at /tasks/29/comment/ Reverse for 'create_comment' with arguments '('',)' not found. 1 pattern(s) tried: [u'tasks/(?P[0-9]+)/comment/$'] How can I render my form on my template, and return to my "detail" view after submit ? forms.py class CreateCommentForm(forms.Form): commentary = forms.CharField(label='Commentary', widget=forms.Textarea, required=True) models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.ForeignKey(Task, on_delete=models.CASCADE) commentary = models.TextField(blank=True, max_length=5000) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.commentary views.py class CommentCreateView(SuperuserRequiredMixin, FormView): template_name = 'tasks/create_comment_modal.html' form_class = CreateCommentForm def form_valid(self, form): user = self.request.user task = Task.objects.get(id=self.kwargs['pk']) commentary = form.cleaned_data['commentary'] comment = Comment(user=user, task=task, commentary=commentary) comment.save() return HttpResponseRedirect(reverse('tasks:detail', kwargs={'pk': task.id})) urls.py url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/comment/$', views.CommentCreateView.as_view(), name='create_comment'), create_comment_modal.html {% load widget_tweaks %} <form role="form" id="comment-create-form" name="comment-create-form" method="post" action="{% url 'tasks:create_comment' task.id %}"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Add comment in task #{{ task.id }} - {{ task.title }}</h4> </div> <div class="modal-body"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <div class="form-group"> <label class="control-label" for="{{ form.commentary.id_for_label }}">Commentary</label> {% render_field form.commentary class+="form-control" %} </div> </div> </div> <div … -
Python MySQL Parameterized Queries with date
I have a sql query used in django where a parameter is a date: query="select DT_ORA_INSERIMENTO from richieste where DT_ORA_INSERIMENTO=%s", datestart but in this manner I receive the error: not enough arguments for format string it seems django don't substitute the value of the variable with his value (2017-09-02 00:00:00).. what is wrong? -
Django DRF append BASE_PATH in front of a serializer field
I currently have a serializer as follows: class UserProductsSerializer(serializers.ModelSerializer): user_name = serializers.SlugRelatedField(source='user_id', read_only=True, slug_field='name') class Meta: model = UserProducts fields = '__all__' and the model: class UserProducts(models.Model): user_id = models.ForeignKey('User', db_column='user_id', related_name='user_name') product_id = models.ForeignKey('Products', db_column='product_id', related_name='user_products') category_id = models.ForeignKey('categories', db_column='category_id', related_name='user_products') image = models.CharField(max_length=255, blank=True, null=True) notice the image field above. I have strings of filenames stored in my s3 bucket like - upload.jpg I would want to me able to append my s3 URL to this field, something like http://<my_s3_url>/upload.jpg. Where should I be doing this - in the serializer or in the view? And how can I achieve this -
Drop-down menu with crispy-forms
I am a new programmer with Django/Python, and I need a bit of help with crispy-forms to create a pull down menu. Some people add formlayout.py and forms.py to their app, but I don't know if it is related? The following images represent what I want to do now, but with 'Type' instead of 'Gender' Image #1 and Image #2 How could create a pull down menu with crispy-forms? What files do I have to add to my Django app? What library do I have to use in python? Why inserting a forms.py and formlayout.py in the app? How the forms.py interact with the template view? An example could be highly appreciated. -
DRF PUT Partial Update returning Not Found
I'm trying to get to grips with Django and DRF but having some trouble. I would like to make a PUT request to make a partial update on a record. I currently have the following parts - From models.py class MyUser(models.Model): # Link to User model instance. user = models.OneToOneField(User) first_name = models.CharField(max_length=32, null=True, blank=True) lastname = models.CharField(max_length=32, null=True, blank=True) joindate = models.DateTimeField(null=False, blank=False) def __str__(self): return self.user.username From api/views.py class MyUserDetailUpdateView(GenericAPIView, UpdateModelMixin): queryset = MyUser.objects.all() serializer_class = MyUserPartialUpdateSerializer lookup_field = 'user' def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) From api/serializers.py class MyUserPartialUpdateSerializer(serializers.ModelSerializer): class Meta: model = MyUser From urls.py url(r'^api/userupdate/(?P<user>[\w]+)/$', apiviews.MyUserDetailUpdateView.as_view(), name='my_user_detail_view_api') For testing I used httpie and try - http -v PUT http://127.0.0.1:8000/api/userupdate/johndoe/ first_name="Johnny" The server side is reporting a "Not Found: /api/userdate/johndoe/" and returns a HTTP 404 to the client. What am I missing to do a partial update? Thanks -
Django static assets reference in Jinja Templates
I have a Jinja macro defined as follows. globalmacros.html {% macro SUINavMenu(leftlist=[],logo="images/Logo_WEB_450_250.png") %} <div class="ui pointing secondary menu"> <div class="item"> <img src="{{ static({{ logo }}) }}"> </div> {% for item in leftlist %} <a class="item" href="{{ item[1] }}"> {{ item[0] }} </a> {% endfor %} </div> {% endmacro %} dashboard.html {% from "macros/globalmacros.html" import SUINavMenu %} {% block navigation %} {{ SUINavenu(leftlist=[["Home","/home/"],["New Bill","/newbill/"]], logo="images/web_logo.png") }} {% endblock navigation %} I am importing the macro defined in "globalmacros.html" into "dashboard.html" and trying to pass the logo location. However I am not sure how to do it. In a non-macro version, the following code works. <img src=" {{ static('images/logo_web.png') }} "></img> The above code in "globalmacros.html" doesnt work as Jinja does not process an {{}} inside another {{}} What is the work around for this? -
Django JWT-Auth also i have login API. Can i generate token on login and send to the front-end?
I am using 'rest_framework_jwt.authentication' and also i have Login API, if i am generating token over default auth-token API then what is the use of Login API? so can i generate token while executing login API and if its success then send back generated token to the front-end. urls.py url(r'^login/$', views.UserLoginAPIView.as_view(), name='login'), url(r'^api/auth/token/', obtain_jwt_token), serializers.py class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read_only= True) email = EmailField(label='Email Address', allow_blank= True) class Meta: model = User fields = [ 'email', 'password', 'token' ] extra_kwargs = {"password": {"write_only": True} } def validate(self, data): user_obj = None email = data.get("email", None) password = data["password"] if not email: raise ValidationError('A username or email is required to login') user = User.objects.filter( Q(email=email) ).distinct() if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("incorrect creadeintial try again") data["token"] = "SOME BLANK TOKEN" return data view.py class UserLoginAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
How do I exchange an idToken or serverAuthCode for a google access_token on Django backend?
I retrieved a valid idToken and serverAuthCode on my client, then posted it to my Django backend. I verified the idToken with verify_id_token([idToken], '******.apps.googleusercontent.com') How can I convert this to an access_token from my backend? -
Django ModuleNotFound For scripts
This has been driving me up the wall. I have a Django project with the following tree structure, and am trying to run python helper_scripts/load_professors_into_db.py from the root directory load_professors_into_db.py has the following code: ## TODO: FIX THIS DAMN IMPORT PATH. THE SCRIPT DOESNT RUN CAUSE OF IT from ocubulum_dashboard.models import Researcher import pandas as pd df = pd.read_csv("helper_scripts/soc_myaces_list.csv") df = df.dropna() df = df[~pd.isnull(df["scopus_id"])] df = df[df["scopus_id"] != 'None'] However, it keeps trying ModuleNotFound errors. I've tried adding __init__.py files everywhere, but that doesn't work either. Traceback (most recent call last): File "helper_scripts/load_professors_into_db.py", line 10, in <module> from ocubulum_dashboard.models import Researcher ModuleNotFoundError: No module named 'ocubulum_dashboard' The problem doesn't only occur for this. For other scripts that I want to run such as scopus_scraper.py, I face this ridiculous import issue as well. Traceback (most recent call last): File "data_collectors/scopus/scopus_scraper.py", line 1, in <module> from ocubulum_dashboard.models import Researcher ModuleNotFoundError: No module named 'ocubulum_dashboard' Can someone point me as to how to solve this problem? I'm on python 3.6. Entire Folder Structure: ├── data_aggregators │ ├── myaces_aggregator.py │ └── scopus_aggregator.py ├── data_collectors │ ├── execute_all.py │ ├── __init__.py │ ├── journals │ │ ├── __init__.py │ │ ├── journal_scraper.py │ │ … -
Run crontab in docker. Django
Sorry for my english. I created docker file. For cron task i user this library, In my local test all work, but now i try use docker and try run cron there.But now i have error no crontab for root My docker file: FROM python:3.6 WORKDIR /usr/src/app COPY requirements.txt ./ RUN apt-get update && apt-get install -y cron RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD python manage.py runserver 0.0.0.0:8000 RUN python manage.py crontab add RUN python manage.py crontab show My requirements Django==1.11.4 django-filter==1.0.4 djangorestframework Pillow django-crontab -
Trying to host django on a centos/apache stack
Hi i'm having difficulties installing and running django on centos/apache. After i installed Django, python, apache (httpd), and centos. I am trying to setup the wsgi file but for some reason after i did ./configure --with-apxs=/bin/apxs \ --with-python=/bin/python and ran make. I am getting a huge error file, attached below. I am on django 1.11.4 apache httpd 2.4.6 (centOS) centos-release-7-3.1611.el7.centos.x86_64 [root@mongodb21 mod_wsgi-4.5.18]# make /bin/apxs -c -I/usr/include/python2.7 -D_GNU_SOURCE -DNDEBUG -D_GNU_SOURCE -Wc,-g -Wc,-O2 src/server/mod_wsgi.c src/server/wsgi_*.c -L/usr/lib64 -L/usr/lib64/python2.7/config -lpython2.7 -lpthread -ldl -lutil -lm /usr/lib64/apr-1/build/libtool --silent --mode=compile gcc -std=gnu99 -prefer-pic -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -DLINUX -D_REENTRANT -D_GNU_SOURCE -pthread -I/usr/include/httpd -I/usr/include/apr-1 -I/usr/include/apr-1 -g -O2 -I/usr/include/python2.7 -D_GNU_SOURCE -DNDEBUG -D_GNU_SOURCE -c -o src/server/mod_wsgi.lo src/server/mod_wsgi.c && touch src/server/mod_wsgi.slo In file included from /usr/include/python2.7/pyconfig.h:6:0, from /usr/include/python2.7/Python.h:8, from src/server/wsgi_python.h:24, from src/server/mod_wsgi.c:22: /usr/include/python2.7/pyconfig-64.h:1188:0: warning: "_POSIX_C_SOURCE" redefined [enabled by default] #define _POSIX_C_SOURCE 200112L ^ In file included from /usr/include/sys/types.h:25:0, from /usr/include/apr-1/apr-x86_64.h:164, from /usr/include/apr-1/apr.h:19, from /usr/include/httpd/ap_hooks.h:39, from /usr/include/httpd/ap_config.h:25, from /usr/include/httpd/httpd.h:44, from src/server/wsgi_apache.h:42, from src/server/mod_wsgi.c:21: /usr/include/features.h:168:0: note: this is the location of the previous definition # define _POSIX_C_SOURCE 200809L ^ In file included from /usr/include/python2.7/pyconfig.h:6:0, from /usr/include/python2.7/Python.h:8, from src/server/wsgi_python.h:24, from src/server/mod_wsgi.c:22: /usr/include/python2.7/pyconfig-64.h:1210:0: warning: "_XOPEN_SOURCE" redefined [enabled by default] #define _XOPEN_SOURCE 600 ^ In file included from /usr/include/sys/types.h:25:0, … -
LIKE query in Django ORM
How can I make query, with rule: order by words, that contain founded string as close as possible to the beginning. Is it real? For example: search 'hi' result: hi all hi cat Peter, hi I come to you and say hi query = query & Q(name__contains=params['name']) -
django DoesNotExist matching query does not exist with postgres only
The assets django app I'm working on runs well with SQLite but I am facing performance issues with deletes / updates of large sets of records and so I am making the transition to a PostgreSQL database. To do so, I am starting fresh by updating theapp/settings.py to configure PostgreSQL, starting with a fresh db and deleting the assets/migrations/ directory. I am then running: ./manage.py makemigrations assets ./manage.py migrate --run-syncdb ./manage.py createsuperuser I have a function called within a registered post_create signal. It runs a scan when a Scan object is created. Within the class assets.models.Scan: @classmethod def post_create(cls, sender, instance, created, *args, **kwargs): if not created: return from celery.result import AsyncResult # get the domains for the project, from scan print("debug: task = tasks.populate_endpoints.delay({})".format(instance.pk)) task = tasks.populate_endpoints.delay(instance.pk) The offending code: from celery import shared_task .... import datetime @shared_task def populate_endpoints(scan_pk): from .models import Scan, Project, from anotherapp.plugins.sensual import subdomains scan = Scan.objects.get(pk=scan_pk) #<<<<<<<< django no like new_entries_count = 0 project = Project.objects.get(id=scan.project.id) .... The resultant exception DoesNotExist raised: debug: task = tasks.populate_endpoints.delay(2) [2017-09-14 23:18:34,950: ERROR/ForkPoolWorker-8] Task assets.tasks.populate_endpoints[4555d329-2873-4184-be60-55e44c46a858] raised unexpected: DoesNotExist('Scan matching query does not exist.',) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/celery/app/trace.py", line 374, in trace_task R = retval … -
ValueError: set the `backend` attribute on the user
I have added python-social-auth in my project for social logins. I also have a signup form of my own for new users. For social logins, I added some authentication backends. Now, the social logins are working fine, but the signup form causes some problems. After I enter the details, and click signup, this error comes up. I see in the admin panel, the user was added even after this error. ValueError: You have multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user. Now, it is asking me to set the backend attribute of the user. How to set that ? Here is the view for signup, def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_pass = form.cleaned_data.get('password') user = authenticate(username=username,password=raw_pass) login(request,user) return redirect('location:get_location') else: form = SignupForm() return render(request, 'signup.html', {'form':form}) -
Issue with online logged users in my Django application
As always, I'm trying to improve my Django application and I would like to create a Django module which could display all logged users. This is my model class LoggedUser : class LoggedUser(models.Model): user = models.OneToOneField(User, primary_key=True) def __unicode__(self): return self.user.username def login_user(sender, request, user, **kwargs): LoggedUser(user=user).save() def logout_user(sender, request, user, **kwargs): try: u = LoggedUser.objects.get(user=user) u.delete() except LoggedUser.DoesNotExist: pass user_logged_in.connect(login_user) user_logged_out.connect(logout_user) Then, I have in my view : def ConnectedUsers(request) : logged_users=[user.user for user in LoggedUser.objects.all()] print logged_users context = { "logged_users":logged_users, } return render(request, "UtilisateursConnectes.html", context) The print query returns : [] And a very simple template just in order to display logged users : {% block content %} List of logged users : {% for users in logged_users %} <li>{{ users }}</li> {% endfor %} {% endblock %} The problem is : When I try to connect different account on my software, the table LoggedUser is still empty. Do I make a mistake in my script ? -
Best way to keep web application data sync with elasticsearh
I'm developing a web application in Python with Django for scheduling medical services. The database using is Mysql. The system has several complex searches. For good performance, I'm using elasticsearch. The idea is to index only searchable data. The document created in the ES is not exactly the same as modeling in the database, for example, the Patient entity has relationships in the DB that are mapped as attributes in the ES. I am in doubt at what time to update the record in the ES when some relationship is updated. I am currently updating the registry in ES whenever an object is created, changed or deleted in the DB. In the case of relationships, I need to fetch the parent entity to update the record. Another strategy would be to do the full index periodically. The problem with this strategy is the delay between a change and it's available for search. What would be the best strategy in this case? -
How to implement MQTT in Django.?
I already have a system where cc3200 IoT devices communicate to Django server via REST APIs. I am planning to change the communication protocol to MQTT as I've heard that it is the best-suited protocol for IoT devices.I have no idea how to implement MQTT in Django and how to replace all Django REST APIs that are currently used for data transfer. How can I receive messages from IoT devices and process it in Django and also how can I send data from Django to IoT devices using MQTT. -
Why can't I put value to db?
I made composite id of trunsaction_id&user_id.I wanted to assign trunsaction_id each user_id.Now User model is class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) user_trunsaction_id = ''.join([str(trunsaction_id), '_', str(user_id)] But when I run file of putting data to User model, all column excepting for user_trunsaction_id has its data, but no user_trunsaction_id's column is db.Of course I run makemigration&migration command,so I really cannot understand why this error happens.What is wrong?How can I fix this? -
Django - Extending Global Static HTML Template
Description How could I extend base.html in my apps using following folder structure Folder Structure └───project ├───plots # <-- app ├───project ├───projects # <-- app ├───static # <-- project static files │ ├───css │ ├───html │ └───img └───users # <-- app Settings File STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] and I do use static files via {% load static %} - {% static '/css/base.css' %} I also know how to use {% extends file %} - {% extends users/html/base.html %} I would like to extend from static folder like such {% extends 'html/base.html' %}, however I can't find a way how to achieve this relation. Alternative Solution I found an alternative way to get it to work modifying templates entry in projects settings file. It works but, if possible, I would like to keep all static files in one place. Folder Structure └───project ├───plots # <-- app ├───project ├───projects # <-- app ├───static # <-- project static files │ ├───css │ └───img ├───templates #<-- !now `base.html` is here! └───users # <-- app Settings 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', ], }, }, … -
Pull down menu with crispy-forms
I am a new programmer with Django/Python, and I need a bit of help with crispy-forms to create a pull down menu. Some people add formlayout.py and forms.py to their app, but I don't know if it is related? The following images represent what I want to do now, but with 'Type' instead of 'Gender' and How could create a pull down menu with crispy-forms? What files do I have to add to my Django app? What library do I have to use in python? I'd appreciate to have some guidelines.