Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to clear or resize a textarea if website is duplicated?
If the user duplicates the website, everything else is reset except for the textarea. How can I clear the textarea if the website is duplicated OR resize the textarea on given Input Original Website Duplicated Website I already tried adding textarea.value = ""; in the JavaScript file but it is not properly working. Is there an easier way than checking the cookies to find out if the website is being duplicated? I only want to remove or resize the textarea, the information if the website is being duplicated does not matter. The backend is made with django. -
Elasticsearch Python Django: How to limit the output text content and highlight the input keyword
This is my search function in views.py def search(request, pk, slug): es = Elasticsearch() es_client = Elasticsearch(['http://127.0.0.1:9200']) print('called search') search_text = request.GET.get('qq') print('Search text: {}'.format(search_text)) print('cluster id/ ealstic search index: {}'.format(pk)) s = None count = 0 try: if search_text: s = Search(index=str(pk)).using(es_client).query("match", content=search_text) response = s.execute() count = 0 for hit in s: count += 1 print(str(count) + ' - ' + str(hit.currnet_url)) #print(hit.content) else: print('nothing more found') else: print('No text to search') except Exception as e: count = 0 print('Exception caught') msg = 'Cluster is not ready to be searched' return render(request, 'base_app/cluster_search.html', {'warning':msg, 'count':count}) return render(request, 'base_app/cluster_search.html', {'cluster':slug, 'hits':s, 'count':count}) This is how I am indexing data to Elasticsearch. def elastic_indexer(text, depth, url, clusrer_id): es_client = Elasticsearch(['http://127.0.0.1:9200']) doc = { "date": time.strftime("%Y-%m-%d"), "currnet_url": url, "depth": depth, "content": text } res = es_client.index(index= str(clusrer_id), doc_type="_doc", body=doc) print(res["result"]) This is the frontend template where the users input a text to search. {% extends "account/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Search" %}{% endblock %} {% block content %} <a href="{% url 'clusters' %}">Go Back</a> <P style="font-size:17px;">You are searching in {{cluster.title}}</P> <form method="GET" action=""> {% csrf_token %} <button class="btn btn-primary" action="">Search</button> <input … -
Django: change TextField before save
This is my model : class Card(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) imp_id = models.TextField(null = True) And here is my view : def Add(request): if request.method == 'POST': form = Add_card(request.POST) if form.is_valid(): save = form.save(commit = False) save.user = request.user save.imp_id = "asd" # I tried to change it here but I failed save.save() else: form = Add_card() cards = Card.objects.all() return render(request, 'addcard.html', {'form': form, 'cards' : cards}) How can I change that textfield before save? -
How do I pass data to another view function for processing
I have the following code that i need to pass on to another function, process_payment for further processing. I've tried the code below but it doesn't seem to work as expected. def SubscribePage(request): if request.method == 'POST': form = PaymentForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] amount = '20' return redirect(process_payment(name, email, phone, amount)) else: form = PaymentForm() context = { 'form': form } return render(request, 'subscribe.html', context) Please advise on where i could be going wrong. Regards. -
django : ValueError - Cannot serialize
i have error in my django project . when i run 'python manage.py makemigrations' command than come error. ValueError: Cannot serialize: <django.db.models.query_utils.DeferredAttribute object at 0x000001B5A3078940> models.py class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) quntity = models.IntegerField(default=1) price = models.IntegerField(default=Product.price) address = models.CharField(max_length=200) phone = models.CharField(max_length=13) date = models.DateTimeField(auto_now=True) print(Product.price) def __str__(self) -> str: return self.product.name admin.py from django.contrib import admin from .models import Order # Register your models here. class OrderAdmin(admin.ModelAdmin): models = Order list_display =['product','customer','quntity','price','address','phone','date'] admin.site.register(Order,OrderAdmin) and this is my error page:- -
How to filter custom urls in ModelViewSet with django-filters
class ExportTabView(ModelViewSet): permission_classes = [UserHasDatasetChangeAccess] queryset = JobTable.objects.all() filterset_fields = [ "job_type", "action", "source_table__name", "source_table__type", ] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] I am able to use django filters with above api as : /api/export-tab-view?source_table__name='temp' But after adding custom urls in this model view set, I am not able to use django filters . class ExportTabView(ModelViewSet): serializer_class = ExportTabSerializer permission_classes = [UserHasDatasetChangeAccess] queryset = JobTable.objects.all() filterset_fields = [ "job_type", "action", "source_table__name", "source_table__type", ] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] @action(detail=False) def export_dataset(self, request, id=None): """ Returns a list of all the relationship names that the given dataset has """ jobs = JobTable.objects.filter( dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, "")) ) return Response(ExportTabSerializer(jobs, many=True).data) Now filters are not working when i call api /api/export-tab-view/export_dataset?source_table__name='temp' -
How to create Conda virtual environment within project subdirectory
I want to create conda env in my project subdirectory like virtual env. Kindly explain the process to create, activate and deactivate conda env. Take my project directory as :- myProject/ -
Django .annotate TruncMonth : How to Get full range of Months
I want total earning from each month and display it in graph so im making below query Here's my query: query = UserOrderService.objects.all() query = query.annotate(month=TruncMonth('order_booking_date')).values( 'month').annotate(no_of_services=Count('pk')).annotate( total=Sum(F('service_price') * F('quantity'))).order_by('month') Above query only gives data from months where booking happend Output: "data": [ { "no_of_services": 1, "total": 26725.0, "month": "November" }, { "no_of_services": 1, "total": 26725.0, "month": "December" } ] Where as i want all data from all months Even if there's no data in that particular month Expected Output: "data": [ { "no_of_services": 0, "total": 0, "month": "January" }, { "no_of_services": 0, "total": 0, "month": "February" }, { "no_of_services": 0, "total": 0, "month": "March" }, ... { "no_of_services": 1, "total": 26725.0, "month": "November" }, { "no_of_services": 1, "total": 26725.0, "month": "December" } ] -
How can I filter time by using Django_Filters
start_time = django_filters.TimeFilter(lookup_expr='gte', field_name='created_at__hour', input_formats="%H") end_time = django_filters.TimeFilter(lookup_expr='lte', field_name='created_at__hour', input_formats="%H") Input: start_time = 10 Result: { "start_time": [ "Enter a valid time." ] } -
Get results of the search from MSSQL data base in Django web page
I have to create simple Web page which will search data in a SQL Server data base. I managed to connect to my database and run server with my simple HTML which has Label, textbox, button and listbox. Expect this, project has default settings. Could you please help me, how can i set request to DB like "Select * FROM Mac_Storage where MAC = "Here should be the text from textbox"" to button and return the results to my Web page? -
google , allauth with i18n errors on social login portal
I am trying to use allauth social login with i18n but google social login portal returns : Authorization Error Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. This is because i put allauth.urls inside i18n_patterns in main urls.py: urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns ( path("accounts/",include("allauth.urls")), ) How can i use i18n to translate allauth pages without error at social login panels? -
date formatting datefield in django
I want to have thew given format "dd/mm/yyyy" overall the application, but momentally I havee "mm/dd/yyyy". Here's the code in models.py period_from = models.DateField(db_column="Period From", blank=True, null=True) How to define it for all the datefields and in which file? -
How do web development frameworks work exactly?
To my (probably flawed) knowledge, the front-end of websites are built with HTML, CSS, and JavaScript but I hear a lot of talk about using frameworks like Django (Python), ASP.NET (C#), Ruby on Rails (Ruby), Spring (Java) etc... How do these frameworks function? At first I thought they were back-end frameworks but apparently Django can be used to help with HTML formatting and such. I thought these things are only possible with JavaScript? I understand how frameworks like React or Angular can be used because those run on JavaScript but how do these other frameworks and languages work? Do they transpile to JS or something? -
Log User in Celery Task in Django
I have an application where we do need to maintain some kind of audit log which shall display which user changed what data in the db at what time. I implemented a simple solution using signals. I therefore created an app called "actions" where I log all necessary information. To to so I connected three signals (presave, postsave and predelete): apps.py class ActionsConfig(AppConfig): name = 'actions' def ready(self): apps_to_audit = ['app1', 'app2', 'app3'] for app in apps_to_audit: app_models = apps.get_app_config(app).get_models() for model in app_models: pre_save.connect(pre_save_signal, sender=f'{app}.{model.__name__}', dispatch_uid=f'{app}_{model}_pre_save') post_save.connect(post_save_signal, sender=f'{app}.{model.__name__}', dispatch_uid=f'{app}_{model}_post_save') pre_delete.connect(pre_delete_signal, sender=f'{app}.{model.__name__}', dispatch_uid=f'{app}_{model}_pre_delete') then i created a celery function to store the data within the actions-model: tasks.py @shared_task def log_action(action): from actions.models import Action from users.models import CustomUser app_label = action.get('app') model_name = action.get('object') user_pk = action.get('user') action_type = action.get('action_type') updated_fields = action.get('updated_fields') # Get Object Object = apps.get_model(app_label=app_label, model_name=model_name) model_pk = action.get('model_pk') # Get Object instance try: target = Object.objects.get(pk=model_pk) except Object.DoesNotExist: target = None # Get User try: user = CustomUser.objects.get(pk=user_pk) except CustomUser.DoesNotExist: user = None # LOGIC TO DEFINE VERB verb = '' if action_type == 1: verb = f' created new {model_name}' elif action_type == 2: verb = f' updated {model_name}' elif action_type == 3: verb … -
Dynamic template tags in django
I'm building an html page in Django, which has the following structure: {% extends 'main/base_template.html' %} {% load filters %} {% block main_window %} <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4"> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h1 class="h2">Stuff</h1> </div> <div class="row mb-3"> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_A.html' %} </div> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_B.html' %} </div> </div> <div class="row mb-3"> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_C.html' %} </div> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_D.html' %} </div> </div> {% endblock %} And each of the stuff_X html file has the same structure, for example: <div class="row mb-3"> <div class="table-responsive"> <table class="table table-striped table-sm caption-top" style="width:40em"> <caption>Data</caption> <thead> <tr> <th scope="col">Data1</th> <th scope="col">Data2</th> <th scope="col">Data3</th> </tr> </thead> <tbody> <tr> <td id="stuff_a_data1" style="width:5em">{{ stuff_a.data1 }}</td> <td id="stuff_a_data2" style="width:5em">{{ stuff_a.data2 }}</td> <td id="stuff_a_data3" style="width:5em">{{ stuff_a.data2 }}</td> </tr> </tbody> </table> </div> </div> So the only things that actually change are some ids and the name of the data to be retrieved from the django context. Are there any mechanisms that allow me to write generic pages for cases like this? Cause currently I am handling 4 (almost) identical pages, adding snippets of code in each of them when I need … -
How to get user info from json file from django rest framework
I am having this problem. I want to fetch the data from my other file using GET method. but it always says, TypeError: Cannot read properties of undefined (reading 'then') how do I get this response data from any file? the file is given bellow APIService export default class APIService { // get user data static GetUser(userId, token) { fetch(`http://127.0.0.1:8000/pp/users/${userId}/`, { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${token}`, }, }); } static GetUserS(token) { fetch("http://127.0.0.1:8000/pp/users/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${token}`, }, }); } } -
How to display tuple items inside template
I want to use items from a tuple I'm currently using in my models.py inside my template. I added this tuple to my views' context but when I try to loop over it nothing shows up. this is my simplified view: def dashboard(request): documents = DocumentInfo.objects.filter(user=request.user) context = {'documents':documents} if request.user.role == 'theory_interviewer': template = loader.get_template('reg/scientific-info-dashboard.html') interviewed = ScientificInfo.objects.filter(is_interviewed=True).all() context['interviewed'] = len(interviewed) context['survey_choices'] = SURVEY_CHOICES return HttpResponse(template.render(request=request, context=context)) and this is my template: {% for x,y in survey_choices %} {{x}}{{y}} {% endfor %} and finally, this is the choice tuple I imported from models.py: SURVEY_CHOICES = ( ('0', 'very bad'), ('1', 'bad'), ('2', 'good'), ('3', 'very good'), ('4', 'nice') ) -
Django: Unable to add post in admin
Right now when I go to admin and want to add post, I get this message: NoReverseMatch at /admin/blog/post/add/ Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8080/admin/blog/post/add/ Django Version: 3.2.9 Exception Type: NoReverseMatch Exception Value: Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name. Exception Location: C:\Download\Development\NowaStrona_Django\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Download\Development\NowaStrona_Django\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\\Download\\Development\\NowaStrona_Django\\mysite\\my_site', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts\\python37.zip', 'C:\\Download\\Development\\NowaStrona_Django\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django\\lib', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts', 'c:\\program files (x86)\\python37-32\\Lib', 'c:\\program files (x86)\\python37-32\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django', 'C:\\Download\\Development\\NowaStrona_Django\\lib\\site-packages'] Server time: Tue, 21 Dec 2021 17:36:13 +0000 Error during template rendering In template C:\Download\Development\NowaStrona_Django\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name. 9 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} … -
Django groups, roles and permissions
I have a question: there's employee app in my project and I want employees to have different titles such as sales representative, manager and etc. and my views behave differently depending on employee's title. For now I have model Titles (title_code, title_name) but I feel like it could've been done with Django's builtin modules. So what do I use for building hierarchy? Groups, roles or permissions? -
Does django-ckeditor works with django-modeltranslation
I use django-modeltranslation to translate some text fields into several languagues. This works well. Now I want to implement django-ckeditor and this is working for not translated field as well. Problem is with fields which is translated (this fields are registered in translation.py). Does anybody using these two apps together? Is there something to do to get translated text fields working with ckeditor? -
Django database error while connecting sqllite
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 33, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
BaseQuerySet became empty after been as filter condition
official_template_ids became empty after been one of filter condition of SopTask official_template_ids = SopTemplate.objects.filter(draft_id=self.id, status=before_status).values_list('id', flat=True) print('official_template_ids', official_template_ids) # >>> official_template_ids <BaseQuerySet [371]> SopTask.objects.filter(template_id__in=official_template_ids, status=before_status).update(**update_kwargs) print('official_template_ids', official_template_ids) # >>> official_template_ids <BaseQuerySet []> -
Django chunked upload on apache2
I am using an django application using the [django chunked-upload][1]. It works locally, but on the apache server, it immediately interrupts. Do I need to add something to apache? Here my config file: <VirtualHost *:80> Alias /static /home/usr/app/static <Directory /home/usr/app/static> Require all granted </Directory> <Directory /home/usr/app/backend> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess app python-path=/home/usr/app python -home=/home/usr/app/appEnv WSGIProcessGroup app WSGIScriptAlias / /home/usr/app/backend/wsgi.py WSGIChunkedRequest On ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SetEnv proxy-sendchunked LogLevel info -
Sidebar's links don't work and the dropdown collapse
I've found a sideber that I'd like to use in my Django project, I was able to edit it to adjust it in the way I want but now I've two problems: The links don't work (for exemple here I'm trying to link to the user profile and nothing happen when the link is clicked) The sidebar dropdown: the dropdown works just fine but when I click one of the link in the sub menu (like Dashboard's "total" the dropdown collapse and it just closed itself) I'm not very good with the css and js stuff. Any help would be very appreciated! Thank you <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="https://unicons.iconscout.com/release/v3.0.6/css/line.css" rel="stylesheet"> <aside class="sidebar position-fixed top-0 left-0 overflow-auto h-100 float-left" id="show-side-navigation1"> <i class="uil-bars close-aside d-md-none d-lg-none" data-close="show-side-navigation1"></i> <div class="sidebar-header d-flex justify-content-center align-items-center px-3 py-4"> <div class="ms-2"> <h5 class="fs-6 mb-0"> <a class="text-decoration-none" href="#">User Name</a> </h5> <p class="mt-1 mb-0">user status</p> </div> </div> <ul class="categories list-unstyled"> <li class="has-dropdown"> <i class="uil-estate fa-fw"></i><a href="#"> Dashboard</a> <ul class="sidebar-dropdown list-unstyled"> <li><a href="#">Total</a></li> <li><a href="#">Partial</a></li> </ul> </li> <li class=""> <i class="uil-user"></i><a href="{% url 'user_profile' %}"> Profile</a> </li> <li class="has-dropdown"> <i class="uil-envelope fa-fw"></i><a href="#"> Inbox</a> <ul class="sidebar-dropdown list-unstyled"> <li><a href="#">Deleted</a></li> </ul> </li> <li class=""> <i class="uil-signout"></i><a href="#"> Logout</a> </li> … -
No module named 'rest_framework' on pythonanywhere.com
I'm trying to host my Django app on https://pythonanywhere.com I'm am getting the following error : ModuleNotFoundError: No module named 'rest_framework' I tried pip install djangorestframework pip3 install djangorestframework but its is still showing error. I also tried pip freeze and found djangorestframework==3.13.1 in the list. >>> import rest_framework also works fine. I ran my project locally and also it in a new virtual env, it worked fine. Installed same requirements.txt on pythonanywhere but still the same error. This is bugging me for a long time! please help here is my error log file: 2021-12-22 10:59:23,012: Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 556, in resolve for pattern in self.url_patterns: File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, …