Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keep getting "Page not found". What to do?
**Can someone please help me solve this problem I just started learning Django. I keep getting getting "PAGE NOT FOUND " whenever i open/click the list/entries In my "entries" folder i have Css.md Django.md Git.md Python.md HTML.md** urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry" views.py from django import forms class NewEntryForm(forms.Form): title = forms.CharField(max_length=100) content = forms.CharField(widget=forms.Textarea) def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, entry): entries = util.get_entry(entry) if entries is None: return render(request, "encyclopedia/error.html", { "message1": "Sorry", "message2": "your requested page was not found " }) return render(request, "encyclopedia/index.html", { "content": entries, "form": NewEntryForm }) index.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia - {{title}} {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href="{{entries}}"></a></li> {% endfor %} </ul> {% endblock %} entry.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia - {{title}} {% endblock %} {% block body %} <div class="container"> <div class="row"> {% if not content%} <div>Sorry, your requested page was not found </div> {% else %} {{ content | safe }} <div><a href="{% url 'edit' entry %}>Edit this entry</a></div> {% … -
no reverse math in django
in veiws.py def updateTask(request, pk): task = Tasks.objects.get(id=pk) return render(request, 'update.html') in urls.py urlpatterns = [ path('', views.index, name='list'), path("update_task/<str:pk>/", views.updateTask, name='update'), ] in templates : {% for task in tasks %} <div> <p> {{ task }}<p> <a href="{% url 'update_task' task.id %}">update</a> </div> {% endfor %} but i am receiving error of NoReverseMatch -
Why does django server startup fails after deprecation warning?
I installed django-dash library in my app and tried starting the server but I keep running into the below error during launch : Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\dash\models.py", line 10, in <module> from nine import versions File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\nine\versions.py", line 7, in <module> DeprecationWarning DeprecationWarning: The `nine` namespace is … -
send_email() Display attach in the mail
At the current stage the email is fully working, however, when receiving the actual mail the image is not attached, rather is name is displayed. I wold like to display che attachment in order to be able to download it. ''' def publication(request): if request.method == "POST": inputImmagine1 = request.POST['inputImmagine1'] send_mail( 'Richiesta di pubblicazione - Condoglianze', #subject inputImmagine1, #message inputEmail, # from email ['XXX@gmail.com'], # to email ) return render(request, 'publication.html', {'inputImmagine1': inputImmagine1}) else: return render(request, 'publication.html', {}) ''' -
How to customize SearchHeadline in django full text search?
I want to highlight search terms with SearchHeadline. My code is somethink like this: query = SearchQuery('cat') vector = SearchVector('caption') Post.objects.annotate( search=vector headline=SearchHeadline( 'caption', query ) ).filter(search=query) This code works well and for example the headline of the first result is: 'My <b>cat</b> breed is Persian. Persian cats are the most beautiful breed.' As you can see cat is highlighted but cats is not, and I want to highlight all of cat string in the caption, like this: 'My <b>cat</b> breed is Persian. Persian <b>cat</b>s are the most beautiful breed.' -
Django Migrating DB django.db.utils.ProgrammingError: relation "django_site" does not exist
Doing a site upgrade for Django, now pushing it to the server when I try python manage.py makemigrations I get this error (kpsga) sammy@kpsga:~/webapps/kpsga$ python manage.py makemigrations Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ The above exception was the direct cause of the following exception: ... File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/sammy/webapps/kpsga/kpsga/urls.py", line 27, in <module> path('blog', include('blog.urls')), ... File "/home/sammy/webapps/kpsga/blog/urls.py", line 2, in <module> from blog.views import LatestBlogEntries, blog_archive, blog_entry_by_id, blog_entry File "/home/sammy/webapps/kpsga/blog/views.py", line 10, in <module> class LatestBlogEntries(Feed): File "/home/sammy/webapps/kpsga/blog/views.py", line 11, in LatestBlogEntries current_site = Site.objects.get_current() File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/contrib/sites/models.py", line 58, in get_current return self._get_site_by_id(site_id) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/contrib/sites/models.py", line 30, in _get_site_by_id site = self.get(pk=site_id) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 425, in get num = len(clone) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 269, in __len__ self._fetch_all() File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return … -
Should I create an app for every page? (Django)
I'm new to Django. I am currently trying to bring my static html/css website to Django (mainly for learning). My only doubt is: should I use a new app for every page I have? The doubt comes from the fact that the title which I'll give to the pages are different, hence making page_title variable requires me to write in views.py, but I can't (maybe I'm wrong) write multiple page_title variables inside the same app's views.py. Thanks for your time! -
Django Filter SearchForm by a Category
My Django application has a search function. To give the user a more accurate search result its also possible to filter by a category before sending the search request. To get the Category object the user can select from at a drop-down menu, I have a form like this: class CategorySearchForm(forms.ModelForm): class Meta: model = Post fields = ['category'] def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(CategorySearchForm, self).__init__(*args, **kwargs) self.fields['category'].required = False self.fields['category'].empty_label = 'All Categories' Currently this is working but to me this is ugly as I reference my category objects by my Post model: category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) Now my Question: How can I get all Category objects at my CategorySearchForm directly by the Category model instead of the Post model? This is how my Category Model looks like: class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(verbose_name="Title", max_length=40, validators=[MinLengthValidator(5)]) description = models.TextField(verbose_name="Description", max_length=3000, validators=[MinLengthValidator(150)], blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title def publish(self): self.published_date = timezone.now() self.save() -
unsupported operand type(s) for +: 'QuerySet' and 'int'
models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nickname = models.CharField(max_length=50) user_test_point = models.IntegerField(default=0) views.py : def test_result(request): user_test_point = Profile.objects.values('user_test_point') test_word = request.GET['test_word'] test_mean = request.GET['mean'] flag = "flag" if test_mean == test_word: flag = "correct" Profile.objects.values('user_test_point').update(user_test_point + 1) context = {"flag": flag} return render(request, 'test_result.html', context) else: flag = "wrong" context = {"flag": flag} context['mean'] = test_mean return render(request, 'test_result.html', context) I created user_test_point in enter code heremodels.py. Then, I want to add point 1 if user's answer is correct. I wonder can I modify this code "Profile.objects.values('user_test_point').update(user_test_point + 1)"? I want to know how to fix this error "unsupported operand type(s) for +: 'QuerySet' and 'int'". -
Problem when trying to migrate from Django to Heroku
I am currently trying to deploy my Django project on to a free Heroku server. When I try to execute the following command I get an error heroku run python3 manage.py migrate. The error is as follows: Running python3 manage.py makemigrations on ⬢ samstaskmanager... up, run.5214 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, … -
Extracting particular columns of a specified row
Hello Guys i am new to this kindly help me out. I have a table like - now i want a button on click i should get names of all children for that my code is - views.py - def view(request): datas=Table.objects.all().values('Parent_Name').distinct() for data in datas: childrennames = datas.filter(Parent_name = data['Child_Name']).values('Child_Name') return render (request,'t.html',{'datas':datas},{'childnames':childnames}) html- {% for data in datas %} <li><span><button>{{data.parent_name}}</button></span> <ul class="nested"> <li><span><button>{{childrenname.child_name}}</button></span> <ul class="nested"> </ul> </li> </ul> </li> {% endfor %} but this is not working please help where am i wrong ? kindly ignore the capital and small letter issue in code. my Database is PostgresSQL. is the query fault or data base fault ? -
Problem in creating Login Function based on Custom ModelForm DB in Django
I didn't want to use Django's inbuilt form, so I made a ModelForm and I was able to implement registering a user based on my ModelForm. But now I want to login using the ModelForm DB to authenticate the user. Is there any way to make a custom authentication based on the ModelForm that I made? I have added code snippets of models.py, forms.py and views.py! hope its enough! models.py from django.db import models # Create your models here. LEVELS = [ ('AD', 'ADMIN'), ('VU', 'VIEW AND UNLOCK'), ('V', 'VIEW ONLY') ] class Clients(models.Model): name = models.CharField(max_length=200, null=True) phone = models.IntegerField(null=True) pswd = models.CharField(max_length=200, null=True) access_level = models.CharField(max_length=2, choices=LEVELS) def __str__(self): return self.name class Meta: verbose_name_plural = "Clients" forms.py from django import forms from django.forms import ModelForm from iot.models import Clients class Clientsform(ModelForm): class Meta: model = Clients fields = '__all__' widgets = {'name': forms.TextInput(attrs={'class': 'form-control', 'required': 'True'}), 'phone': forms.NumberInput(attrs={'class': 'form-control', 'required': 'True'}), 'pswd': forms.PasswordInput(attrs={'class': 'form-control', 'required': 'True'}), 'access_level': forms.Select(attrs={'class': 'form-control', 'required': 'True'})} views.py def register(request): form = Clientsform() if request.method == 'POST': form = Clientsform(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('name') messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form': form} return render(request, "form.html", context) … -
Iam Having This Error on Django Exception in thread Django-main-thread
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '3' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin ':' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin 'a' in CORS_ORIGIN_WHITELIST is missing scheme or … -
json.dumps return double quotes error in python
I am receiving this kind of json { a: {}, b: 'xyz', c: '1', d: 'hotel', e: '1', f: '1' } when i use json.dumps i receive double quote error. How to add double quote for keys in above json. -
database design for checkout and order table
I am designing a database for e-commerce. I am confused regarding the checkout and order table. I am not sure if I need to create separate order table when most of the things is already done on checkout table. Here is the design as of now class Product(ModelWithMetadata, PublishableModel): product_type = models.ForeignKey( ProductType, related_name="products", on_delete=models.CASCADE ) category = models.ForeignKey( Category, related_name="products", on_delete=models.SET_NULL, null=True, blank=True, ) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants") variant_attributes = models.ManyToManyField(VariantAttribute, related_name="productvariants") class Checkout(ModelWithMetadata): """A shopping checkout.""" created = models.DateTimeField(auto_now_add=True) last_change = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name="checkouts", on_delete=models.CASCADE, ) email = models.EmailField() token = models.UUIDField(primary_key=True, default=uuid4, editable=False) quantity = models.PositiveIntegerField(default=0) billing_address = models.ForeignKey( Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL ) shipping_address = models.ForeignKey( Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL ) shipping_method = models.ForeignKey( ShippingMethod, blank=True, null=True, related_name="checkouts", on_delete=models.SET_NULL, ) note = models.TextField(blank=True, default="") currency = models.CharField( max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH, default=settings.DEFAULT_CURRENCY, ) country = CountryField(default=get_default_country) discount_amount = models.DecimalField( max_digits=settings.DEFAULT_MAX_DIGITS, decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0, ) discount = MoneyField(amount_field="discount_amount", currency_field="currency") discount_name = models.CharField(max_length=255, blank=True, null=True) voucher_code = models.CharField(max_length=12, blank=True, null=True) # gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="checkouts") objects = CheckoutQueryset.as_manager() class Meta: ordering = ("-last_change", "pk") class CheckoutLine(models.Model): """A single checkout line. """ checkout = models.ForeignKey( Checkout, related_name="lines", on_delete=models.CASCADE ) variant = models.ForeignKey( … -
The view shop.views.product_list didn't return an HttpResponse object. It returned None instead
Here is my code , I am getting same error again and again. I dont know whats wrong here. category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request,'templates/shop/product/list.html',{'category':category,'categories':categories,'products':products}) -
JQuery AJAX with django getting csrf error 403
Getting Error CSRF verification failed. Request aborted. Missing or Incorrect Token. I am new to JQuery not sure if it is contributing to my error. I think I am passing the request properly. Cookies are accepted and a simpler JQuery request worked earlier. Views def testcall(request): text = request.POST['text'] if request.method == 'POST' and request.POST['action'] == 'start_function1': function1(text) response = text + "has been successful" return HttpResponse(response) if request.method == 'POST' and request.POST['action'] == 'start_function2': function2(text) response = text + "has been successful" return HttpResponse(response) Template <html> <head> <title>Test Data</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> jQuery(document).ready(function($){ $('demo-form').on('submit', function(event){ event.preventDefault(); var text = document.getElementById('text-to-analyze').value; $.ajax({ url : '{{ 'my-ajax-testsub/' }}', type : "POST", data: { csrfmiddlewaretoken: '{{ csrf_token }}', text: text, action: 'start_function1' }, success: function callback(response){ alert(response); }, }); })}) jQuery(document).ready(function($){ $('demo-form').on('submit', function(event){ event.preventDefault(); var text = document.getElementById('text-to-analyze').value; $.ajax({ url : '{{ 'my-ajax-testunsub/' }}', type : "POST", data: { csrfmiddlewaretoken: '{{ csrf_token }}', text: text, action: 'start_function2' }, success: function callback(response){ alert(response); }, }); })}) </script> </head> <body> <form name="demo-form" method="POST" action="{% url 'home' %}"> <p>Input field: <input type="text" id="text-to-analyze" value="name@gmail.com"></p><br> <button class="btn btn-success" name="start_function1">Function</button> <button class="btn btn-success" name="start_function2">Function</button> </form> </body> </html> -
Django web email client
How can I embed a web email client in Django App? The users in the systems should be able to send mails to each others. I have tried django messages but that is not the solutions I'm looking. -
Efficient Design of DB with several relations - Django
I want to know the most efficient way for structuring and designing a database with several relations. I will explain my problem with a toy example which is scaled up in my current situation Here are the Models in the Django database 1.) Employee Master (biggest table with several columns and rows) class Emp_Mast(): emp_mast_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) desgn_mast = models.ForeignKey("hr.Desgn_Mast", on_delete=models.SET_NULL, null=True) qual_mast = models.ForeignKey("hr.Qualification_Mast", on_delete=models.SET_NULL, null=True) office_mast = models.ManyToManyField("company_setup.Office_Mast", ref_mast = models.ForeignKey("hr.Reference_Mast", on_delete=models.SET_NULL, null=True) refernce_mast = models.ForeignKey("hr.Refernce_Mast", on_delete=models.SET_NULL, null=True) This is how the data is displayed in frontend 2.) All the relational field in the Employee Master have their corresponding models 3.) Crw_Movement_Transaction Now I need to create a table for Transaction Data that that stores each and every movement of the employees. We have several Offshore sites that the employees need to travel to and daily about 50 rows would be added to this Transaction Table called Crw_Movement_Transaction The Crw_Movement Table will have a few additional columns of calculations of itself and rest of the columns will be static (data would not be changed from here) and will be from the employee_master such as desgn_mast, souring_mast (so … -
Issue with connecting to MongoDB docker container with another container
Having an issue with connecting to a docker container to another container. I'm able to connect to it locally outside the container but from within the container doesn't work. This is the stack trace pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9cf7b6d9d395e79548d42a, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> My docker-compose.yml file is pretty straight forward and simple. Nothing unique mongod: restart: always image: mongo:latest volumes: - ./mongodb/mongod.conf:/etc/mongod.conf ports: - "27017:27017" command: mongod app: build: ./app container_name: django-gunicorn restart: always env_file: - ./app/django.env ports: - "8000:8000" command: "gunicorn --workers=2 --bind=0.0.0.0:8000 webapp.wsgi:application" I've binded the port to 0.0.0.0 in the mongod.conf. What else am I missing? -
How to filter and paginate in ListView Django
I have a problem when I want to paginate the filter that I create with django_filter, in my template it shows me the query set and filter but paginate does not work, I would like to know why this happens and if you could help me. I'll insert snippets of my code so you can see. This is my views.py PD: i have all the necesary imports. @method_decorator(staff_member_required, name='dispatch') class EmployeeListView(ListView): model = Employee paginate_by = 4 def dispatch(self, request, *args, **kwargs): if not request.user.has_perm('employee.view_employee'): return redirect(reverse_lazy('home')) return super(EmployeeListView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = EmployeeFilter(self.request.GET, queryset = self.get_queryset()) return context filters.py import django_filters from .models import Employee, Accident class EmployeeFilter(django_filters.FilterSet): class Meta: model = Employee fields = { 'rutEmployee' : ['startswith'] } and employee_list.html {% extends 'core/base.html' %} {% load bootstrap %} {% load static %} {% block title %}EMPLEADOS{% endblock %} {% block content %} <main role="main"> <div class="row"> <div class="col-md-12 stretch-card"> <div class="card"> <div class="card-body"> <p class="card-title">Lista de Empleados</p> <div class="table-responsive"> <form method="GET"> {{ filter.form|bootstrap }} <button type="submit" class="btn btn-primary">Filtrar</button> </form> <hr> <table class="table table-bordered"> <thead> <tr> <th>Rut</th> <th>Nombre</th> <th>Apellido Paterno</th> <th>Detalle</th> </tr> </thead> <tbody> {% for employee in filter.qs|dictsort:"id" reversed %} … -
Backend interfering with load times - Django
I am working on a project where a backend function in my Django project pulls data and then runs a data analysis on it. The issue I am encountering is that while this is happening the frontend shows a 404 error until the analysis is complete. As this will be client-facing is there a way to fix this without rewriting the analysis in Javascript? -
Django Video Wont Play How To Fix?
I am trying to load my basic video that I recored with gyazo but it wont load my video the video is a mp4 and the name is correct as well I loaded my {% static %} on top and made sure the video was in my static image file and in my setting is STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] correct as well I am not sure how to fix this problem this is how I load my videos from gyazo <video width="430" height="340" controls autoplay> <source src="{% static dam.mp4 %}" type="video/mp4"> </source> damcool </video> my full code <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Learn To Code</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> * { box-sizing: border-box; } body { font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } body {font-family: "Times New Roman", Georgia, Serif;} h1, h2, h3, h4, h5, h6 { font-family: "Playfair Display"; letter-spacing: 0px; color: white; } /* Style the header */ .header { background-color: #58D68D; padding: 10px; text-align: center; font-size: 35px; } /* Create three equal columns that floats next to each other */ .column { float: left; width: 73.33%; padding: 10px; … -
Javascript runs in template html file but not extended html file in Django application
I am writing a website in Django and Vanilla JS I have 2 html pages, I want them both to share css but I want them to use different javascript. Both pages extend a layout.html. The layout.html looks begins like this {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <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="{% static 'network/styles.css' %}" rel="stylesheet"> </head> My index.html (which extends my layout.html) begins like this {% extends "network/layout.html" %} {% load static %} <script src="{% static 'network/messages.js' %}"></script> and my Javascript file looks like this: document.addEventListener('DOMContentLoaded', function() { console.log("page loaded!") document.addEventListener('click', event => { const element = event.target; console.log("Something was clicked") }) }); It simply prints out a line when the page is loaded and when something is clicked. However, when I go to index.html with the code like this, the javascript file is not loaded, nothing is printed out when the page is loaded or when anything is clicked. However, if I modify the layout.html page to be like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <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="{% static 'network/styles.css' %}" … -
SMTPSenderRefused at /accounts/signup/
I tried to configure sending email on registration using gmail server and i get these error: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError u2sm3847520edr.70 - gsmtp', 'webmaster@localhost'). These are my configurations in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')