Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /polls/1/ in Django 4.0
I am learning Django from the official documentation, and getting this error: NoReverseMatch at /polls/1/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/\\Z'] Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Django Version: 4.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/\\Z'] These are my urlpatterns: urlpatterns = [ path('', views.index, name='polls'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/result/', views.result, name='result'), path('<int:question_id>/vote/', views.vote, name='vote'), ] View.py File: def index(request): latest_questions = Question.objects.order_by('-pub_date') return render(request, 'polls/index.html', {'latest_questions': latest_questions}) def detail(request, question_id): detail = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'detail': detail}) def result(request, question_id): return HttpResponse("This is the result for question no. %s" % question_id) def vote(request, question_id): return HttpResponse("You are voting for question %s" % question_id) And this is where the problem lies on detail.html: <form action="{% url 'vote' question.id %}" method="post"> -
Django AppConfig ready()
I have Django 2.1.7 I read Django documentation as well as, this How to use django AppConfig.ready() and this Overriding AppConfig.ready(). Now, the folder/file structure is like this, my_app __init__.py urls.py sub_app1 migrations __init__.py admin.py apps.py models.py ... sub_app2 ... sub_app3 ... and all sub_apps are registered into INSTALLED_APPS of Django settings.py file as my_app.sub_app1 for example. I noticed that when I try to override ready()for sub_app1 w/in sub_app1.apps.py, overriding has no effect. When I flatten my structure above as my_app __init__.py urls.py apps.py overriding of ready works fine. In other words, it seems that overriding of readyof a sub app w/in sub app's apps.py doesn't work. Also, whether using default_app_config w/in sub app's __init__.py or my_app.sub_app1.apps.SubApp1Config w/in settings.py INSTALLED_APPS it gives error django.core.exceptions.ImproperlyConfigured: Cannot import 'sub_app1'. Check that 'my_app.sub_app1.apps.SubApp1Config.name' is correct. Why is this happening? -
Compose template variable with another template in Django
I'm trying to dynamically get a template variable in an html file. Depending on the particular file loaded i'm having some things passed in the context: prefix, a string which for sake of the example may be "foo" or "bar" foo_conf bar_conf Both foo_conf and bar_conf have the attribute timestamp. The non-working code I've written is the following: <div class="col-12">Configuration: {{ prefix|add:'_conf.timestamp'|time }}</div> What I want to do is so take the value of the variable foo_conf.timestamp or bar_conf.timestamp and pass it to the "time" filter, displaying the result. But with the code I've written, the string "bar_conf.timestamp" (or foo_conf.timestamp") is passed to the "time" filter, which of course throws an exception being designed to work with time objects, not strings. How can I achieve the desired behaviour? Thanks in advance. -
ImportError: No module named south.v2 but I have installed v2
I am running django 1.2 on a windows 10. I created a virtual environment and cloned my repository from github. I try to migrate ./manage.py migrate and I get the error: ImportError: No module named v2 I have checked similar problems but they don't work on my project. ! Migration assist:0332_alias_crawl_from probably doesn't exist. Traceback: Traceback (most recent call last): File "manage.py", line 6, in execute_manager(conf) File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management_init_.py", line 438, in execute_manager utility.execute() File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management_init_.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management\base.py", line 191, in run_from_argv self.execute(*args, **options.dict) File "D:\workspace\Fix python\web\venv2\lib\site-packages\django\core\management\base.py", line 218, in execute output = self.handle(*args, **options) File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\management\commands\migrate.py", line 79, in handle tree = migration.dependency_tree() File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\migration.py", line 117, in dependency_tree tree = all_migrations() File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\migration.py", line 112, in all_migrations for app in get_migrated_apps() File "D:\workspace\Fix python\web\venv2\lib\site-packages\south\migration.py", line 94, in get_migration module = import(app.name + "." + name, '', '', ['Migration']) File "D:\workspace\Fix python\web\assist\migrations\0332_alias_crawl_from.py", line 4, in from south.v2 import SchemaMigration ImportError: No module named v2 Here are my pip freeze list ''' amqp 1.0.13 amqplib 0.6.1 anyjson 0.3.3 beatbox 16.1 BeautifulSoup 3.2.0 billiard 2.7.3.34 carrot 0.10.7 celery 3.0.22 contextlib2 0.6.0.post1 Django 1.2 django-basic-apps 0.7 django-celery 2.5.0 django-filebrowser 3.2 django-mobileadmin 0.5.2 … -
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.