Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change my models.TextField to models.JSONField?
I'm using django as my backend and it was working very fine, but after I tried to replaced text = models.TextField(blank=True, null=True) text = models.JSONField(blank=True, null=True) but I got the text field is shown as string with slashes \ "text": "{\"name\": [\"test\", \"test2\"]}", while styles field look as json "style": { "borderRadius": "5px", "backgroundColor": "orange" }, despite they both are jsonfield. models.py class elements(models.Model): tag = models.CharField(blank=True, null=True, max_length=20) # it was # text = models.TextField(blank=True, null=True) # now it is text = models.JSONField(blank=True, null=True) src = models.TextField(blank=True, null=True) style = models.JSONField(blank=True, null=True) main = models.ForeignKey( 'self', null=True, blank=True, related_name="sub", on_delete=models.PROTECT) def __str__(self): return "<elements: {} {}>".format(self.tag, self.text, self.src, self.style) def __repr__(self): return self.__str__() Note: I tried to delete my data don't remigrate as well but did't work -
How can I launch my Django application internally for my company?
I am in the process of building a fairly large data analytics web app using Django - however I am more of a data scientist than a software developer so I am unsure of a few things here. The key issue I have is that the data this application contains is highly sensitive and there is a company-wide ban on microsites on their servers. As a result I cannot simply host this application on any old server or Heroku etc., and I'm not sure even a secure user authentication would suffice in this case without my company's own security layers included - something i'd be unlikely to get sorted in time for the project deadline. Is there an easy way I can package the app into a desktop application that only members of my organisation can install? If so how I do go about this and how can I enable specific colleagues to install it? Or am I missing a much more obvious method? Thanks -
SQL vs django: reproduce the __ from a filter
I have following django filter: replacement_device = DeviceReplacement.objects.filter( new_device__mac_address=mac_address ).all() I want to reproduce this in SQL but don't know how to do the __ in sql. more information: devicereplacement has 3 attributes: id, new_device_id, old_device_id device has many attributes including id and mac_address -
How to execute solr "rebuild_indexes" from deployment .yaml in k8s?
I have my app and database pods running and my database is initialized by loading some predefined data. Then I start my solr pod but i can only search newly created data from my app and not the predefined data which is loaded into my database. I assume a rebuild_indexes command needs to be issued from the deployment.yaml file of solr so that the predefined data is also indexed and can be searched? -
How to access Local file in Python from Website
I was able to access local file in local host by using the code 'src = path.realpath("C:\Users\HP\AppData\Local\imp.txt") but as I hosted it on heroku it shows error of file not found '/app/C:\Users\HP\AppData\Local\imp.txt' -
Django : 'bool' object is not callable - fields.py in clean, line 45 [closed]
I'm using django-messages app. Everything works well (reply, message, ... except compose). I can easily reply to a message. Assume I've created a message from my admin pannel. But If want to send a new message to someone and create new conversation, that does not work. I'm facing an issue when I try send a new message to someone. 'bool' object is not callable message/fields.py in clean, line 45 messages/fields.py from django import forms from django.forms import widgets from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from .utils import * User = get_user_model() class CommaSeparatedUserInput(widgets.Input): input_type = 'text' def render(self, name, value, **kwargs): if value is None: value = '' elif isinstance(value, (list, tuple)): value = (', '.join([getattr(user, get_username_field()) for user in value])) return super(CommaSeparatedUserInput, self).render(name, value, **kwargs) class CommaSeparatedUserField(forms.Field): widget = CommaSeparatedUserInput def __init__(self, *args, **kwargs): receiver_filter = kwargs.pop('receiver_filter', None) self._receiver_filter = receiver_filter super(CommaSeparatedUserField, self).__init__(*args, **kwargs) def clean(self, value): super(CommaSeparatedUserField, self).clean(value) if not value: return '' if isinstance(value, (list, tuple)): return value names = set(value.split(',')) names_set = set([name.strip() for name in names if name.strip()]) users = list(User.objects.filter(**{'%s__in' % get_username_field(): names_set})) unknown_names = names_set ^ set([getattr(user, get_username_field()) for user in users]) receiver_filter = self._receiver_filter invalid_users = [] if … -
Django Rest Framework(DRF): HyperlinkedModelSerializer Could not resolve URL for hyperlinked relationship
I have this issue: Could not resolve URL for hyperlinked relationship using view name "test-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. This error occurs from the below code: File: models.py class Test(models.Model): first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) File: serializers.py class TestSeriliazer(serializers.HyperlinkedModelSerializer): class Meta: model = Test fields = ('first_name', 'last_name', 'url') File: apiviews.py class TestsList(generics.ListCreateAPIView): queryset = Test.objects.all() serializer_class = TestSeriliazer File: urls.py urlpatterns = [ .... path('tests/', TestsList.as_view(), name='tests-list') ] If i change the url name to 'test-detail' also does not work! How do i solve this issue? If it possible without Routes. -
Pytest Image Upload
I'm testing an API call that uploads an image to the user profile. The test case below returns status code 400. If I remove image_filename key from data, the test case succeeds. How can I test an image upload in pytest? def test_edit_user_profile(db, client): # stream the image into binary with open('C:/...../test.png', 'rb') as consultant_image: image_binary = BytesIO(consultant_image.read()) userdetail_response = client.patch(path=reverse('user-detail', args="1"), data={"full_name": "James edited", "image_filename": (image_binary, 'test2.png')}, content_type='multipart/form-data', HTTP_AUTHORIZATION='Token ' + data.json()['token_key']) assert userdetail_response.status_code == status.HTTP_200_OK -
Django - User created but Profile is missing
When I register a new user, I can see from the Admin page that the user was created. But whenever I go on my profile page in my nav var I get the following Error. It was actually working before I added a function on my Profile page (a button that deletes a user&profile) but I don't see what I need to page to fix this error. profile.html {% extends "digitalFarm/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="boder-bottom mb-4">Profile info</legend> {{ u_form|crispy }} {{ p_form|crispy }} {{ d_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update Profile</button> </div> </form> <form> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Delete User Account</legend> </fieldset> <div class="form-group"> <button class="btn btn-danger"> <a style="color: white" href="{% url 'profile_confirm_delete' %}">Delete Account</a></button> </div> </form> </div> {% endblock content %} views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to login') return redirect('login') else: form = UserRegisterForm() return … -
Django: @login_required decorator does not redirect to "next"
I am building a dictionary app using Django where users are able to define words. However, I want users to be logged in before being able to do that. I am trying to implement this constraint using the build-in @login_required decorator on my define view (the view that lets users define words). Using @login_required, when I am not logged in and try to define a word (using a definition form) I correctly get redirected to the login page. Here is my login_view view in views.py: def login_view(request): form = LoginForm(data=request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse(settings.LOGIN_REDIRECT_URL)) return render(request, "users/login.html", {"form": form}) At this time my URL looks something like: http://127.0.0.1:8000/login?next=/define So far so good. As soon as I log in, however, Django does not redirect me back to the definition form I was trying to access in the first place (located at /define). How can I tell Django to redirect me to the definition form in this situation? Also, in my settings.py I have redefined the LOGIN_URL, LOGIN_REDIRECT_URL, and LOGOUT_REDIRECT_URL variables as follows: LOGIN_URL = "users:login" LOGIN_REDIRECT_URL = "dictionary:index" LOGOUT_REDIRECT_URL = "dictionary:index" Might the … -
Django: how to create private groups and join them using password?
EXAMPLE to elaborate my problem -> I am the user of the website and i want to create a group. While creating group the website asked me the group_name,group_description ,group_password (as i don't want the group to be public and a person if want to join the group should know the password). now i have given the name and the password to my friends and they can join the group by authenticating with the password of group to successfully join. ISSUE i am facing -> i have created the password field in models.py. But the password is saved in the database as plane text but not something liked hashed django passwords. secondly, i want in the joining user to authenticate with the password in order to join the group. models.py class Group(models.Model): admin = models.ForeignKey(to=Profile, related_name="admin", on_delete=models.CASCADE) name = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200, default='thinkgroupy') slug = models.SlugField(allow_unicode=True, unique=True) group_pic = models.ImageField(upload_to="users/group_images/%y/%m/%d",null=True) about = models.CharField(max_length=255, null=True, blank=True) about_html = models.TextField(editable=False, default='', blank=True) created_at = models.DateTimeField(auto_now=True) members = models.ManyToManyField(User, through="GroupMember") def __str__(self): return "%s" % self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.about_html = misaka.html(self.about) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class Meta: ordering = ["name"] class GroupMember(models.Model): … -
Linking table in django
I have the tables below and I'm trying to link them such that I can query and perform calculation from fields of these tables.Example quantity - quantity_issued. Any help help would be highly appreciated. class Stock(models.Model): item_date = models.DateField(("Date"), default=datetime.date.today) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) quantity_expected = models.IntegerField(blank=True, null=True) total_cost = models.IntegerField(blank=True,null=True) supplier_details = models.CharField(max_length=100, blank=True, null=True) created_by = models.CharField(max_length=100, blank=True, null=True) last_update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.item_name + " " + str(self.quantity) class Issued_items(models.Model): item_date = models.DateField(("Date"), default=datetime.date.today) item_name = models.CharField(max_length=100, blank=True, null=True) quantity_issued = models.IntegerField(blank=True, null=True) issued_to = models.IntegerField(blank=True, null=True) last_update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.item_name + " " + str(self.quantity_issued) -
Nginx redirect with Gunicorn on Django app not working properly
I've developed a simple Django web application but am currently struggling to set up nginx to properly serve static files. The app runs correctly with Gunicorn on port 8000. I'm trying to add static files by accessing the port 8080. Unfortunately, I get the following timeout message after a request on port 8080: nginx_1 | 2020/09/02 12:16:56 [error] 27#27: *5 upstream prematurely closed connection while reading response header from upstream, client: 172.18.0.1, server: , request: "GET /admin/ HTTP/1.1", upstream: "uwsgi://172.18.0.4:8000", host: "0.0.0.0:8080" I believe the error is coming from the server: , part of the error message above, but can't seem to figure out how to actually solve it. Here is my nginx default.conf file: server { listen 8080; location /static { autoindex off; alias /vol/static; } location / { uwsgi_pass app:8000; proxy_request_buffering off; proxy_buffering off; proxy_set_header Host $host:$server_port; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; include /etc/nginx/uwsgi_params; } } Here is the Dockerfile of my nginx image: FROM nginxinc/nginx-unprivileged:1-alpine COPY /docker/prod/nginx/uwsgi_params /etc/nginx/uwsgi_params USER root RUN mkdir -p /vol/static RUN chmod 755 /vol/static USER nginx And here's my docker-compose.yml: version: "3" services: app: build: context: . dockerfile: docker/prod/python/Dockerfile ports: - 8000:8000 volumes: - .:/workspace:cached - static_data:/vol/web working_dir: /workspace/src/ environment: - DJANGO_SETTINGS_MODULE=config.settings.production env_file: - ./src/.env … -
Forgot Password API Django rest framework
I am using OTP authentication for the Forgot password of user. I want the phone no get verify then the user can able to change the password of their account. I want to change the password of the user if the user can verify their number the new password could get set. I someone able to give an answer please help. serializers.py class PasswordSerializer(serializers.Serializer): """ Serializer for password change endpoint. """ new_password = serializers.CharField(required=True) models.py class ResetPhoneOTP(models.Model): phone_regex = RegexValidator( regex = r'^\+?1?\d{9,14}$', message = "Phone number must be entered in the form of +919999999999.") phone = models.CharField(validators = [phone_regex], max_length=17, blank=True) otp = models.CharField(max_length=9, blank=True, null=True) count = models.IntegerField(default=0, help_text = 'Number of opt_sent') validated = models.BooleanField(default=False, help_text= 'if it is true, that means user have validate opt correctly in seconds') def __str__(self): return str(self.phone) + ' is sent ' + str(self.otp) views.py class UserViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): """ list: Return a list of all the existing users. read: Return the given user. me: Return authenticated user. """ queryset = User.objects.all() serializer_class = PasswordSerializer # permission_classes = (IsSuperuserOrIsSelf,) # @action(detail=True, methods=['put']) def post(self, request): phone = request.data.get('phone' , False) # new_password = request.data.get('new_password') if phone: old = ResetPhoneOTP.objects.filter(phone__iexact = … -
How to pass data in django redirect?
I want to pass JSON data with redirect URL, I used HttpResponseRedirect path('session_data_req/', SessionDataFetch.as_view(url='http://0.0.0.0:8080/reciever/')), class SessionDataFetch(APIView): url = None pattern_name = None def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) data = {"a": "a", "b": "b"} return HttpResponseRedirect(url, data=data) but I am getting an error __init__() got an unexpected keyword argument 'data' I also tried to use return redirect(url, kwargs={"ok", "ok"}) but not getting kwargs data in redirected URL views class ReceiverView(APIView): def get(self, request, *args, **kwargs): print(kwargs) # data = request.data data = kwargs return Response({"a": "----| In receiver |----", "data": data}) response: { "a": "----| In receiver |----", "data": {} } Is there any way to pass data in the redirect function?... and If you are downvoting this question then let me know the reason. -
How to solve Incorrect padding error in django
Traceback: Traceback (most recent call last): File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 199, in _get_session return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\pranil\web_projects\mon_amie\onlyapp\views.py", line 11, in home if request.user.is_authenticated: File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 224, in inner self._setup() File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 360, in _setup self._wrapped = self._setupfunc() File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\middleware.py", line 24, in request.user = SimpleLazyObject(lambda: get_user(request)) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user request.cached_user = auth.get_user(request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth_init.py", line 173, in get_user user_id = get_user_session_key(request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth_init.py", line 58, in _get_user_session_key return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 64, in getitem return self._session[key] File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 204, in _get_session self._session_cache = self.load() File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\db.py", line 44, in load return self.decode(s.session_data) if s else {} File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 110, in decode encoded_data = base64.b64decode(session_data.encode('ascii')) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\base64.py", line 87, in b64decode return binascii.a2b_base64(s) Exception Type: Error at / Exception Value: Incorrect padding My views function of the page which is giving error: def home(request): if request.user.is_authenticated: return redirect('user') else: return render(request, 'home.html') What could have possibly gone wrong cause … -
Setting a default value for model fields in Django
I want to create a model in Django with two fields {initial price, current price} .. is there a way in Django to set the default value for the current price field to be the same as the initial price field value? -
Django: How to parse slug from url typed in address bar?
I am trying to simulate Google's behavior where the user types something on the address bar of the browser and the Django server checks for any exact matches in the database. If so, a detailview of the object is rendered. If not an exact match, then a list of matches on substrings are rendered with ListView. This behavior works fine when the user types into a search form. For instance, when the user just types the letter 'j' in the search form and hits submit, the Django server matches on 3 objects in the data base 'Django, Java, node.js' and renders this list through ListView. If there is an exact match, say the user typed 'java', then the Django server renders details about the object 'java' in a Detail view. The relevant segments of the html form, urls.py, and views.py are displayed below <form method="GET" action="{% url 'searchwiki' %}"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> urls.py : from django.urls import path from . import views urlpatterns = [ path("", views.EntryListView.as_view(), name="index"), path("entries/",views.EntryListView.as_view(),name='entries'), path("entry/<int:pk>",views.EntryDetailView.as_view(),name="entry_detail"), path("<int:pk>", views.EntryDetailView.as_view(), name="path_entry-detail"), **# path("<slug:subject>",views.get_obj_orlist), path("<slug:subject>",views.EntryDetailView.as_view()),** path("random/",views.randompage,name="randompage"), **path("searchwiki/",views.searchwiki,name="searchwiki"),** ] views.py : def searchwiki(request): searchtoken = request.GET.get('q') try: entry = Entry.objects.get(subject=searchtoken) except Entry.DoesNotExist: entries = Entry.objects.filter(subject__icontains=searchtoken) print("Inside … -
add serial number in a row automatically in django-model?
i want to create customer data table as such i want to create customer id- as unique id code - i did the following - class customer(models.Model): def number(self): no = customer.objects.aggregate(Max('customerid')) if no == None: return 1 else: return no + 1 customerid = models.IntegerField(_('Code'), unique=True, \ default=number) customername=models.CharField(max_length=1000) def __str__(self): return self.customername the code is giving me error-undefined variable:'_' i want to know- can this be a primary key? if i have 10 customers later i deleted one then will the id change or it will keep on adding as 11? i want a fixed unique id even if its deleted later DO I have to use any other Code? Please Help -
How to test CSRF protected sites using gatling?
I am testing a django powered site using gatling. My forms are protected by a CSRF token: <input type="hidden" name="csrfmiddlewaretoken" value="EqFQPv1fdfJjAfq4wFcWkVsecmWSisQzQU0ee1utyOEpJd7edxk3DMhAQNMpI2DK"> How can I test my forms using Gatling testing framework? -
Python decorator not calling intermittenly
decorator.py file: ========================= class Decorator1: def __init__(<params>): <code snippet1> <code snippet2> example.py file: ====================== from decorator import decorator class Example1: @Decorator1(<args, kwargs>) def method1: <method code snippet> @Decorator1(<args, kwargs>) def method2: <method code snippet> def method3: <method code snippet> All three functions are part of different API execution flows, intermittently decorators are not executing and not throwing any exception. Is this because of multiple usages in a single class/file with only one-time importing decorator class? -
Django Logging per user
I have an application in Django in witch I have logging... My problem is, that if two users are using an application at the same time, logs are mixed. That way, I can't see where the application stuck if there is a bug... How to add a user to a log file (maybe in formatters) or to do different files for each user... Right now I have logging set: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters' : { 'standard': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { -
Django error: name 'LOGIN_REDIRECT_URL' is not defined
I am trying to take advantage of the global variable LOGIN_REDIRECT_URL in the settings.py file in my Django project to avoid duplicating URLs everywhere. In my settings.py I have redefined LOGIN_REDIRECT_URL like so: LOGIN_REDIRECT_URL = "my_app_name:index" I am trying to use LOGIN_REDIRECT_URL in my login_view in views.py as follows: def login_view(request): form = LoginForm(data=request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse(LOGIN_REDIRECT_URL)) else: ... However, when I log in I get the following error message: name 'LOGIN_REDIRECT_URL' is not defined I thought about importing LOGIN_REDIRECT_URL from settings.py but that feels wrong since other variables from there do not need to be imported anywhere. What am I doing wrong? -
Error when deploying an application with django in apache
Hello please anybody help me please ( I am new with this environment ) please see the code: AND WHEN YOU GO TO THE URL, IT APPEARS IN THE INDEX OF THE WEB SERVER PANEL, NORMALLY I HAVE A CONSTRUCTION INDEX, BUT NOW, NOT EVEN MY PROJECT COMES OUT. IT ONLY SHOWS THE INDEX THAT I MENTIONED ABOVE(SER SERVER PANEL). APACHE SERVER http <VirtualHost *:80> ServerName mydomain.com ServerAlias www.mydomain.com ServerAdmin webmaster@mydomanin.com DocumentRoot /home/admin/public_html UseCanonicalName Off ScriptAlias /cgi-bin/ /home/admin/public_html/cgi-bin/ #CustomLog /usr/local/apache/domlogs/mydomain.com.bytes bytes #CustomLog /usr/local/apache/domlogs/mydomain.com.log combined ErrorLog /usr/local/apache/domlogs/mydomain.com.error.log # Custom settings are loaded below this line (if any exist) # IncludeOptional "/usr/local/apache/conf/userdata/admin/mydomain.com/*.conf" <IfModule mod_setenvif.c> SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on </IfModule> <IfModule mod_userdir.c> UserDir disabled UserDir enabled admin </IfModule> <IfModule mod_suexec.c> SuexecUserGroup admin admin </IfModule> <IfModule mod_suphp.c> suPHP_UserGroup admin admin suPHP_ConfigPath /home/admin </IfModule> <IfModule mod_ruid2.c> RMode config RUidGid admin admin </IfModule> <IfModule itk.c> AssignUserID admin admin </IfModule> WSGIScriptAlias / /home/admin/public_html/myproject/myfolder/wsgi.py <Directory "/home/admin/public_html/myproject"> <Files wsgi.py> Require all granted </Files> </Directory> <IfModule proxy_fcgi_module> <FilesMatch \.php$> SetHandler "proxy:unix:/opt/alt/php-fpm72/usr/var/sockets/admin.sock|fcgi://localhost" </FilesMatch> </IfModule> </VirtualHost> https <VirtualHost *:443> ServerName mydomain.com ServerAlias www.mydomain.com ServerAdmin webmaster@mydomain.com DocumentRoot /home/admin/public_html UseCanonicalName Off ScriptAlias /cgi-bin/ /home/admin/public_html/cgi-bin/ #CustomLog /usr/local/apache/domlogs/mydomain.com.bytes bytes #CustomLog /usr/local/apache/domlogs/mydomain.com.log combined ErrorLog /usr/local/apache/domlogs/mydomain.com.error.log # Custom settings are loaded below this line (if any exist) # … -
How to put an IntegerField and a Text into the same line in a survey using CSS / Django?
I do a survey and would love to put my IntegerField into the same line as my text. Right now, it is displayed vertically (InputField under the sentence) as seen in the picture (How it looks right now) but I would like to have a small IntegerField within the same line or the same sentence. Anybody has an idea on how to do it? I am not really familiar with css. Maybe the css_class could help there. Thanks! forms.py class SurveyPolicy(forms.Form): policy6b = forms.IntegerField( # required=False, label='', widget=forms.NumberInput() ) def __init__(self, *args, **kwargs): super(SurveyPolicy, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'survey-form' self.helper.label_class = 'col-lg-12' self.helper.field_class = 'col-lg-12' self.desc = "example" self.helper.layout = Layout( Fieldset( "<hr><h6 style='color: #2D2D2D; font-family: Arial;'>Die Maßnahmen sollten zu</h5>", Div('policy6b', css_class='form-group row-ml-0 mb-0'), ), Fieldset( "<h6 style='color: #2D2D2D; font-family: Arial;'>% durch eine Abgabe auf konventionelle Energieträger wie z.B. Erdgas finanziert werden - schließlich sollten Leute, die mehr CO2-Ausstoß verursachen auch mehr bezahlen.</h5>", ), [...]