Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to turn off superfluous headers in Django?
I have a Django application running with a WSGI server. Things are working fine, but my responses are coming back with lots of headers like - { 'Date': 'Fri, 20 Sep 2019 15:11:34 GMT', 'Server': 'WSGIServer/0.2 CPython/3.7.3', 'Content-Type': 'application/json', 'TERM_PROGRAM': 'iTerm.app', 'PYENV_ROOT': '/Users/siddharth.saha/.pyenv', 'TERM': 'xterm-256color', 'SHELL': '/bin/zsh', 'TMPDIR': '/var/folders/r1/v5jp8l016j9b3nb97tk224qs07cp6s/T/', 'Apple_PubSub_Socket_Render': '/private/tmp/com.apple.launchd.jAa5tsZccM/Render', 'TERM_PROGRAM_VERSION': '3.3.0', 'TERM_SESSION_ID': 'w0t2p0:EB83BE59-190F-4819-BE37-618016E6C685', 'PYENV_VERSION': 'hodor_env', 'ZSH': '/Users/siddharth.saha/.oh-my-zsh', 'USER': 'siddharth.saha', 'COMMAND_MODE': 'unix2003', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.FB43X5s2aG/Listeners', 'PYENV_DIR': '/Users/siddharth.saha/src/hodor/hodor_app', '__CF_USER_TEXT_ENCODING': '0x407658D9:0x0:0x0', 'VIRTUAL_ENV': '/Users/siddharth.saha/.pyenv/versions/3.7.3/envs/hodor_env', 'PAGER': 'less', 'PYENV_VIRTUAL_ENV': '/Users/siddharth.saha/.pyenv/versions/3.7.3/envs/hodor_env', 'LSCOLORS': 'Gxfxcxdxbxegedabagacad', 'PATH': '/Users/siddharth.saha/.pyenv/versions/hodor_env/bin:/usr/local/Cellar/pyenv/1.2.13/libexec:/Users/siddharth.saha/.pyenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Users/siddharth.saha/src/go_parsers/vendor/bin', 'PWD': '/Users/siddharth.saha/src/hodor/hodor_app', 'ITERM_PROFILE': 'Default', 'PYENV_HOOK_PATH': '/Users/siddharth.saha/.pyenv/pyenv.d:/usr/local/Cellar/pyenv/1.2.13/pyenv.d:/usr/local/etc/pyenv.d:/etc/pyenv.d:/usr/lib/pyenv/hooks', '_OLD_VIRTUAL_PS1': '${ret_status} %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)', 'XPC_FLAGS': '0x0', 'XPC_SERVICE_NAME': '0', 'PYENV_SHELL': 'zsh', 'SHLVL': '1', 'HOME': '/Users/siddharth.saha', 'COLORFGBG': '7;0', 'GOROOT': '/usr/local/go', 'LC_TERMINAL_VERSION': '3.3.0', 'ITERM_SESSION_ID': 'w0t2p0:EB83BE59-190F-4819-BE37-618016E6C685', 'HODOR_BUILD_ENV': 'dev', 'LESS': '-R', 'LOGNAME': 'siddharth.saha', 'LC_CTYPE': 'UTF-8', 'GOPATH': '/Users/siddharth.saha/src/go_parsers/vendor:/Users/siddharth.saha', 'LC_TERMINAL': 'iTerm2', 'PYENV_ACTIVATE_SHELL': '1', 'SECURITYSESSIONID': '186a9', 'COLORTERM': 'truecolor', 'DJANGO_SETTINGS_MODULE': 'api.settings', 'TZ': 'UTC', 'RUN_MAIN': 'true', 'SERVER_NAME': '1.0.0.127.in-addr.arpa', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '8000', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/ping', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'CONTENT_TYPE': 'application/json', 'HTTP_HOST': 'localhost:8000', 'HTTP_USER_AGENT': 'python-requests/2.18.1', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT': '*/*', 'HTTP_CONNECTION': 'keep-alive', 'wsgi.input': '<_io.BufferedReader name=4>', 'wsgi.errors': "<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>", 'wsgi.version': '(1, 0)', 'wsgi.run_once': 'False', 'wsgi.url_scheme': 'http', 'wsgi.multithread': 'True', 'wsgi.multiprocess': 'False', 'wsgi.file_wrapper': "<class 'wsgiref.util.FileWrapper'>", 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '36' } As you can see lots … -
Django read frame returning decimal fields value after rounding or truncating
Django read frame is returning decimal fields value after rounding or truncating. How can this be prevented? My Django Model class Stock(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=20, db_index=True) price = models.DecimalField(max_digits=19, decimal_places=2) diff = models.DecimalField(max_digits=19, decimal_places=5) open_price = models.DecimalField(max_digits=19, decimal_places=2) previous_close = models.DecimalField(max_digits=19, decimal_places=2) low52 = models.DecimalField(max_digits=19, decimal_places=2) high52 = models.DecimalField(max_digits=19, decimal_places=2) last_updated = models.DateTimeField() objects = DataFrameManager() def save(self, *args, **kwargs): ''' On save, update timestamps ''' self.last_updated = timezone.now() return super(Stock, self).save(*args, **kwargs) def __str__(self): return str(self.code) enter image description here But when I read data using django readframe then I see In [41]: read_frame(Stock.objects.filter(code='ABB')) Out[41]: id name code price diff open_price previous_close low52 high52 last_updated 0 1 ABB India Ltd. ABB 1400.00 5.02 1328.60 1325.45 1190.00 1670.00 2019-09-20 14:51:28.666744+00:00 -
Django-crispy-forms: set css for individual field and inputs
Is there a way to specify the css for an individual field and input in django crispy forms? I am using bootstrap4 and would like to use a horizontal form for a few fields in my form. I know you can use a self.helper to set label.class and field.class but I presume that applies to all field. I only want to change the label and field class on a few of my fields. -
What is the command to search a content in all the model fields at once?
I am developing an app with Django. I have developed a search bar to filter the database contents. I want that, when the user clicks on the search button, the indicated content is searched in all the model fields. My model has 16 fields, so my filter command will be a very long line, like: selected_entries = glossary_entry.objects.filter(Q(field1__icontains=query) | Q(field2__icontains=query)) | ...ETC ETC... | Q(field16__icontains=query)) Here you can see this line in my view function, in views.py: def glossario(request): query = request.GET.get('q') template = "glossario.html" # query applied if query: query = request.GET.get('q') selected_entries = glossary_entry.objects.filter(Q(field1__icontains=query) | Q(field2__icontains=query)) | ...ETC ETC... | Q(field16__icontains=query)) return render(request, template, {'all_entries':selected_entries}) # no query else: all_entries = glossary_entry.objects.all return render(request, template, {'all_entries':all_entries}) Is there a shorter command to do the same? Like: selected_entries = glossary_entry.objects.filter(Q(ALL_MODEL_FIELDS_ICONTAINS(model=MyModel)=query)) Note: ALL_MODEL_FIELDS_ICONTAINS is my invention -
How to display and save mutiple instances of a django form based on variable amount?
I've been looking around the site and can't seem to find an answer. Same for the django docs. The issue is I can't seem to save multiple instances of the same form. I'm trying to have a user set up a weekly calendar for a sports club. They land on a page with check boxes of each day they have activities. So if they click monday, tuesday, wednesday. Three instances of the DAY model are created created. Which works fine. Then, on the next page. Based on the amount of Days they have chosen, I would like a PeriodsForm (for this example let's just say they have one period each day). Then they can set what time each day starts and finises. I just can't seem to save the data. I was hoping someone has come across this before. Many thanks. I've tried using the modelformset_factory() but it's far too rigid. I also tried prefixes but I can't seem to loop through the forms on the POST. ### views.py def create_timetable_days(request): club = request.user.club form = TimetableCreateForm(request.POST or None) if len(list(Day.objects.filter(club=club))) > 0: return redirect('/timetables/create_timetable_times') if form.is_valid(): for item in form['Days']: if item.data['selected']: day = Day(name=item.data['label'], club=club) day.save() return redirect('/timetables/create_timetable_times') … -
Send mail in Django from Yandex
I want to send mail with Yandex. I got data from my serializer class and send with EmailMessage. When ı tried to send data ı got an error on DigitaOcean cloud server. Settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.xxxx.com.tr' EMAIL_PORT = 587 EMAIL_HOST_USER = 'info@xxxx.com.tr' EMAIL_HOST_PASSWORD = 'EN//7798' DEFAULT_FROM_EMAIL = 'info@xxxx.com.tr' EMAIL_USE_TLS = True Serializers.py: from django.core.mail import EmailMessage class InvoiceSerializer(ModelSerializer): # program = CharField(source='program.name', read_only=True) class Meta: model = Invoice fields = '__all__' def create(self, validated_data): # message = validated_data.pop('context') message_obj = super().create(validated_data) email = EmailMessage(message_obj.full_name, message_obj.email, to=['example@gmail.com']) email.send() return message_obj Where is my fault? -
How to allow tabulators when displaying string on website?
I pass the string named 'data' to a html page. With the following command i can generate linebreaks with '\n' in the string: {{ data | linebreaks}} The sting also contains tabs '\t' which are ignored and not displayed. So i look for some filter allowing tabs, something like: {{ data | linebreaks | tabulators}} But 'tabulators' is not a predefined filter. Does someone know what command i am looking for? -
Django Rest Framework - Group data by dynamic Key
I'm trying to format data when querying my API. I can retrieve my data like that : "results": [ { "Cat1": [ { "job": String, "position": Integer } ] }, { "Cat1": [ { "job": String, "position": Integer } ] }, { "Cat2": [ { "job": String, "position": Integer } ] } ] But I want something like that: "results": [ { "Cat1": [ { "job": String, "position": Integer }, { "job": String, "position": Integer } ] }, { "Cat2": [ { "job": String, "position": Integer } ] } ] I use a serializer like this: class CustomSerializer(serializers.ModelSerializer): cat = CatSerializer() job = JobSerializer() class Meta: model = MyModel fields = '__all__' def to_representation(self, value): return { value.cat.name: [{"job": value.job.name, "position": value.position, }] cat1 and cat2 are dynamics, they are from another table. I don't understand how to create my arrays properly using those serializers. The category is a @Property field in my model who's a foreign key of job. How should I deal with serializers to format my data properly ? -
TypeError: 'str' object is not callable -- on request to API
I am trying to run a minimal Django server but I get this error when I send a get request to the /api/v1/ endpoint. I realize similar questions have been asked before, and I believe this is occurring because of an invalid import reference, but I am unable to see where the mistake I made is. The filesystem (minus cache + migrations folders): . ├── api │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── blog_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── Pipfile ├── Pipfile.lock └── posts ├── admin.py ├── apps.py ├── __init__.py ├── models.py ├── tests.py └── views.py api/views.py from django.shortcuts import render # Create your views here. from rest_framework import generics from posts import models from .serializers import PostSerializer class PostList(generics.ListCreateAPIView): queryset = models.Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Post.objects.all() serializer_class = PostSerializer api/serializers.py from rest_framework import serializers from posts import models class PostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'author', 'title', 'body', 'created_at',) model = models.Post api/urls.py from django.urls import path from .views import PostList, PostDetail urlpatterns = [ … -
slack: challenge_failed using ngrok
I'm trying to test slack through ngrok. But the link does not pass in any way https://a333d0d4.ngrok.io/events/ class Events(APIView): def post(self, request, *args, **kwargs): slack_message = request.data if not 'token' in slack_message: parse_message.delay(slack_message) return Response(status=status.HTTP_200_OK) -
Change admin URLs in django
I want to change basic admin urls, for example I have the following URL: http://127.0.0.1:8000/admin/EmailSend/contact/1/change/ and I want to change URL to http://127.0.0.1:8000/admin/EmailSend/contact/{self.Name}/change/ -
Filter/order django rest api on a property=value but property is a value instead of a field
Consider an object that has multiple properties. class Object(models.Model): name= Charfield(max_length=80) class Property(models.Model): object= ForeignKey(Object, related_name='properties') name= Charfield(max_length=80) value= Charfield(max_length=80) I would like to provide an api accessible listview for the Object model, but I'm failing at ordering the ObjectList by property value as well as at sorting the the ObjectList by property value. To make the example more tangible you can imagine that Object has as type book, and an object of book has, among other properties, a property with name title and a value such as 20,000 Leagues Under the Sea. I would like to be able to be able to specify ?order_by=title and to be able to filter ?title__contains=League (or at least ?title="20,000 Leagues Under the Sea". I already did try to annotate Object with title="20,000 Leagues Under the Sea" and I'm able to show the title in the ObjectSerializer as if it was a field, but then ordering by this field does not work. -
Calculate percentage based on the sum value in the django view
I would like to display the percentage mark instead of the total sum of the mark. Right now i have a table that display the student name and their mark attendance. I would like to convert the mark attendance into a percentage. the current implementation is: Student Name Attendance Annie 200 Anny 150 But i would like to show the attendance in percentange. for example: Student Name Attendance Annie 100% Anny 85% i am not sure how to implement the method. But i have tried this: my Model.py: class MarkAtt(models.Model): studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=1) attendance = models.IntegerField(default=100) #1 is present def get_percentage(self): ttlCount = MarkAtt.objects.filter(studName).count() perc = ttlCount / 1100 *100 return perc my Views.py: def attStudName(request): students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance')) context = { 'students' : students } return render(request,'show-name.html',context) Do advise me. -
Django channels daphne returns 200 status code
I have setup a Django application with Nginx + uwsgi. The application also uses django-channels with redis. When deploying the setup in an individual machine, everything works fine. But when I tried to setup the app in 2 instances and setup a common load balancer to coordinate the requests, the request get properly routed to the daphne process and I can see the logs. But the status code returned from the daphne process is 200 instead of 101. Load balancer nginx conf: upstream webservers { server 10.1.1.2; server 10.1.1.3 } server { location / { proxy_pass http://webservers; } } Versions used: daphne==2.2.4 channels==2.1.6 channels-redis==2.3.2 All the routing works fine and there are no errors, but just that the status code returned is 200 instead of 101. -
How to filter by dictionary key using FilterSet of django tables2
The problem is that I can not filter a record from my dictionary when trying to search by key. Just to notice that I am feeding my filterset with a dictionary and not with a queryset. To clarify look the code below: views snippet class CompletedWithTotalsWholesaleOrderProductsListView(LoginRequiredMixin,SingleTableMixin, FilterView): login_url = '/login/' table_class = CompletedWithTotalsWoocommerceOrderProductsTable model = Woo_Order_Has_Products template_name ='woo_commerce_orders/completed_with_totals_wholesale_order_products_list.html' filterset_class = WoocommerceOrderProductsFilter def get_context_data(self, **kwargs): context = super(CompletedWithTotalsWholesaleOrderProductsListView, self).get_context_data(**kwargs) #object_list=Woo_Order_Has_Products.objects.filter(woo_order__is_completed=True,woo_order__is_invoiced=True,woo_order__is_approved=True,woo_order__is_paid=True) #populate the table with a sample dictionary data = [{'woo_order_id':8,'seller_commission':88, 'net_total':888, 'vat':8888, 'gross_total':88888}, {'woo_order_id':9,'seller_commission':99, 'net_total':999, 'vat':9999, 'gross_total':99999},] f = self.filterset_class(self.request.GET, queryset=data) context['filter'] = f table = self.table_class(data) # if self.request.user.first_name!="neuro": # table.exclude = ('delete',) if not self.request.user.is_superuser: table.exclude = ('delete',) RequestConfig(self.request).configure(table) context['table'] = table has_filter = any(field in self.request.GET for field in set(self.filterset_class.get_fields())) context['has_filter'] = has_filter return context tables snippet class CompletedWithTotalsWoocommerceOrderProductsTable(tables.Table): woo_order_id = tables.Column(verbose_name= 'ID Order',orderable=False,empty_values=()) seller_commission=tables.Column(verbose_name= 'Seller Commission(€)',orderable=False,empty_values=()) net_total=tables.Column(verbose_name= 'Net Total(€)',orderable=False,empty_values=()) vat=tables.Column(verbose_name= 'Vat(€)',orderable=False,empty_values=()) gross_total=tables.Column(verbose_name= 'Gross Total(€)',orderable=False,empty_values=()) class Meta: #define the model model = Woo_Order_Has_Products template_name = 'django_tables2/bootstrap.html' exclude = ('id','wholesale_price_category','printed_description','current_previous_price','vat_percentage','wholesale_product','price','quantity','woo_order') sequence = ('woo_order_id','seller_commission','net_total','vat','gross_total') filters snippet class WoocommerceOrderProductsFilter(django_filters.FilterSet): woo_order_id = django_filters.CharFilter(lookup_expr='exact') class Meta: model = Woo_Order_Has_Products fields = ['woo_order_id'] My purpose (and the problem) is to search only by woo_order_id. -
What's the proper order in which Django cache middleware should be added?
I'm trying to add caching to my Django project and I'm failing to understand documentation on middleware ordering. Consider the following MIDDLEWARE list, which is mostly default: 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', 'simple_history.middleware.HistoryRequestMiddleware' ] If I'm understanding this piece of documentation correctly, I'm supposed to add three new entries to MIDDLEWARE list. Is there more than one proper ordering for my case? -
Celery Tasks are executing multiple times in Django Application
I have a Django application where I defined a few @task functions under task.py to execute at given periodic task. I'm 100% sure that the issue is not caused by task.py or any code related but due to some configuration may be in settings.py or my celery worker. Task does execute at periodic task but at multiple times. Here are the celery worker logs: celery -A cimexmonitor worker --loglevel=info -B -c 4 [2019-09-19 21:22:16,360: INFO/ForkPoolWorker-5] Project Monitor Started : APPProject1 [2019-09-19 21:22:16,361: INFO/ForkPoolWorker-4] Project Monitor Started : APPProject1 [2019-09-19 21:25:22,108: INFO/ForkPoolWorker-4] Project Monitor DONE : APPProject1 [2019-09-19 21:25:45,255: INFO/ForkPoolWorker-5] Project Monitor DONE : APPProject1 [2019-09-20 00:22:16,395: INFO/ForkPoolWorker-4] Project Monitor Started : APPProject2 [2019-09-20 00:22:16,398: INFO/ForkPoolWorker-5] Project Monitor Started : APPProject2 [2019-09-20 01:22:11,554: INFO/ForkPoolWorker-5] Project Monitor DONE : APPProject2 [2019-09-20 01:22:12,047: INFO/ForkPoolWorker-4] Project Monitor DONE : APPProject2 If you check above time interval, tasks.py executes one task but 2 workers of celery takes the task & executes the same task at the same interval. I'm not sure why 2 workers took for one task? settings.py .. .. # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True .. .. .. ######## CELERY … -
django - adding userprofile to registration form. getting csrf token error
I have a registration form and am adding a user profile to add another field. but when i submit i am getting CSRF error. need help to find what i a missing. First time when i submitted it was updated, then i am getting the CSRF error models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Assigned_Group = models.CharField(max_length=500) def __str__(self): return self.user.username views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) profile_form = UserProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('index') else: form = RegistrationForm() profile_form = UserProfileForm() context = {'form': form, 'profile_form':profile_form} return render(request, 'registration/register.html', context ) index.html ```python def index(request): if request.user.is_authenticated: username = request.user.username else: username = 'not logged in' context = {'username':username} return render(request, 'index.html', context) urls.py path('Register/', views.register, name='register'), -
Catching bulk events in Django
I have Book model. It has some fields like title, year publish and etc. Also, i have overrided save() method. When new books is adding, it checks if book exsists, it creating new directory with name self.title in MEDIA_ROOT path. def save(self, *args, **kwargs): book_dir = os.path.join(MEDIA_ROOT, self.title) # check that at least one file is loading if all([self.pdf, self.fb2, self.epub]): raise ValidationError("At least 1 file should be uploaded!") # create book's directory if it not exists if os.path.exists(book_dir): raise ValidationError("This book is already exists!") else: os.mkdir(book_dir) # rename and edit storage location of books to book_dir for field in [self.image, self.pdf, self.fb2, self.epub]: field.storage.location = book_dir super().save(*args, **kwargs) # Call the "real" save() method. Also i have overrided delete() method, that just remove directory of deleted book. def delete(self, *args, **kwargs): book_dir = os.path.join(MEDIA_ROOT, self.title) rmtree(book_dir) super().delete(*args, **kwargs) # Call the "real" delete() method. delete() method works well if i delete only 1 book. But, if i want to delete multiple files (all actions take place in the admin panel), only DB records got deleted. So, i want to just catch this moment to remove directory of deleted book. -
m2m_changed when items added and removed
I'm wondering if it's possible to gather the 'end state' of a m2m field in Django? I'm currently using m2m_changed.connect(myfunction, sender=MyModel.tests.through) And I have: myfunction(**kwargs): action = kwargs.pop('action', None) instance = kwargs.pop('instance', None) if action in ["post_remove", "post_add"]: instance.owned_tests = instance.tests.count() instance.save() My problem is that if I add and remove items from the m2m field and then save, two m2m_changed signals are fired, one for the add, and one for the remove. Is there any way to group these together in order to only have myfunction called once when all changes to the m2m field are finished? -
2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)" in docker-compose up
I'm trying to start the server through docker-compose up I'm get an error: 2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)" docker-compose.yml version: '3' services: db: image: mysql:5.7 environment: MYSQL_DATABASE: 'slack_bot1' MYSQL_USER: 'root' MYSQL_PASSWORD: '' MYSQL_ROOT_PASSWORD: '****' volumes: - /opt/slack_bot/mysql_data:/var/lib/mysql redis: image: "redis:alpine" volumes: - /opt/slack_bot/redis_data:/var/lib/redis web: build: . command: python manage.py runserver 0.0.0.0:8001 ports: - "8001:8001" depends_on: - db Dockerfile FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /home/slack_bot ADD requirements.txt /home/slack_bot/ RUN set -e; \ apk add --no-cache --virtual .build-deps \ gcc \ libc-dev \ linux-headers \ mariadb-dev \ python3-dev \ ; RUN pip install -r requirements.txt ADD . /home/slack_bot/ EXPOSE 8001 CMD ["python", "manage.py", "runserver", "0.0.0.0:8001"] -
Django redirect user after login
i have problem with redirecting user after login into base.html which is in main template folder. Django can't find this template. How to properly setup things for this to work? django structure: accounts main_folder settings.py urls.py staticfiles templates base.html short app structure accounts templates accounts login.html urls.py views.py settings.py templates part 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', ], }, }, ] accounts urls.py from django.urls import path from .views import* urlpatterns = [ path('', login_view), ] accounts view.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib import messages def login_view(request): if request.method == 'POST': # get posted data username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) # handle user authentication if user is not None and user.is_active and user.is_authenticated: login(request, user) # move user to main page return redirect('base') return render(request, 'accounts/login.html') -
How to implement a button of the searchbar erasing the query? Django environment)
I am developing a webapp in Django. I developed a nice search bar with two buttons. One of these (fa fa-search) is to search and display the results of the database, and it is altrady working. I would like that, when my user clicks on the other one (fa fa-trash), the code erases the query and reloads all the unfiltered results. How do I do it? Here is my code: in views.py: def glossario(request): query = request.GET.get('q') template = "glossario.html" # query apply if query: query = request.GET.get('q') #q è variabile risultante dalla query del database selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query)) return render(request, template, {'all_entries':selected_entries}) # no query else: all_entries = glossary_entry.objects.all return render(request, template, {'all_entries':all_entries}) in glossario.html: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="topnav"> <a id="pulsante_ricerca_avanzata" href="#Ricerca_avanzata">Ricerca avanzata</a> <div id="blocco_ricerca_semplice" class="search-container"> <form method="GET" action="{% url 'glossario' %}"> <input type="text" placeholder="Ricerca terminologia..." name="q" value="{{request.GET.q}}"> <button id="cancel_search_button" type=""><i class="fa fa-trash"></i></button> <button id="search_button" type="submit"><i class="fa fa-search"></i></button> </form> </div> </div> -
Django fieldset.html override
So I decided to override all the Django templates for a custom look and feel for my WebApp. One problem I'm coming across though, is that I want to change the classes of these fields to form-control (I'm using bootstrap). I see that there's a built in function is_checkbox but there isn't anything to see if it is an input tag or a select tag. What I basically want to do is for Django to iterate over all the fields in the field set if a field is an input tag, I want to add the form-control class to it and if it is a select tag, I want to add the selectpicker class to it. Here's the Django code I'm referencing: <fieldset class="module aligned {{ fieldset.classes }}"> {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %} {% if fieldset.description %} <div class="description">{{ fieldset.description|safe }}</div> {% endif %} {% for line in fieldset %} <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} {% for field in line %} <div{% … -
I can't get the values from django dropzone into view
I have trouble getting the django Dropzonejs values of the chosen file into django. It just creates an empty file object in the models. The problem is that I can't get the values into the model. It just creates aa blank model. HTML: <form class="dropzone" action="{% url 'teacher_assignment_add_file' OBJECTID %}" method="POST"> {% csrf_token %} <div class="fallback"> <input name="Assignment-File" type="file" multiple /> </div> </form> <ul class="list-group list-group-activity dropzone-previews flex-column-reverse"> {% for file in files %} <li class="list-group-item"> <div class="media align-items-center"> <ul class="avatars"> <li> <div class="avatar bg-primary"> <i class="material-icons">insert_drive_file</i> </div> </li> </ul> <div class="media-body d-flex justify-content-between align-items-center"> <div> <a href="{% url 'file123' file %}" data-filter-by="text">{{ file }}</a> <br> </div> <div class="dropdown"> <button class="btn-options" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="material-icons">more_vert</i> </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#">Download</a> <a class="dropdown-item" href="#">Share</a> <div class="dropdown-divider"></div> <a class="dropdown-item text-danger" href="#">Delete</a> </div> </div> </div> </div> </li> {% endfor %} View: @login_required def teacher_assignment_add_files(request, assignment_id): if request.method == 'POST': file = request.POST.get('Assignment-File') file = File(file=file) file.save() assignment = Assignment(id=assignment_id) assignment.files.add(file.id) return redirect('teacher-detail-assignment', id = assignment_id)